Skip to content

Commit bbd9631

Browse files
authored
Micropython support (ev3dev#514)
Motors and sensors now support Micropython. CI server updated to run both CPython and Micropython builds.
1 parent b5e658a commit bbd9631

7 files changed

Lines changed: 82 additions & 33 deletions

File tree

‎.travis.yml‎

Lines changed: 15 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,32 @@
11
language: python
2+
env:
3+
- USE_MICROPYTHON=false
4+
- USE_MICROPYTHON=true
25
python:
36
- 3.4
4-
cache: pip
7+
cache:
8+
pip: true
9+
directories:
10+
- ~/micropython
11+
- ~/.micropython
512
sudo: false
613
git:
714
depth: 100
815
install:
9-
- pip install Pillow Sphinx sphinx_bootstrap_theme recommonmark evdev==1.0.0
10-
- pip install -r ./docs/requirements.txt
16+
- if [ $USE_MICROPYTHON = false ]; then pip install Pillow Sphinx sphinx_bootstrap_theme recommonmark evdev==1.0.0 && pip install -r ./docs/requirements.txt; fi
17+
- if [ $USE_MICROPYTHON = true ]; then ./.travis/install-micropython.sh && PYTHON=~/micropython/ports/unix/micropython; else PYTHON=python3; fi
1118
script:
1219
- chmod -R g+rw ./tests/fake-sys/devices/**/*
13-
- ./tests/api_tests.py
14-
- sphinx-build -nW -b html ./docs/ ./docs/_build/html
20+
- $PYTHON tests/api_tests.py
21+
- if [ $USE_MICROPYTHON = false ]; then sphinx-build -nW -b html ./docs/ ./docs/_build/html; fi
1522
deploy:
1623
provider: pypi
1724
user: Denis.Demidov
1825
password:
1926
secure: cTDN4WMJEjxZ0zwFwkLPpOIOSG/1JlHbQsHzd/tV9LfjBMR0nJR5HrmyiIO1TE5Wo6AFSFd7S3JmKdEnFO1ByvN/EFtsKGRUR9L6Yst4KfFi4nHwdZ7vgPTV0nNdvgC1YM/3bx8W8PcjFSm/k8awx7aicwXj09yDA8ENTf5XedaX22Z+9OKhb1mKola1cqEoc0GwaYzd8UX0Ruwh9/6RRbvTt7zn8BCZc9vIVqNd6mZgBWY9zAU40ZZsjYORbiZmDNCygEI+RViZ51M58WYkPPhoivzcG9em8DMRS7SC3CjWGapiOaXUHa3Fhnn+IQ+Q8Xv9YU5+qmj65MWQy3SSnMnvuxmrLf4aLoOlSJUMhDarjni4tdBOTX5PdOkdmhskyQt1DqDrw0+WhPItYfGe5zQfQwqW+YOpGbOipAeU+844arPo5jvZG/IOBX2qVUwdSxo8Y/98ocjqoZOq8b5xkWtJef0Kh1RCkp1bR2XELQVe76qeWqQxWz3OPqq+wK3xeNvj5kMQmytl3dCEB//D6UcES7Qr8YxD+LWoaIf32JIj/4LaCXXuxMVH+PJ68Oc72/ox0qLmXK0qhbea2QvaqXyGDrO+a2X6VbMdH32D2xHzH4Mg75xLnXnSaFvGovhYl1zEVcYUDioxrXZEuDmymGf9nH2mivJ24Fon6u+C3QQ=
2027
on:
2128
tags: true
22-
condition: $TRAVIS_TAG != ev3dev-stretch/*
29+
condition:
30+
- $TRAVIS_TAG != ev3dev-stretch/*
31+
- $USE_MICROPYTHON = false
2332
repo: ev3dev/ev3dev-lang-python

‎.travis/install-micropython.sh‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
#!/bin/sh
2+
set -ex
3+
4+
if [ -e ~/micropython/ports/unix/micropython ]; then
5+
# the micropython binary already exists, which means that the cached folder was restored
6+
exit 0
7+
fi
8+
9+
cd ~/
10+
11+
# Build micropython from source
12+
# TODO: cache micropython build output
13+
git clone --recurse-submodules https://github.com/micropython/micropython.git --depth 1 --branch v1.9.4 --quiet
14+
cd ./micropython/ports/unix
15+
make axtls
16+
make
17+
18+
# Install upip
19+
~/micropython/tools/bootstrap_upip.sh
20+
21+
# Install micropython library modules
22+
~/micropython/ports/unix/micropython -m upip install micropython-unittest micropython-os micropython-os.path micropython-shutil micropython-io micropython-fnmatch micropython-numbers micropython-struct micropython-time micropython-logging micropython-select
23+
# Make unittest module show error output; will run until failure then print first error
24+
# See https://github.com/micropython/micropython-lib/blob/f20d89c6aad9443a696561ca2a01f7ef0c8fb302/unittest/unittest.py#L203
25+
sed -i 's/#raise/raise/g' ~/.micropython/lib/unittest.py

‎ev3dev2/__init__.py‎

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,15 @@
2828
if sys.version_info < (3,4):
2929
raise SystemError('Must be using Python 3.4 or higher')
3030

31+
def is_micropython():
32+
return sys.implementation.name == "micropython"
33+
34+
def chain_exception(exception, cause):
35+
if is_micropython():
36+
raise exception
37+
else:
38+
raise exception from cause
39+
3140
import os
3241
import io
3342
import fnmatch
@@ -188,7 +197,8 @@ def get_index(file):
188197
except StopIteration:
189198
self._path = None
190199
self._device_index = None
191-
raise DeviceNotFound("%s is not connected." % self) from None
200+
201+
chain_exception(DeviceNotFound("%s is not connected." % self), None)
192202

193203
def __str__(self):
194204
if 'address' in self.kwargs:
@@ -206,13 +216,13 @@ def _attribute_file_open(self, name):
206216
w_ok = mode & stat.S_IWGRP
207217

208218
if r_ok and w_ok:
209-
mode = 'r+'
219+
mode_str = 'r+'
210220
elif w_ok:
211-
mode = 'w'
221+
mode_str = 'w'
212222
else:
213-
mode = 'r'
223+
mode_str = 'r'
214224

215-
return io.FileIO(path, mode)
225+
return io.FileIO(path, mode_str)
216226

217227
def _get_attribute(self, attribute, name):
218228
"""Device attribute getter"""
@@ -245,20 +255,22 @@ def _raise_friendly_access_error(self, driver_error, attribute):
245255
if not isinstance(driver_error, OSError):
246256
raise driver_error
247257

248-
if driver_error.errno == errno.EINVAL:
258+
driver_errorno = driver_error.args[0] if is_micropython() else driver_error.errno
259+
260+
if driver_errorno == errno.EINVAL:
249261
if attribute == "speed_sp":
250262
try:
251263
max_speed = self.max_speed
252264
except (AttributeError, Exception):
253-
raise ValueError("The given speed value was out of range") from driver_error
265+
chain_exception(ValueError("The given speed value was out of range"), driver_error)
254266
else:
255-
raise ValueError("The given speed value was out of range. Max speed: +/-" + str(max_speed)) from driver_error
256-
raise ValueError("One or more arguments were out of range or invalid") from driver_error
257-
elif driver_error.errno == errno.ENODEV or driver_error.errno == errno.ENOENT:
267+
chain_exception(ValueError("The given speed value was out of range. Max speed: +/-" + str(max_speed)), driver_error)
268+
chain_exception(ValueError("One or more arguments were out of range or invalid"), driver_error)
269+
elif driver_errorno == errno.ENODEV or driver_errorno == errno.ENOENT:
258270
# We will assume that a file-not-found error is the result of a disconnected device
259271
# rather than a library error. If that isn't the case, at a minimum the underlying
260272
# error info will be printed for debugging.
261-
raise DeviceNotFound("%s is no longer connected" % self) from driver_error
273+
chain_exception(DeviceNotFound("%s is no longer connected" % self), driver_error)
262274
raise driver_error
263275

264276
def get_attr_int(self, attribute, name):

‎ev3dev2/motor.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
import select
3232
import time
3333
from logging import getLogger
34-
from math import atan2, degrees as math_degrees, hypot
34+
from math import atan2, degrees as math_degrees, sqrt
3535
from os.path import abspath
3636
from ev3dev2 import get_current_platform, Device, list_device_names
3737

@@ -1905,7 +1905,7 @@ def get_speed_steering(self, steering, speed):
19051905
"""
19061906

19071907
assert steering >= -100 and steering <= 100,\
1908-
"%{} is an invalid steering, must be between -100 and 100 (inclusive)".format(steering)
1908+
"{} is an invalid steering, must be between -100 and 100 (inclusive)".format(steering)
19091909

19101910
# We don't have a good way to make this generic for the pair... so we
19111911
# assume that the left motor's speed stats are the same as the right
@@ -1957,7 +1957,7 @@ def on(self, x, y, max_speed=100.0, radius=100.0):
19571957
MoveTank.off()
19581958
return
19591959

1960-
vector_length = hypot(x, y)
1960+
vector_length = sqrt(x*x + y*y)
19611961
angle = math_degrees(atan2(y, x))
19621962

19631963
if angle < 0:

‎ev3dev2/sensor/__init__.py‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -211,10 +211,7 @@ def value(self, n=0):
211211
an error. The values are fixed point numbers, so check decimals to see
212212
if you need to divide to get the actual value.
213213
"""
214-
if isinstance(n, numbers.Real):
215-
n = int(n)
216-
elif isinstance(n, str):
217-
n = int(n)
214+
n = int(n)
218215

219216
self._value[n], value = self.get_attr_int(self._value[n], 'value'+str(n))
220217
return value

‎tests/api_tests.py‎

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
#!/usr/bin/env python3
2-
import unittest, sys, os
2+
import unittest, sys, os.path
33

44
FAKE_SYS = os.path.join(os.path.dirname(__file__), 'fake-sys')
55

@@ -21,15 +21,22 @@
2121

2222
_internal_set_attribute = ev3dev2.Device._set_attribute
2323
def _set_attribute(self, attribute, name, value):
24-
# After writing, clear the rest of the file to remove any residual text from
25-
# the last write. On the real device we're writing to sysfs attributes where
26-
# there isn't any persistent buffer, but in the test environment they're
27-
# normal files on disk.
24+
# Follow the text with a newline to separate new content from stuff that
25+
# already existed in the buffer. On the real device we're writing to sysfs
26+
# attributes where there isn't any persistent buffer, but in the test
27+
# environment they're normal files on disk which retain previous data.
2828
attribute = _internal_set_attribute(self, attribute, name, value)
29-
attribute.truncate()
30-
29+
attribute.write(b'\n')
30+
return attribute
3131
ev3dev2.Device._set_attribute = _set_attribute
3232

33+
_internal_get_attribute = ev3dev2.Device._get_attribute
34+
def _get_attribute(self, attribute, name):
35+
# Split on newline delimiter; see _set_attribute above
36+
attribute, value = _internal_get_attribute(self, attribute, name)
37+
return attribute, value.split('\n', 1)[0]
38+
ev3dev2.Device._get_attribute = _get_attribute
39+
3340
def dummy_wait(self, cond, timeout=None):
3441
pass
3542

@@ -114,7 +121,6 @@ def test_infrared_sensor(self):
114121
self.assertEqual(s.mode, "IR-REMOTE")
115122

116123
val = s.proximity
117-
# Our test environment writes to actual files on disk, so while "seek(0) write(...)" works on the real device, it leaves trailing characters from previous writes in tests. "s.mode" returns "IR-PROXTE" here.
118124
self.assertEqual(s.mode, "IR-PROX")
119125
self.assertEqual(val, 16)
120126

‎tests/fake-sys‎

0 commit comments

Comments
 (0)