Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/butiaAPI.py
blob: 4bb6ca38b61a0c52d63d7f772a4f64f25ca8ea4e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# ButiaAPI
# Copyright (c) 2009, 2010, 2011, 2012 Butiá Team butia@fing.edu.uy
# Butia is a free open plataform for robotics projects
# www.fing.edu.uy/inco/proyectos/butia
# Facultad de Ingenieria - Universidad de la República - Uruguay
#
# Implements abstractions for the comunications with the bobot-server
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import socket
import string
import math
import threading

ERROR_SENSOR_READ = -1

BUTIA_1 = 20

BOBOT_HOST = 'localhost'
BOBOT_PORT = 2009

class robot:
    

    def __init__(self, host = BOBOT_HOST, port = BOBOT_PORT):
        """
        init the robot class
        """
        self.lock = threading.Lock()
        self.host = host
        self.port = port
        self.client = None
        self.fclient = None
        self.ver = BUTIA_1
        self.reconnect()
        self.getVersion()

       
    def doCommand(self, msg):
        """
        Executes a command in butia.
        @param msg message to be executed
        """
        msg = msg +'\n'
        ret = ERROR_SENSOR_READ
        self.lock.acquire()
        try:
            self.client.send(msg)
            ret = self.fclient.readline()
            ret = ret[:-1]
        except:
            ret = ERROR_SENSOR_READ # Doesn't return here to release the lock
        self.lock.release()
        
        if ((ret == 'nil value') or (ret == None) or (ret == 'fail') or (ret == 'missing driver')):
            ret = ERROR_SENSOR_READ
        return ret
          
    # connect o reconnect the bobot
    def reconnect(self):
        self.close()
        try:
            self.client = socket.socket()
            self.client.connect((self.host, self.port))
            self.fclient = self.client.makefile()
            msg = 'INIT'
            #bobot server instance is running, but we have to check for new or remove hardware
            self.doCommand(msg)
        except:
            return ERROR_SENSOR_READ
        return 0

    # ask bobot for refresh is state of devices connected
    def refresh(self):
        if (self.ver == BUTIA_1) or (self.ver == ERROR_SENSOR_READ):
            msg = 'INIT'
        else:
            msg = 'REFRESH'
        return self.doCommand(msg)

    # close the comunication with the bobot
    def close(self):
        try:
            if self.fclient != None:
                self.fclient.close()
                self.fclient = None
            if self.client != None:
                self.client.close()
                self.client = None
        except:
            return ERROR_SENSOR_READ
        return 0

    #######################################################################
    ### Operations to the principal module
    #######################################################################


    # call the module 'modulename'
    def callModule(self, modulename, function , params = ''):
        msg = 'CALL ' + modulename + ' ' + function
        if params != '' :
            msg += ' ' + params
        ret = self.doCommand(msg)
        try:
            ret = int(ret)
        except:
            ret = ERROR_SENSOR_READ
        return ret

    # Close bobot service
    def closeService(self):
        msg = 'QUIT'
        return self.doCommand(msg)

    #######################################################################
    ### Useful functions
    #######################################################################

    # returns if the module_name is present
    def isPresent(self, module_name):
        module_list = self.get_modules_list()
        return (module_name in module_list)

    # returns a list of modules
    def get_modules_list(self):
        msg = 'LIST'
        l = []
        ret = self.doCommand(msg)
        if not (ret == '' or ret == ERROR_SENSOR_READ):
            l = ret.split(',')
        return l

    # loopBack: send a message to butia and wait to recibe the same
    def loopBack(self, data):
        msg = 'lback send ' + data
        ret = self.doCommand(msg)
        if ret != -1 :
            msg = 'CALL lback read'
            return self.doCommand(msg)
        else:
            return ERROR_SENSOR_READ
            

    #######################################################################
    ### Operations for motores.lua driver
    #######################################################################

    def set2MotorSpeed(self, leftSense = '0', leftSpeed = '0', rightSense = '0', rightSpeed = '0'):
        msg = leftSense + ' ' + leftSpeed + ' ' + rightSense + ' ' + rightSpeed
        if self.ver == BUTIA_1:
            return self.callModule('motores', 'setvel2mtr', msg)
        else:
            return self.callModule('motors', 'setvel2mtr', msg)
     
    def setMotorSpeed(self, idMotor = '0', sense = '0', speed = '0'):
        msg = idMotor + ' ' + sense + ' ' + speed
        if self.ver == BUTIA_1:
            return self.callModule('motores', 'setvelmtr', msg)
        else:
            return self.callModule('motors', 'setvelmtr', msg)

    #######################################################################
    ### Operations for ax.lua driver
    #######################################################################

    def wheel_mode(self, idMotor = '0'):
        msg = idMotor
        if self.ver == BUTIA_1:
            return self.callModule('ax', 'wheel_mode', msg) ##TODO implement
        else:
            return self.callModule('ax', 'wheel_mode', msg)
     
    def joint_mode(self, idMotor = '0', min = '0', max = '1023'):
        msg = idMotor + ' ' + min + ' ' + max
        if self.ver == BUTIA_1:
            return self.callModule('ax', 'joint_mode', msg) ##TODO implement
        else:
            return self.callModule('ax', 'joint_mode', msg)

    def set_speed(self, idMotor = '0', speed = '0'):
        msg = idMotor + ' ' + speed
        if self.ver == BUTIA_1:
            return self.callModule('ax', 'set_speed', msg) ##TODO implement
        else:
            return self.callModule('ax', 'set_speed', msg)

    def set_position(self, idMotor = '0', pos = '0'):
        msg = idMotor + ' ' + pos
        if self.ver == BUTIA_1:
            return self.callModule('ax', 'set_position', msg) ##TODO implement
        else:
            return self.callModule('ax', 'set_position', msg)

    def get_position(self, idMotor = '0'):
        msg = idMotor
        if self.ver == BUTIA_1:
            return self.callModule('ax', 'get_position', msg) ##TODO implement
        else:
            return self.callModule('ax', 'get_position', msg)



    #######################################################################
    ### Operations for butia.lua driver
    #######################################################################

    def ping(self):
        return self.callModule('placa', 'ping')

    # returns the approximate charge of the battery
    def getBatteryCharge(self):
        return self.callModule('butia', 'get_volt')

    # returns the firmware version
    def getVersion(self):
        ver = self.callModule('butia', 'read_ver')
        if not(ver == ERROR_SENSOR_READ):
            self.ver = ver
        return ver
    
    # set de motor idMotor on determinate angle
    def setPosition(self, idMotor = 0, angle = 0):
        msg = str(idMotor) + ' ' + str(angle)
        return self.callModule('placa', 'setPosicion' , msg )
    
    # return the value of button: 1 if pressed, 0 otherwise
    def getButton(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('boton' + str(number), 'getValue')
        else:
            return self.callModule('button:' + str(number), 'getValue')

    # return the value en ambient light sensor
    def getAmbientLight(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('luz' + str(number), 'getValue')
        else:
            return self.callModule('light:' + str(number), 'getValue')

    # return the value of the distance sensor
    def getDistance(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('dist' + str(number), 'getValue')
        else:
            return self.callModule('distanc:' + str(number), 'getValue')
    
    # return the value of the grayscale sensor
    def getGrayScale(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('grises' + str(number), 'getValue')
        else:
            return self.callModule('grey:' + str(number), 'getValue')

    # return the value of the temperature sensor
    def getTemperature(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('temp' + str(number), 'getValue')
        else:
            return self.callModule('temp:' + str(number), 'getValue')

    # return the value of the vibration sensor
    def getVibration(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('vibra' + str(number), 'getValue')
        else:
            return self.callModule('vibra:' + str(number), 'getValue')

    # return the value of the resistance sensor
    def getResistance(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('resist' + str(number), 'getValue') #TODO implement
        else:
            return self.callModule('resist:' + str(number), 'getValue')

    # return the value of the tilt sensor
    def getTilt(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('tilt' + str(number), 'getValue')
        else:
            return self.callModule('tilt:' + str(number), 'getValue')

    # FIXME: the name of the module and the function...
    # return the value of the capacitive touch sensor
    def getCapacitive(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('capacitive' + str(number), 'getValue')
        else:
            return self.callModule('capacitive:' + str(number), 'getValue')

    # return the value of the magnetic induction sensor
    def getMagneticInduction(self, number=''):
        if self.ver == BUTIA_1:
            return self.callModule('magnet' + self.aux + str(number), 'getValue')
        else:
            return self.callModule('magnet:' + self.aux + str(number), 'getValue')

    # set the led intensity
    def setLed(self, nivel = 255, number= ''):
        if self.ver == BUTIA_1:
            return self.callModule('led' + self.aux + str(number), 'setLight', str(math.trunc(nivel)))
        else:
            return self.callModule('led:' + self.aux + str(number), 'setLight', str(math.trunc(nivel)))

    # FIXME: check the lenght of text?
    # write a text in LCD display
    def writeLCD(self, text):
        text = str(text)
        text = text.replace(' ', '_')
        self.callModule('display', 'escribir' , text)