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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387 | # -----------------------------------------------------------------------------
# Copyright (c) 2015 Ralph Hempel <rhempel@hempeldesigngroup.com>
# Copyright (c) 2015 Anton Vanhoucke <antonvh@gmail.com>
# Copyright (c) 2015 Denis Demidov <dennis.demidov@gmail.com>
# Copyright (c) 2015 Eric Pascual <eric@pobot.org>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# -----------------------------------------------------------------------------
import sys
import os
import io
import fnmatch
import re
import stat
import errno
from os.path import abspath
try:
# if we are in a released build, there will be an auto-generated "version"
# module
from .version import __version__
except ImportError:
__version__ = "<unknown>"
if sys.version_info < (3, 4):
raise SystemError('Must be using Python 3.4 or higher')
def is_micropython():
return sys.implementation.name == "micropython"
def chain_exception(exception, cause):
if is_micropython():
raise exception
else:
raise exception from cause
def get_current_platform():
"""
Look in /sys/class/board-info/ to determine the platform type.
This can return 'ev3', 'evb', 'pistorms', 'brickpi', 'brickpi3' or 'fake'.
"""
board_info_dir = '/sys/class/board-info/'
if not os.path.exists(board_info_dir) or os.environ.get("FAKE_SYS"):
return 'fake'
for board in os.listdir(board_info_dir):
uevent_filename = os.path.join(board_info_dir, board, 'uevent')
if os.path.exists(uevent_filename):
with open(uevent_filename, 'r') as fh:
for line in fh.readlines():
(key, value) = line.strip().split('=')
if key == 'BOARD_INFO_MODEL':
if value == 'LEGO MINDSTORMS EV3':
return 'ev3'
elif value in ('FatcatLab EVB', 'QuestCape'):
return 'evb'
elif value == 'PiStorms':
return 'pistorms'
# This is the same for both BrickPi and BrickPi+.
# There is not a way to tell the difference.
elif value == 'Dexter Industries BrickPi':
return 'brickpi'
elif value == 'Dexter Industries BrickPi3':
return 'brickpi3'
elif value == 'FAKE-SYS':
return 'fake'
return None
# -----------------------------------------------------------------------------
def list_device_names(class_path, name_pattern, **kwargs):
"""
This is a generator function that lists names of all devices matching the
provided parameters.
Parameters:
class_path: class path of the device, a subdirectory of /sys/class.
For example, '/sys/class/tacho-motor'.
name_pattern: pattern that device name should match.
For example, 'sensor*' or 'motor*'. Default value: '*'.
keyword arguments: used for matching the corresponding device
attributes. For example, address='outA', or
driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value
is a list, then a match against any entry of the list is
enough.
"""
if not os.path.isdir(class_path):
return
def matches(attribute, pattern):
try:
with io.FileIO(attribute) as f:
value = f.read().strip().decode()
except Exception:
return False
if isinstance(pattern, list):
return any([value.find(p) >= 0 for p in pattern])
else:
return value.find(pattern) >= 0
for f in os.listdir(class_path):
if fnmatch.fnmatch(f, name_pattern):
path = class_path + '/' + f
if all([matches(path + '/' + k, kwargs[k]) for k in kwargs]):
yield f
def library_load_warning_message(library_name, dependent_class):
return 'Import warning: Failed to import "{}". {} will be unusable!'.format(library_name, dependent_class)
class DeviceNotFound(Exception):
pass
class DeviceNotDefined(Exception):
pass
class ThreadNotRunning(Exception):
pass
# -----------------------------------------------------------------------------
# Define the base class from which all other ev3dev classes are defined.
class Device(object):
"""The ev3dev device base class"""
__slots__ = [
'_path',
'_device_index',
'_attr_cache',
'kwargs',
]
DEVICE_ROOT_PATH = '/sys/class'
_DEVICE_INDEX = re.compile(r'^.*(\d+)$')
def __init__(self, class_name, name_pattern='*', name_exact=False, **kwargs):
"""Spin through the Linux sysfs class for the device type and find
a device that matches the provided name pattern and attributes (if any).
Parameters:
class_name: class name of the device, a subdirectory of /sys/class.
For example, 'tacho-motor'.
name_pattern: pattern that device name should match.
For example, 'sensor*' or 'motor*'. Default value: '*'.
name_exact: when True, assume that the name_pattern provided is the
exact device name and use it directly.
keyword arguments: used for matching the corresponding device
attributes. For example, address='outA', or
driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value
is a list, then a match against any entry of the list is
enough.
Example::
d = ev3dev.Device('tacho-motor', address='outA')
s = ev3dev.Device('lego-sensor', driver_name=['lego-ev3-us', 'lego-nxt-us'])
If there was no valid connected device, an error is thrown.
"""
classpath = abspath(Device.DEVICE_ROOT_PATH + '/' + class_name)
self.kwargs = kwargs
self._attr_cache = {}
def get_index(file):
match = Device._DEVICE_INDEX.match(file)
if match:
return int(match.group(1))
else:
return None
if name_exact:
self._path = classpath + '/' + name_pattern
self._device_index = get_index(name_pattern)
else:
try:
name = next(list_device_names(classpath, name_pattern, **kwargs))
self._path = classpath + '/' + name
self._device_index = get_index(name)
except StopIteration:
self._path = None
self._device_index = None
chain_exception(DeviceNotFound("%s is not connected." % self), None)
def __str__(self):
if 'address' in self.kwargs:
return "%s(%s)" % (self.__class__.__name__, self.kwargs.get('address'))
else:
return self.__class__.__name__
def __repr__(self):
return self.__str__()
# This allows us to sort lists of Device objects
def __lt__(self, other):
return str(self) < str(other)
def _attribute_file_open(self, name):
path = os.path.join(self._path, name)
mode = stat.S_IMODE(os.stat(path)[stat.ST_MODE])
r_ok = mode & stat.S_IRGRP
w_ok = mode & stat.S_IWGRP
if r_ok and w_ok:
mode_str = 'r+'
elif w_ok:
mode_str = 'w'
else:
mode_str = 'r'
return io.FileIO(path, mode_str)
def _get_attribute(self, attribute, name):
"""Device attribute getter"""
try:
if attribute is None:
attribute = self._attribute_file_open(name)
else:
attribute.seek(0)
return attribute, attribute.read().strip().decode()
except Exception as ex:
self._raise_friendly_access_error(ex, name, None)
def _set_attribute(self, attribute, name, value):
"""Device attribute setter"""
try:
if attribute is None:
attribute = self._attribute_file_open(name)
else:
attribute.seek(0)
if isinstance(value, str):
value = value.encode()
attribute.write(value)
attribute.flush()
except Exception as ex:
self._raise_friendly_access_error(ex, name, value)
return attribute
def _raise_friendly_access_error(self, driver_error, attribute, value):
if not isinstance(driver_error, OSError):
raise driver_error
driver_errorno = driver_error.args[0] if is_micropython() else driver_error.errno
if driver_errorno == errno.EINVAL:
if attribute == "speed_sp":
try:
max_speed = self.max_speed
except (AttributeError, Exception):
chain_exception(ValueError("The given speed value {} was out of range".format(value)), driver_error)
else:
chain_exception(
ValueError("The given speed value {} was out of range. Max speed: +/-{}".format(
value, max_speed)), driver_error)
chain_exception(ValueError("One or more arguments were out of range or invalid, value {}".format(value)),
driver_error)
elif driver_errorno == errno.ENODEV or driver_errorno == errno.ENOENT:
# We will assume that a file-not-found error is the result of a disconnected device
# rather than a library error. If that isn't the case, at a minimum the underlying
# error info will be printed for debugging.
chain_exception(DeviceNotFound("%s is no longer connected" % self), driver_error)
raise driver_error
def get_attr_int(self, attribute, name):
attribute, value = self._get_attribute(attribute, name)
return attribute, int(value)
def get_cached_attr_int(self, filehandle, keyword):
value = self._attr_cache.get(keyword)
if value is None:
(filehandle, value) = self.get_attr_int(filehandle, keyword)
self._attr_cache[keyword] = value
return (filehandle, value)
def set_attr_int(self, attribute, name, value):
return self._set_attribute(attribute, name, str(int(value)))
def set_attr_raw(self, attribute, name, value):
return self._set_attribute(attribute, name, value)
def get_attr_string(self, attribute, name):
return self._get_attribute(attribute, name)
def get_cached_attr_string(self, filehandle, keyword):
value = self._attr_cache.get(keyword)
if value is None:
(filehandle, value) = self.get_attr_string(filehandle, keyword)
self._attr_cache[keyword] = value
return (filehandle, value)
def set_attr_string(self, attribute, name, value):
return self._set_attribute(attribute, name, value)
def get_attr_line(self, attribute, name):
return self._get_attribute(attribute, name)
def get_attr_set(self, attribute, name):
attribute, value = self.get_attr_line(attribute, name)
return attribute, [v.strip('[]') for v in value.split()]
def get_cached_attr_set(self, filehandle, keyword):
value = self._attr_cache.get(keyword)
if value is None:
(filehandle, value) = self.get_attr_set(filehandle, keyword)
self._attr_cache[keyword] = value
return (filehandle, value)
def get_attr_from_set(self, attribute, name):
attribute, value = self.get_attr_line(attribute, name)
for a in value.split():
v = a.strip('[]')
if v != a:
return v
return ""
@property
def device_index(self):
return self._device_index
def list_devices(class_name, name_pattern, **kwargs):
"""
This is a generator function that takes same arguments as `Device` class
and enumerates all devices present in the system that match the provided
arguments.
Parameters:
class_name: class name of the device, a subdirectory of /sys/class.
For example, 'tacho-motor'.
name_pattern: pattern that device name should match.
For example, 'sensor*' or 'motor*'. Default value: '*'.
keyword arguments: used for matching the corresponding device
attributes. For example, address='outA', or
driver_name=['lego-ev3-us', 'lego-nxt-us']. When argument value
is a list, then a match against any entry of the list is
enough.
"""
classpath = abspath(Device.DEVICE_ROOT_PATH + '/' + class_name)
return (Device(class_name, name, name_exact=True) for name in list_device_names(classpath, name_pattern, **kwargs))
|