This repository has been archived by the owner on Oct 24, 2022. It is now read-only.
/
robot.py
353 lines (262 loc) · 10.5 KB
/
robot.py
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# Copyright Robert Spanton 2014
import json
import sys
import optparse
import os
import glob
import logging
import pyudev
import smbus
from sr.robot.thunderborg import ThunderBorgBoard, BlackJackBoardPWM, BlackJackBoardGPIO
from sr.robot import power, ruggeduino, vision
logger = logging.getLogger("sr.robot")
def setup_logging():
"""Apply default settings for logging"""
# (We do this by default so that our users
# don't have to worry about logging normally)
logger.setLevel(logging.INFO)
h = logging.StreamHandler(sys.stdout)
h.setLevel(logging.INFO)
fmt = logging.Formatter("%(message)s")
h.setFormatter(fmt)
logger.addHandler(h)
class NoCameraPresent(Exception):
"""Camera not connected."""
def __str__(self):
return "No camera found."
class AlreadyInitialised(Exception):
"""The robot has been initialised twice"""
def __str__(self):
return "Robot object can only be initialised once."
class UnavailableAfterInit(Exception):
"""The called function is unavailable after init()"""
def __str__(self):
return "The called function is unavailable after init()"
def pre_init(f):
"""Decorator for functions that may only be called before init()"""
def g(self, *args, **kw):
if self._initialised:
raise UnavailableAfterInit()
return f(self, *args, **kw)
return g
class Robot(object):
"""Class for initialising and accessing robot hardware"""
SYSLOCK_PATH = "/tmp/robot-object-lock"
def __init__(self,
quiet=False,
init=True,
config_logging=True):
if config_logging:
setup_logging()
self._initialised = False
self._quiet = quiet
# TODO: Re-enable the lock after mangling herdsman etc to support it
# self._acquire_syslock()
self._parse_cmdline()
self._ruggeduino_id_handlers = {}
self._ruggeduino_fwver_handlers = {"SRduino": ruggeduino.Ruggeduino}
bus = smbus.SMBus(1)
self.gpio = BlackJackBoardGPIO(bus)
if init:
self.init(bus)
self.wait_start()
@classmethod
def setup(cls, quiet=False, config_logging=True):
if config_logging:
setup_logging()
logger.debug("Robot.setup( quiet = %s )", str(quiet))
return cls(init=False,
quiet=quiet,
# Logging is already configured
config_logging=False)
def init(self, bus):
# Find and initialise hardware
if self._initialised:
raise AlreadyInitialised()
logger.info("Initialising hardware.")
self._init_devs(bus)
self._init_vision()
if not self._quiet:
self._dump_devs()
self._initialised = True
def off(self):
for motor in self.motors:
motor.off()
def _acquire_syslock(self):
try:
# Create the file
self._syslock = os.open(self.SYSLOCK_PATH, os.O_CREAT | os.O_EXCL)
except OSError:
raise Exception("Robot lock could not be acquired. Have you created more than one Robot() object?")
def _dump_devs(self):
"""Write a list of relevant devices out to the log"""
logger.info("Found the following devices:")
self._dump_power()
self._dump_usbdev_dict(self.ruggeduinos, "Ruggeduinos")
self._dump_webcam()
def _dump_webcam(self):
"""Write information about the webcam to stdout"""
if not hasattr(self, "vision"):
# No webcam
return
# For now, just display the fact we have a webcam
logger.info(" - Webcam")
def _dump_power(self):
"""Write information about the power board to stdout"""
if self.power is None:
# No power board!
return
logger.info(" - {0}".format(self.power))
def _dump_usbdev_dict(self, devdict, name):
"""Write the contents of a device dict to stdout"""
if len(devdict) == 0:
return
logger.info(" - %s:", name)
for key, motor in devdict.iteritems():
if not isinstance(key, int):
continue
logger.info(" %(index)s: %(motor)s",
{"index": key, "motor": motor})
def _parse_cmdline(self):
"""Parse the command line arguments"""
parser = optparse.OptionParser()
parser.add_option("--usbkey", type="string", dest="usbkey",
help="The path of the (non-volatile) user USB key")
parser.add_option("--startfifo", type="string", dest="startfifo",
help="The path of the fifo which start information will be received through")
(options, args) = parser.parse_args()
self.usbkey = options.usbkey
self.startfifo = options.startfifo
def wait_start(self):
"""Wait for the start signal to happen"""
logger.info("Waiting for start signal.")
f = open(self.startfifo, "r")
d = f.read()
f.close()
j = json.loads(d)
for prop in ["zone", "mode", "arena"]:
if prop not in j:
raise Exception("'{}' must be in startup info".format(prop))
setattr(self, prop, j[prop])
if self.mode not in ["comp", "dev"]:
raise Exception("mode of '%s' is not supported -- must be 'comp' or 'dev'" % self.mode)
if self.zone < 0 or self.zone > 3:
raise Exception("zone must be in range 0-3 inclusive -- value of %i is invalid" % self.zone)
if self.arena not in ["A", "B"]:
raise Exception("arena must be A or B")
@pre_init
def ruggeduino_set_handler_by_id(self, r_id, handler):
logger.debug("Ruggeduino handler set for ID '%s'", r_id)
self._ruggeduino_id_handlers[r_id] = handler
@pre_init
def ruggeduino_set_handler_by_fwver(self, fwver, handler):
logger.debug("Ruggeduino handler set for firmware version '%s'", fwver)
self._ruggeduino_fwver_handlers[fwver] = handler
@pre_init
def ruggeduino_ignore_id(self, r_id):
"""Ignore the Ruggeduino with the given ID"""
logger.debug("Ruggeduino ID '%s' set to be ignored", r_id)
self.ruggeduino_set_handler_by_id(r_id, ruggeduino.IgnoredRuggeduino)
def _init_devs(self, bus):
"""Initialise the attributes for accessing devices"""
# Power board
self._init_power()
# Motor boards
self._init_motors()
# Servo boards
self._init_servos(bus)
# Ruggeduinos
self._init_ruggeduinos()
def _init_power(self):
boards = self._init_usb_devices("Power_board_v4", power.Power)
if len(boards):
self.power = boards[0]
# Bring the rails up
# In the future we will do something more complicated here
for x in range(6):
self.power.output[x] = True
else:
self.power = None
def _init_motors(self):
self.motors = {}
for i, addr in enumerate([0x14, 0x15, 0x16, 0x17]):
try:
self.motors[i] = ThunderBorgBoard(addr)
except Exception:
pass
def _init_servos(self, bus):
self.servos = BlackJackBoardPWM(bus)
def _init_ruggeduinos(self):
self.ruggeduinos = {}
for n, dev in enumerate(self._list_usb_devices("Ruggeduino", subsystem="tty")):
handler = None
snum = dev["ID_SERIAL_SHORT"]
if snum in self._ruggeduino_id_handlers:
handler = self._ruggeduino_id_handlers[snum]
else:
# There's no ID-specific handler, so we can query it for
# its firmware version.
r = ruggeduino.RuggeduinoCmdBase(dev.device_node)
ver = r.firmware_version_read()
genre = ver.split(":")[0]
if genre in self._ruggeduino_fwver_handlers:
handler = self._ruggeduino_fwver_handlers[genre]
if handler is None:
raise Exception("No handler found for ruggeduino: serial {0}, firmware '{1}'".format(snum, genre))
srdev = handler(dev.device_node, snum)
self.ruggeduinos[n] = srdev
self.ruggeduinos[snum] = srdev
def _list_usb_devices(self, model, subsystem=None):
"""Create a sorted list of USB devices of the given type"""
udev = pyudev.Context()
devs = list(udev.list_devices(ID_MODEL=model, subsystem=subsystem))
# Sort by serial number
devs.sort(key=lambda x: x["ID_SERIAL_SHORT"])
return devs
def _init_usb_devices(self, model, ctor, subsystem=None):
devs = self._list_usb_devices(model, subsystem)
# Devices stored in a dictionary
# Each device appears twice in this dictionary:
# 1. Under its serial number
# 2. Under an integer key. Integers assigned by ordering
# boards by serial number.
srdevs = {}
n = 0
for dev in devs:
serialnum = dev["ID_SERIAL_SHORT"]
if "BUSNUM" in dev:
srdev = ctor(dev.device_node,
busnum=int(dev["BUSNUM"]),
devnum=int(dev["DEVNUM"]),
serialnum=serialnum)
else:
srdev = ctor(dev.device_node,
busnum=None,
devnum=None,
serialnum=serialnum)
srdevs[n] = srdev
srdevs[serialnum] = srdev
n += 1
return srdevs
def _init_vision(self):
# Find libkoki.so:
libpath = None
if "LD_LIBRARY_PATH" in os.environ:
for d in os.environ["LD_LIBRARY_PATH"].split(":"):
l = glob.glob("%s/libkoki.so*" % os.path.abspath(d))
if len(l):
libpath = os.path.abspath(d)
break
if libpath is None:
v = vision.Vision("/root/libkoki/lib")
else:
v = vision.Vision(libpath)
self.vision = v
def see(self, res=(640, 480), stats=False, save=True):
if not hasattr(self, "vision"):
raise NoCameraPresent()
return self.vision.see(res=res,
mode=self.mode,
arena=self.arena,
stats=stats,
save=save)