Skip to content

Commit

Permalink
tree-wide: apply codestyle
Browse files Browse the repository at this point in the history
These are automatic changes made by running ./tools/codestyle.py
  • Loading branch information
dlech committed May 17, 2020
1 parent 842fff3 commit d293aaa
Show file tree
Hide file tree
Showing 167 changed files with 3,310 additions and 3,362 deletions.
18 changes: 9 additions & 9 deletions bricks/ev3dev/brickconfig.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,17 @@
#define MICROPY_PORT_DEINIT_FUNC pybricks_deinit()
#define MICROPY_MPHALPORT_H "ev3dev_mphal.h"
#define MICROPY_VM_HOOK_LOOP do { \
extern int pbio_do_one_event(void); \
pbio_do_one_event(); \
extern int pbio_do_one_event(void); \
pbio_do_one_event(); \
} while (0);
#define MICROPY_EVENT_POLL_HOOK do { \
extern void mp_handle_pending(void); \
mp_handle_pending(); \
extern int pbio_do_one_event(void); \
while (pbio_do_one_event()) { } \
MP_THREAD_GIL_EXIT(); \
g_main_context_iteration(g_main_context_get_thread_default(), TRUE); \
MP_THREAD_GIL_ENTER(); \
extern void mp_handle_pending(void); \
mp_handle_pending(); \
extern int pbio_do_one_event(void); \
while (pbio_do_one_event()) { } \
MP_THREAD_GIL_EXIT(); \
g_main_context_iteration(g_main_context_get_thread_default(), TRUE); \
MP_THREAD_GIL_ENTER(); \
} while (0);

#define MICROPY_PY_SYS_PATH_DEFAULT (":~/.pybricks-micropython/lib:/usr/lib/pybricks-micropython")
Expand Down
2 changes: 1 addition & 1 deletion bricks/ev3dev/ev3dev_mphal.c
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ void mp_hal_delay_ms(mp_uint_t ms) {
.tv_nsec = ms % 1000 * 1000000,
};
struct timespec remain;
for(;;) {
for (;;) {
mp_handle_pending();
MP_THREAD_GIL_EXIT();
int ret = clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, &remain);
Expand Down
6 changes: 4 additions & 2 deletions bricks/ev3dev/ev3dev_mphal.h
Original file line number Diff line number Diff line change
Expand Up @@ -49,9 +49,11 @@ static inline int mp_hal_readline(vstr_t *vstr, const char *p) {

// TODO: POSIX et al. define usleep() as guaranteedly capable only of 1s sleep:
// "The useconds argument shall be less than one million."
static inline void mp_hal_delay_us(mp_uint_t us) { usleep(us); }
static inline void mp_hal_delay_us(mp_uint_t us) {
usleep(us);
}
#define mp_hal_ticks_cpu() 0

#define RAISE_ERRNO(err_flag, error_val) \
{ if (err_flag == -1) \
{ mp_raise_OSError(error_val); } }
{ mp_raise_OSError(error_val); } }
2 changes: 1 addition & 1 deletion bricks/ev3dev/modbluetooth.c
Original file line number Diff line number Diff line change
Expand Up @@ -75,5 +75,5 @@ STATIC MP_DEFINE_CONST_DICT(ev3dev_bluetooth_globals, ev3dev_bluetooth_globals_t

const mp_obj_module_t pb_module_bluetooth = {
.base = { &mp_type_module },
.globals = (mp_obj_dict_t*)&ev3dev_bluetooth_globals,
.globals = (mp_obj_dict_t *)&ev3dev_bluetooth_globals,
};
9 changes: 8 additions & 1 deletion bricks/ev3dev/modules/core.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
"""Conveniently import core functionality for use on the REPL."""
from pybricks.hubs import EV3Brick
from pybricks.ev3devices import Motor, TouchSensor, ColorSensor, InfraredSensor, UltrasonicSensor, GyroSensor
from pybricks.ev3devices import (
Motor,
TouchSensor,
ColorSensor,
InfraredSensor,
UltrasonicSensor,
GyroSensor,
)
from pybricks.parameters import Port, Stop, Direction, Button, Color
from pybricks.tools import wait, StopWatch, DataLog
from pybricks.robotics import DriveBase
Expand Down
23 changes: 12 additions & 11 deletions bricks/ev3dev/modules/pybricks/bluetooth.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,32 @@

AF_BLUETOOTH = 31
BTPROTO_RFCOMM = 3
BDADDR_ANY = '00:00:00:00:00:00'
BDADDR_ANY = "00:00:00:00:00:00"

sa_family_t = UINT16

bd_addr_t = {
'b': (ARRAY | 0, UINT8 | 6)
}
bd_addr_t = {"b": (ARRAY | 0, UINT8 | 6)}

sockaddr_rc = {
'rc_family': sa_family_t | 0,
'rc_bdaddr': (2, bd_addr_t),
'rc_channel': UINT8 | 8,
"rc_family": sa_family_t | 0,
"rc_bdaddr": (2, bd_addr_t),
"rc_channel": UINT8 | 8,
}


def str2ba(string, ba):
"""Convert string to Bluetooth address"""
for i, v in enumerate(string.split(':')):
ba.b[5-i] = int(v, 16)
for i, v in enumerate(string.split(":")):
ba.b[5 - i] = int(v, 16)


def ba2str(ba):
"""Convert Bluetooth address to string"""
string = []
for b in ba.b:
string.append('{:02X}'.format(b))
string.append("{:02X}".format(b))
string.reverse()
return ':'.join(string).upper()
return ":".join(string).upper()


class RFCOMMServer:
Expand All @@ -56,6 +54,7 @@ class RFCOMMServer:
This is based on the ``socketserver.SocketServer`` class in the Python
standard library.
"""

request_queue_size = 1

def __init__(self, server_address, RequestHandlerClass):
Expand Down Expand Up @@ -123,6 +122,7 @@ class ThreadingRFCOMMServer(ThreadingMixIn, RFCOMMServer):
"""Version of :class:`RFCOMMServer` that handles connections in a new
thread.
"""

pass


Expand All @@ -132,6 +132,7 @@ class StreamRequestHandler:
This is based on ``socketserver.StreamRequestHandler`` from the Python
standard library.
"""

def __init__(self, request, client_address, server):
self.request = request
self.client_address = client_address
Expand Down
11 changes: 6 additions & 5 deletions bricks/ev3dev/modules/pybricks/display.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,16 @@
from .parameters import Align


class Display():
class Display:
"""Show images or text on a display."""
_valid_devices = ['EV3']
_font_height = 8 # TODO: Update class when font no longer constant

_valid_devices = ["EV3"]
_font_height = 8 # TODO: Update class when font no longer constant

def __init__(self, device_type):
"""Device specific display initialization."""
assert device_type in self._valid_devices, 'Selected device is not supported.'
if device_type == 'EV3':
assert device_type in self._valid_devices, "Selected device is not supported."
if device_type == "EV3":
self._device = Ev3devDisplay()
self._loaded_files = {}
self._reset_text_history()
Expand Down
7 changes: 3 additions & 4 deletions bricks/ev3dev/modules/pybricks/ev3brick.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,10 @@

try:
# Initialize the EV3 speaker and display
sound = Speaker('EV3')
display = Display('EV3')
sound = Speaker("EV3")
display = Display("EV3")
except Exception as exception:
print("Pybricks is already running on this device. Exiting...",
file=stderr)
print("Pybricks is already running on this device. Exiting...", file=stderr)
exit(1)

battery = _brickobj.battery
Expand Down
16 changes: 12 additions & 4 deletions bricks/ev3dev/modules/pybricks/ev3devices.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
"""Classes for LEGO MINDSTORMS EV3 Devices."""

# import those ev3devices that are already written in MicroPython-style C code.
from ev3devices_c import (InfraredSensor, ColorSensor, TouchSensor,
UltrasonicSensor, GyroSensor)
from ev3devices_c import InfraredSensor, ColorSensor, TouchSensor, UltrasonicSensor, GyroSensor
from ev3devices_c import Motor as CompatMotor
from pybricks.parameters import Stop

Expand Down Expand Up @@ -37,8 +36,17 @@ def set_run_settings(self, max_speed, acceleration):
"""set_run_settings backwards-compatible with 1.0 EV3 release."""
self.control.limits(max_speed, acceleration)

def set_pid_settings(self, kp, ki, kd, tight_loop_limit, angle_tolerance,
speed_tolerance, stall_speed, stall_time):
def set_pid_settings(
self,
kp,
ki,
kd,
tight_loop_limit,
angle_tolerance,
speed_tolerance,
stall_speed,
stall_time,
):
"""set_pid_settings backwards-compatible with 1.0 EV3 release."""
self.control.pid(kp, ki, kd)
self.control.target_tolerances(speed_tolerance, angle_tolerance)
Expand Down
42 changes: 22 additions & 20 deletions bricks/ev3dev/modules/pybricks/ev3devio.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
def read_int(infile):
"""Read an integer from a previously opened file descriptor."""
infile.seek(0)
return(int(infile.read().decode().strip()))
return int(infile.read().decode().strip())


def write_int(outfile, value):
Expand All @@ -21,7 +21,7 @@ def write_int(outfile, value):
def read_str(infile):
"""Read a string from a previously opened file descriptor."""
infile.seek(0)
return(infile.read().decode().strip())
return infile.read().decode().strip()


def write_str(outfile, value):
Expand All @@ -32,34 +32,34 @@ def write_str(outfile, value):

def get_sensor_path(port, driver_name):
"""Get a path to a device based on port number."""
base_dir = '/sys/class/lego-sensor'
base_dir = "/sys/class/lego-sensor"
# Iterate through ['sensor0', 'sensor1', 'sensor2', ...]
for device_dir, _, _ in ilistdir(base_dir):
# In each folder, open the address file
with open(base_dir + '/' + device_dir + '/address', 'r') as addr_file:
with open(base_dir + "/" + device_dir + "/address", "r") as addr_file:
# Read the port string (e.g. 'outB')
port_found = addr_file.read().strip('\n')
port_found = addr_file.read().strip("\n")
# If the port name matches, we are done searching and
# we know the full path
if 'in' + chr(port) in port_found:
if "in" + chr(port) in port_found:
# Make the full path
full_dir = base_dir + '/' + device_dir + '/'
with open(full_dir + 'driver_name', 'r') as driver_file:
full_dir = base_dir + "/" + device_dir + "/"
with open(full_dir + "driver_name", "r") as driver_file:
if driver_name in driver_file.read():
return full_dir
raise OSError('No such sensor on Port S' + chr(port))
raise OSError("No such sensor on Port S" + chr(port))


class Ev3devSensor():
class Ev3devSensor:
"""Base class for ev3dev sensors operating through sysfs."""

_ev3dev_driver_name = 'none'
_ev3dev_driver_name = "none"
_number_of_values = 1
_default_mode = None

def __init__(self, port):
"""Initialize the sensor."""
assert ord('1') <= port <= ord('4')
assert ord("1") <= port <= ord("4")
self.port = port
self._open_files()
if self._default_mode:
Expand All @@ -68,9 +68,11 @@ def __init__(self, port):
def _open_files(self):
"""Open the sysfs files for this device."""
self.path = get_sensor_path(self.port, self._ev3dev_driver_name)
self.mode_file = open(self.path + 'mode', 'r+b')
self.mode_file = open(self.path + "mode", "r+b")
self.mode_now = read_str(self.mode_file)
self.value_files = [open(self.path + 'value' + str(num), 'rb') for num in range(self._number_of_values)]
self.value_files = [
open(self.path + "value" + str(num), "rb") for num in range(self._number_of_values)
]

def _close_files(self):
"""Close the sysfs files for this device."""
Expand All @@ -93,14 +95,14 @@ class Ev3devUartSensor(Ev3devSensor):
"""UART ev3dev sensor operating through sysfs."""

def _reset_port(self):
path = '/sys/class/lego-port/port' + chr(self.port-1) + '/'
with open(path + 'mode', 'w') as rf:
rf.write('auto')
with open(path + 'mode', 'w') as rf:
rf.write('ev3-uart')
path = "/sys/class/lego-port/port" + chr(self.port - 1) + "/"
with open(path + "mode", "w") as rf:
rf.write("auto")
with open(path + "mode", "w") as rf:
rf.write("ev3-uart")
watch = StopWatch()
while True:
with open(path + 'status', 'r') as sf:
with open(path + "status", "r") as sf:
status = sf.read().strip()
if status != "no-sensor":
break
Expand Down
7 changes: 3 additions & 4 deletions bricks/ev3dev/modules/pybricks/experimental.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ def task2():
# task2: 'OK2'
"""
if len(args) < 2:
raise TypeError('requires at least 2 arguments')
raise TypeError("requires at least 2 arguments")
for n, arg in enumerate(args):
if not callable(arg):
raise TypeError('argument {} is not callable'.format(n))
raise TypeError("argument {} is not callable".format(n))

ids = set()
lock = allocate_lock()
Expand Down Expand Up @@ -84,6 +84,5 @@ def wrapper(func):

lock.acquire()
if any(isinstance(x, Exception) for x in results.values()):
raise RuntimeError("An unhandled exception occurred in run_parallel",
results)
raise RuntimeError("An unhandled exception occurred in run_parallel", results)
return results
Loading

0 comments on commit d293aaa

Please sign in to comment.