diff --git a/bricks/ev3dev/brickconfig.h b/bricks/ev3dev/brickconfig.h index b1407b232..27905336e 100644 --- a/bricks/ev3dev/brickconfig.h +++ b/bricks/ev3dev/brickconfig.h @@ -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") diff --git a/bricks/ev3dev/ev3dev_mphal.c b/bricks/ev3dev/ev3dev_mphal.c index 627e21f4e..981555c52 100644 --- a/bricks/ev3dev/ev3dev_mphal.c +++ b/bricks/ev3dev/ev3dev_mphal.c @@ -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); diff --git a/bricks/ev3dev/ev3dev_mphal.h b/bricks/ev3dev/ev3dev_mphal.h index a07f47b38..c201f43e2 100644 --- a/bricks/ev3dev/ev3dev_mphal.h +++ b/bricks/ev3dev/ev3dev_mphal.h @@ -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); } } diff --git a/bricks/ev3dev/modbluetooth.c b/bricks/ev3dev/modbluetooth.c index 527b7945b..3279c1cd0 100644 --- a/bricks/ev3dev/modbluetooth.c +++ b/bricks/ev3dev/modbluetooth.c @@ -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, }; diff --git a/bricks/ev3dev/modules/core.py b/bricks/ev3dev/modules/core.py index 18025c61a..3373f28dd 100644 --- a/bricks/ev3dev/modules/core.py +++ b/bricks/ev3dev/modules/core.py @@ -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 diff --git a/bricks/ev3dev/modules/pybricks/bluetooth.py b/bricks/ev3dev/modules/pybricks/bluetooth.py index a1c6cc277..e8eb340e4 100644 --- a/bricks/ev3dev/modules/pybricks/bluetooth.py +++ b/bricks/ev3dev/modules/pybricks/bluetooth.py @@ -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: @@ -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): @@ -123,6 +122,7 @@ class ThreadingRFCOMMServer(ThreadingMixIn, RFCOMMServer): """Version of :class:`RFCOMMServer` that handles connections in a new thread. """ + pass @@ -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 diff --git a/bricks/ev3dev/modules/pybricks/display.py b/bricks/ev3dev/modules/pybricks/display.py index 9f58a76e9..cda378690 100644 --- a/bricks/ev3dev/modules/pybricks/display.py +++ b/bricks/ev3dev/modules/pybricks/display.py @@ -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() diff --git a/bricks/ev3dev/modules/pybricks/ev3brick.py b/bricks/ev3dev/modules/pybricks/ev3brick.py index 9bd0ee0cc..f00cd7bd8 100644 --- a/bricks/ev3dev/modules/pybricks/ev3brick.py +++ b/bricks/ev3dev/modules/pybricks/ev3brick.py @@ -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 diff --git a/bricks/ev3dev/modules/pybricks/ev3devices.py b/bricks/ev3dev/modules/pybricks/ev3devices.py index 791d9ccec..32b171068 100644 --- a/bricks/ev3dev/modules/pybricks/ev3devices.py +++ b/bricks/ev3dev/modules/pybricks/ev3devices.py @@ -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 @@ -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) diff --git a/bricks/ev3dev/modules/pybricks/ev3devio.py b/bricks/ev3dev/modules/pybricks/ev3devio.py index 0f0ae0146..40d27e92b 100644 --- a/bricks/ev3dev/modules/pybricks/ev3devio.py +++ b/bricks/ev3dev/modules/pybricks/ev3devio.py @@ -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): @@ -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): @@ -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: @@ -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.""" @@ -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 diff --git a/bricks/ev3dev/modules/pybricks/experimental.py b/bricks/ev3dev/modules/pybricks/experimental.py index 79644f123..cb00487cf 100644 --- a/bricks/ev3dev/modules/pybricks/experimental.py +++ b/bricks/ev3dev/modules/pybricks/experimental.py @@ -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() @@ -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 diff --git a/bricks/ev3dev/modules/pybricks/media/ev3dev.py b/bricks/ev3dev/modules/pybricks/media/ev3dev.py index 74530463e..8901abec6 100644 --- a/bricks/ev3dev/modules/pybricks/media/ev3dev.py +++ b/bricks/ev3dev/modules/pybricks/media/ev3dev.py @@ -1,172 +1,172 @@ from media_ev3dev_c import Font, Image -class SoundFile(): - _BASE_PATH = '/usr/share/sounds/ev3dev/' - - CAT_PURR = _BASE_PATH + 'animals/cat_purr.wav' - DOG_BARK_1 = _BASE_PATH + 'animals/dog_bark_1.wav' - DOG_BARK_2 = _BASE_PATH + 'animals/dog_bark_2.wav' - DOG_GROWL = _BASE_PATH + 'animals/dog_growl.wav' - DOG_SNIFF = _BASE_PATH + 'animals/dog_sniff.wav' - DOG_WHINE = _BASE_PATH + 'animals/dog_whine.wav' - ELEPHANT_CALL = _BASE_PATH + 'animals/elephant_call.wav' - INSECT_BUZZ_1 = _BASE_PATH + 'animals/insect_buzz_1.wav' - INSECT_BUZZ_2 = _BASE_PATH + 'animals/insect_buzz_2.wav' - INSECT_CHIRP = _BASE_PATH + 'animals/insect_chirp.wav' - SNAKE_HISS = _BASE_PATH + 'animals/snake_hiss.wav' - SNAKE_RATTLE = _BASE_PATH + 'animals/snake_rattle.wav' - T_REX_ROAR = _BASE_PATH + 'animals/t-rex_roar.wav' - - BLACK = _BASE_PATH + 'colors/black.wav' - BLUE = _BASE_PATH + 'colors/blue.wav' - BROWN = _BASE_PATH + 'colors/brown.wav' - GREEN = _BASE_PATH + 'colors/green.wav' - RED = _BASE_PATH + 'colors/red.wav' - WHITE = _BASE_PATH + 'colors/white.wav' - YELLOW = _BASE_PATH + 'colors/yellow.wav' - - BRAVO = _BASE_PATH + 'communication/bravo.wav' - EV3 = _BASE_PATH + 'communication/ev3.wav' - FANTASTIC = _BASE_PATH + 'communication/fantastic.wav' - GAME_OVER = _BASE_PATH + 'communication/game_over.wav' - GO = _BASE_PATH + 'communication/go.wav' - GOOD = _BASE_PATH + 'communication/good.wav' - GOOD_JOB = _BASE_PATH + 'communication/good_job.wav' - GOODBYE = _BASE_PATH + 'communication/goodbye.wav' - HELLO = _BASE_PATH + 'communication/hello.wav' - HI = _BASE_PATH + 'communication/hi.wav' - LEGO = _BASE_PATH + 'communication/lego.wav' - MINDSTORMS = _BASE_PATH + 'communication/mindstorms.wav' - MORNING = _BASE_PATH + 'communication/morning.wav' - NO = _BASE_PATH + 'communication/no.wav' - OKAY = _BASE_PATH + 'communication/okay.wav' - OKEY_DOKEY = _BASE_PATH + 'communication/okey-dokey.wav' - SORRY = _BASE_PATH + 'communication/sorry.wav' - THANK_YOU = _BASE_PATH + 'communication/thank_you.wav' - YES = _BASE_PATH + 'communication/yes.wav' - - BOING = _BASE_PATH + 'expressions/boing.wav' - BOO = _BASE_PATH + 'expressions/boo.wav' - CHEERING = _BASE_PATH + 'expressions/cheering.wav' - CRUNCHING = _BASE_PATH + 'expressions/crunching.wav' - CRYING = _BASE_PATH + 'expressions/crying.wav' - FANFARE = _BASE_PATH + 'expressions/fanfare.wav' - KUNG_FU = _BASE_PATH + 'expressions/kung_fu.wav' - LAUGHING_1 = _BASE_PATH + 'expressions/laughing_1.wav' - LAUGHING_2 = _BASE_PATH + 'expressions/laughing_2.wav' - MAGIC_WAND = _BASE_PATH + 'expressions/magic_wand.wav' - OUCH = _BASE_PATH + 'expressions/ouch.wav' - SHOUTING = _BASE_PATH + 'expressions/shouting.wav' - SMACK = _BASE_PATH + 'expressions/smack.wav' - SNEEZING = _BASE_PATH + 'expressions/sneezing.wav' - SNORING = _BASE_PATH + 'expressions/snoring.wav' - UH_OH = _BASE_PATH + 'expressions/uh-oh.wav' - - ACTIVATE = _BASE_PATH + 'information/activate.wav' - ANALYZE = _BASE_PATH + 'information/analyze.wav' - BACKWARDS = _BASE_PATH + 'information/backwards.wav' - COLOR = _BASE_PATH + 'information/color.wav' - DETECTED = _BASE_PATH + 'information/detected.wav' - DOWN = _BASE_PATH + 'information/down.wav' - ERROR = _BASE_PATH + 'information/error.wav' - ERROR_ALARM = _BASE_PATH + 'information/error_alarm.wav' - FLASHING = _BASE_PATH + 'information/flashing.wav' - FORWARD = _BASE_PATH + 'information/forward.wav' - LEFT = _BASE_PATH + 'information/left.wav' - OBJECT = _BASE_PATH + 'information/object.wav' - RIGHT = _BASE_PATH + 'information/right.wav' - SEARCHING = _BASE_PATH + 'information/searching.wav' - START = _BASE_PATH + 'information/start.wav' - STOP = _BASE_PATH + 'information/stop.wav' - TOUCH = _BASE_PATH + 'information/touch.wav' - TURN = _BASE_PATH + 'information/turn.wav' - UP = _BASE_PATH + 'information/up.wav' - - AIR_RELEASE = _BASE_PATH + 'mechanical/air_release.wav' - AIRBRAKE = _BASE_PATH + 'mechanical/airbrake.wav' - BACKING_ALERT = _BASE_PATH + 'mechanical/backing_alert.wav' - HORN_1 = _BASE_PATH + 'mechanical/horn_1.wav' - HORN_2 = _BASE_PATH + 'mechanical/horn_2.wav' - LASER = _BASE_PATH + 'mechanical/laser.wav' - MOTOR_IDLE = _BASE_PATH + 'mechanical/motor_idle.wav' - MOTOR_START = _BASE_PATH + 'mechanical/motor_start.wav' - MOTOR_STOP = _BASE_PATH + 'mechanical/motor_stop.wav' - RATCHET = _BASE_PATH + 'mechanical/ratchet.wav' - SONAR = _BASE_PATH + 'mechanical/sonar.wav' - TICK_TACK = _BASE_PATH + 'mechanical/tick_tack.wav' - - SPEED_DOWN = _BASE_PATH + 'movements/speed_down.wav' - SPEED_IDLE = _BASE_PATH + 'movements/speed_idle.wav' - SPEED_UP = _BASE_PATH + 'movements/speed_up.wav' - - ZERO = _BASE_PATH + 'numbers/zero.wav' - ONE = _BASE_PATH + 'numbers/one.wav' - TWO = _BASE_PATH + 'numbers/two.wav' - THREE = _BASE_PATH + 'numbers/three.wav' - FOUR = _BASE_PATH + 'numbers/four.wav' - FIVE = _BASE_PATH + 'numbers/five.wav' - SIX = _BASE_PATH + 'numbers/six.wav' - SEVEN = _BASE_PATH + 'numbers/seven.wav' - EIGHT = _BASE_PATH + 'numbers/eight.wav' - NINE = _BASE_PATH + 'numbers/nine.wav' - TEN = _BASE_PATH + 'numbers/ten.wav' - - CLICK = _BASE_PATH + 'system/click.wav' - CONFIRM = _BASE_PATH + 'system/confirm.wav' - GENERAL_ALERT = _BASE_PATH + 'system/general_alert.wav' - OVERPOWER = _BASE_PATH + 'system/overpower.wav' - READY = _BASE_PATH + 'system/ready.wav' - - -class ImageFile(): - _BASE_PATH = '/usr/share/images/ev3dev/mono/' - - ANGRY = _BASE_PATH + 'eyes/angry.png' - AWAKE = _BASE_PATH + 'eyes/awake.png' - BLACK_EYE = _BASE_PATH + 'eyes/black_eye.png' - BOTTOM_LEFT = _BASE_PATH + 'eyes/bottom_left.png' - BOTTOM_RIGHT = _BASE_PATH + 'eyes/bottom_right.png' - CRAZY_1 = _BASE_PATH + 'eyes/crazy_1.png' - CRAZY_2 = _BASE_PATH + 'eyes/crazy_2.png' - DISAPPOINTED = _BASE_PATH + 'eyes/disappointed.png' - DIZZY = _BASE_PATH + 'eyes/dizzy.png' - DOWN = _BASE_PATH + 'eyes/down.png' - EVIL = _BASE_PATH + 'eyes/evil.png' - HURT = _BASE_PATH + 'eyes/hurt.png' - KNOCKED_OUT = _BASE_PATH + 'eyes/knocked_out.png' - LOVE = _BASE_PATH + 'eyes/love.png' - MIDDLE_LEFT = _BASE_PATH + 'eyes/middle_left.png' - MIDDLE_RIGHT = _BASE_PATH + 'eyes/middle_right.png' - NEUTRAL = _BASE_PATH + 'eyes/neutral.png' - NUCLEAR = _BASE_PATH + 'eyes/nuclear.png' - PINCHED_LEFT = _BASE_PATH + 'eyes/pinched_left.png' - PINCHED_MIDDLE = _BASE_PATH + 'eyes/pinched_middle.png' - PINCHED_RIGHT = _BASE_PATH + 'eyes/pinched_right.png' - SLEEPING = _BASE_PATH + 'eyes/sleeping.png' - TEAR = _BASE_PATH + 'eyes/tear.png' - TIRED_LEFT = _BASE_PATH + 'eyes/tired_left.png' - TIRED_MIDDLE = _BASE_PATH + 'eyes/tired_middle.png' - TIRED_RIGHT = _BASE_PATH + 'eyes/tired_right.png' - TOXIC = _BASE_PATH + 'eyes/toxic.png' - UP = _BASE_PATH + 'eyes/up.png' - WINKING = _BASE_PATH + 'eyes/winking.png' - - ACCEPT = _BASE_PATH + 'information/accept.png' - BACKWARD = _BASE_PATH + 'information/backward.png' - DECLINE = _BASE_PATH + 'information/decline.png' - FORWARD = _BASE_PATH + 'information/forward.png' - LEFT = _BASE_PATH + 'information/left.png' - NO_GO = _BASE_PATH + 'information/no_go.png' - QUESTION_MARK = _BASE_PATH + 'information/question_mark.png' - RIGHT = _BASE_PATH + 'information/right.png' - STOP_1 = _BASE_PATH + 'information/stop_1.png' - STOP_2 = _BASE_PATH + 'information/stop_2.png' - THUMBS_DOWN = _BASE_PATH + 'information/thumbs_down.png' - THUMBS_UP = _BASE_PATH + 'information/thumbs_up.png' - WARNING = _BASE_PATH + 'information/warning.png' - - EV3 = _BASE_PATH + 'lego/ev3.png' - EV3_ICON = _BASE_PATH + 'lego/ev3_icon.png' - - TARGET = _BASE_PATH + 'objects/target.png' +class SoundFile: + _BASE_PATH = "/usr/share/sounds/ev3dev/" + + CAT_PURR = _BASE_PATH + "animals/cat_purr.wav" + DOG_BARK_1 = _BASE_PATH + "animals/dog_bark_1.wav" + DOG_BARK_2 = _BASE_PATH + "animals/dog_bark_2.wav" + DOG_GROWL = _BASE_PATH + "animals/dog_growl.wav" + DOG_SNIFF = _BASE_PATH + "animals/dog_sniff.wav" + DOG_WHINE = _BASE_PATH + "animals/dog_whine.wav" + ELEPHANT_CALL = _BASE_PATH + "animals/elephant_call.wav" + INSECT_BUZZ_1 = _BASE_PATH + "animals/insect_buzz_1.wav" + INSECT_BUZZ_2 = _BASE_PATH + "animals/insect_buzz_2.wav" + INSECT_CHIRP = _BASE_PATH + "animals/insect_chirp.wav" + SNAKE_HISS = _BASE_PATH + "animals/snake_hiss.wav" + SNAKE_RATTLE = _BASE_PATH + "animals/snake_rattle.wav" + T_REX_ROAR = _BASE_PATH + "animals/t-rex_roar.wav" + + BLACK = _BASE_PATH + "colors/black.wav" + BLUE = _BASE_PATH + "colors/blue.wav" + BROWN = _BASE_PATH + "colors/brown.wav" + GREEN = _BASE_PATH + "colors/green.wav" + RED = _BASE_PATH + "colors/red.wav" + WHITE = _BASE_PATH + "colors/white.wav" + YELLOW = _BASE_PATH + "colors/yellow.wav" + + BRAVO = _BASE_PATH + "communication/bravo.wav" + EV3 = _BASE_PATH + "communication/ev3.wav" + FANTASTIC = _BASE_PATH + "communication/fantastic.wav" + GAME_OVER = _BASE_PATH + "communication/game_over.wav" + GO = _BASE_PATH + "communication/go.wav" + GOOD = _BASE_PATH + "communication/good.wav" + GOOD_JOB = _BASE_PATH + "communication/good_job.wav" + GOODBYE = _BASE_PATH + "communication/goodbye.wav" + HELLO = _BASE_PATH + "communication/hello.wav" + HI = _BASE_PATH + "communication/hi.wav" + LEGO = _BASE_PATH + "communication/lego.wav" + MINDSTORMS = _BASE_PATH + "communication/mindstorms.wav" + MORNING = _BASE_PATH + "communication/morning.wav" + NO = _BASE_PATH + "communication/no.wav" + OKAY = _BASE_PATH + "communication/okay.wav" + OKEY_DOKEY = _BASE_PATH + "communication/okey-dokey.wav" + SORRY = _BASE_PATH + "communication/sorry.wav" + THANK_YOU = _BASE_PATH + "communication/thank_you.wav" + YES = _BASE_PATH + "communication/yes.wav" + + BOING = _BASE_PATH + "expressions/boing.wav" + BOO = _BASE_PATH + "expressions/boo.wav" + CHEERING = _BASE_PATH + "expressions/cheering.wav" + CRUNCHING = _BASE_PATH + "expressions/crunching.wav" + CRYING = _BASE_PATH + "expressions/crying.wav" + FANFARE = _BASE_PATH + "expressions/fanfare.wav" + KUNG_FU = _BASE_PATH + "expressions/kung_fu.wav" + LAUGHING_1 = _BASE_PATH + "expressions/laughing_1.wav" + LAUGHING_2 = _BASE_PATH + "expressions/laughing_2.wav" + MAGIC_WAND = _BASE_PATH + "expressions/magic_wand.wav" + OUCH = _BASE_PATH + "expressions/ouch.wav" + SHOUTING = _BASE_PATH + "expressions/shouting.wav" + SMACK = _BASE_PATH + "expressions/smack.wav" + SNEEZING = _BASE_PATH + "expressions/sneezing.wav" + SNORING = _BASE_PATH + "expressions/snoring.wav" + UH_OH = _BASE_PATH + "expressions/uh-oh.wav" + + ACTIVATE = _BASE_PATH + "information/activate.wav" + ANALYZE = _BASE_PATH + "information/analyze.wav" + BACKWARDS = _BASE_PATH + "information/backwards.wav" + COLOR = _BASE_PATH + "information/color.wav" + DETECTED = _BASE_PATH + "information/detected.wav" + DOWN = _BASE_PATH + "information/down.wav" + ERROR = _BASE_PATH + "information/error.wav" + ERROR_ALARM = _BASE_PATH + "information/error_alarm.wav" + FLASHING = _BASE_PATH + "information/flashing.wav" + FORWARD = _BASE_PATH + "information/forward.wav" + LEFT = _BASE_PATH + "information/left.wav" + OBJECT = _BASE_PATH + "information/object.wav" + RIGHT = _BASE_PATH + "information/right.wav" + SEARCHING = _BASE_PATH + "information/searching.wav" + START = _BASE_PATH + "information/start.wav" + STOP = _BASE_PATH + "information/stop.wav" + TOUCH = _BASE_PATH + "information/touch.wav" + TURN = _BASE_PATH + "information/turn.wav" + UP = _BASE_PATH + "information/up.wav" + + AIR_RELEASE = _BASE_PATH + "mechanical/air_release.wav" + AIRBRAKE = _BASE_PATH + "mechanical/airbrake.wav" + BACKING_ALERT = _BASE_PATH + "mechanical/backing_alert.wav" + HORN_1 = _BASE_PATH + "mechanical/horn_1.wav" + HORN_2 = _BASE_PATH + "mechanical/horn_2.wav" + LASER = _BASE_PATH + "mechanical/laser.wav" + MOTOR_IDLE = _BASE_PATH + "mechanical/motor_idle.wav" + MOTOR_START = _BASE_PATH + "mechanical/motor_start.wav" + MOTOR_STOP = _BASE_PATH + "mechanical/motor_stop.wav" + RATCHET = _BASE_PATH + "mechanical/ratchet.wav" + SONAR = _BASE_PATH + "mechanical/sonar.wav" + TICK_TACK = _BASE_PATH + "mechanical/tick_tack.wav" + + SPEED_DOWN = _BASE_PATH + "movements/speed_down.wav" + SPEED_IDLE = _BASE_PATH + "movements/speed_idle.wav" + SPEED_UP = _BASE_PATH + "movements/speed_up.wav" + + ZERO = _BASE_PATH + "numbers/zero.wav" + ONE = _BASE_PATH + "numbers/one.wav" + TWO = _BASE_PATH + "numbers/two.wav" + THREE = _BASE_PATH + "numbers/three.wav" + FOUR = _BASE_PATH + "numbers/four.wav" + FIVE = _BASE_PATH + "numbers/five.wav" + SIX = _BASE_PATH + "numbers/six.wav" + SEVEN = _BASE_PATH + "numbers/seven.wav" + EIGHT = _BASE_PATH + "numbers/eight.wav" + NINE = _BASE_PATH + "numbers/nine.wav" + TEN = _BASE_PATH + "numbers/ten.wav" + + CLICK = _BASE_PATH + "system/click.wav" + CONFIRM = _BASE_PATH + "system/confirm.wav" + GENERAL_ALERT = _BASE_PATH + "system/general_alert.wav" + OVERPOWER = _BASE_PATH + "system/overpower.wav" + READY = _BASE_PATH + "system/ready.wav" + + +class ImageFile: + _BASE_PATH = "/usr/share/images/ev3dev/mono/" + + ANGRY = _BASE_PATH + "eyes/angry.png" + AWAKE = _BASE_PATH + "eyes/awake.png" + BLACK_EYE = _BASE_PATH + "eyes/black_eye.png" + BOTTOM_LEFT = _BASE_PATH + "eyes/bottom_left.png" + BOTTOM_RIGHT = _BASE_PATH + "eyes/bottom_right.png" + CRAZY_1 = _BASE_PATH + "eyes/crazy_1.png" + CRAZY_2 = _BASE_PATH + "eyes/crazy_2.png" + DISAPPOINTED = _BASE_PATH + "eyes/disappointed.png" + DIZZY = _BASE_PATH + "eyes/dizzy.png" + DOWN = _BASE_PATH + "eyes/down.png" + EVIL = _BASE_PATH + "eyes/evil.png" + HURT = _BASE_PATH + "eyes/hurt.png" + KNOCKED_OUT = _BASE_PATH + "eyes/knocked_out.png" + LOVE = _BASE_PATH + "eyes/love.png" + MIDDLE_LEFT = _BASE_PATH + "eyes/middle_left.png" + MIDDLE_RIGHT = _BASE_PATH + "eyes/middle_right.png" + NEUTRAL = _BASE_PATH + "eyes/neutral.png" + NUCLEAR = _BASE_PATH + "eyes/nuclear.png" + PINCHED_LEFT = _BASE_PATH + "eyes/pinched_left.png" + PINCHED_MIDDLE = _BASE_PATH + "eyes/pinched_middle.png" + PINCHED_RIGHT = _BASE_PATH + "eyes/pinched_right.png" + SLEEPING = _BASE_PATH + "eyes/sleeping.png" + TEAR = _BASE_PATH + "eyes/tear.png" + TIRED_LEFT = _BASE_PATH + "eyes/tired_left.png" + TIRED_MIDDLE = _BASE_PATH + "eyes/tired_middle.png" + TIRED_RIGHT = _BASE_PATH + "eyes/tired_right.png" + TOXIC = _BASE_PATH + "eyes/toxic.png" + UP = _BASE_PATH + "eyes/up.png" + WINKING = _BASE_PATH + "eyes/winking.png" + + ACCEPT = _BASE_PATH + "information/accept.png" + BACKWARD = _BASE_PATH + "information/backward.png" + DECLINE = _BASE_PATH + "information/decline.png" + FORWARD = _BASE_PATH + "information/forward.png" + LEFT = _BASE_PATH + "information/left.png" + NO_GO = _BASE_PATH + "information/no_go.png" + QUESTION_MARK = _BASE_PATH + "information/question_mark.png" + RIGHT = _BASE_PATH + "information/right.png" + STOP_1 = _BASE_PATH + "information/stop_1.png" + STOP_2 = _BASE_PATH + "information/stop_2.png" + THUMBS_DOWN = _BASE_PATH + "information/thumbs_down.png" + THUMBS_UP = _BASE_PATH + "information/thumbs_up.png" + WARNING = _BASE_PATH + "information/warning.png" + + EV3 = _BASE_PATH + "lego/ev3.png" + EV3_ICON = _BASE_PATH + "lego/ev3_icon.png" + + TARGET = _BASE_PATH + "objects/target.png" diff --git a/bricks/ev3dev/modules/pybricks/messaging.py b/bricks/ev3dev/modules/pybricks/messaging.py index 093ba1eb4..37dcaf2ed 100644 --- a/bricks/ev3dev/modules/pybricks/messaging.py +++ b/bricks/ev3dev/modules/pybricks/messaging.py @@ -5,8 +5,13 @@ from uerrno import ECONNRESET from ustruct import pack, unpack -from pybricks.bluetooth import (resolve, BDADDR_ANY, ThreadingRFCOMMServer, - ThreadingRFCOMMClient, StreamRequestHandler) +from pybricks.bluetooth import ( + resolve, + BDADDR_ANY, + ThreadingRFCOMMServer, + ThreadingRFCOMMClient, + StreamRequestHandler, +) class Mailbox: @@ -91,7 +96,7 @@ class LogicMailbox(Mailbox): """ def encode(self, value): - return b'\x01' if value else b'\x00' + return b"\x01" if value else b"\x00" def decode(self, payload): return bool(payload[0]) @@ -105,10 +110,10 @@ class NumericMailbox(Mailbox): """ def encode(self, value): - return pack(' 0 and length == 0: - print(*headers, sep=', ', file=self.file) + print(*headers, sep=", ", file=self.file) def log(self, *values): - print(*values, sep=', ', file=self.file) + print(*values, sep=", ", file=self.file) def __repr__(self): self.file.seek(0, 0) diff --git a/bricks/ev3dev/modules/pybricks/uev3dev/_alsa.py b/bricks/ev3dev/modules/pybricks/uev3dev/_alsa.py index 4c4bc77e2..5529ef178 100644 --- a/bricks/ev3dev/modules/pybricks/uev3dev/_alsa.py +++ b/bricks/ev3dev/modules/pybricks/uev3dev/_alsa.py @@ -8,8 +8,8 @@ from uctypes import addressof -_alsa = ffi.open('libasound.so.2') -_strerror = _alsa.func('s', 'snd_strerror', 'i') +_alsa = ffi.open("libasound.so.2") +_strerror = _alsa.func("s", "snd_strerror", "i") def _check_error(err): @@ -22,31 +22,33 @@ def __init__(self, message): super(AlsaError, self).__init__(message) -class Mixer(): - _open = _alsa.func('i', 'snd_mixer_open', 'pi') - _close = _alsa.func('i', 'snd_mixer_close', 'p') - _attach = _alsa.func('i', 'snd_mixer_attach', 'ps') - _load = _alsa.func('i', 'snd_mixer_load', 'p') - - _selem_register = _alsa.func('i', 'snd_mixer_selem_register', 'ppp') - _selem_register = _alsa.func('i', 'snd_mixer_selem_register', 'ppp') - _selem_id_sizeof = _alsa.func('p', 'snd_mixer_selem_id_sizeof', '') - _selem_id_set_index = _alsa.func('v', 'snd_mixer_selem_id_set_index', 'pI') - _selem_id_set_name = _alsa.func('v', 'snd_mixer_selem_id_set_name', 'ps') - _find_selem = _alsa.func('p', 'snd_mixer_find_selem', 'pP') - _selem_get_playback_volume_range = \ - _alsa.func('i', 'snd_mixer_selem_get_playback_volume_range', 'ppp') - _selem_set_playback_volume_all = \ - _alsa.func('i', 'snd_mixer_selem_set_playback_volume_all', 'pl') +class Mixer: + _open = _alsa.func("i", "snd_mixer_open", "pi") + _close = _alsa.func("i", "snd_mixer_close", "p") + _attach = _alsa.func("i", "snd_mixer_attach", "ps") + _load = _alsa.func("i", "snd_mixer_load", "p") + + _selem_register = _alsa.func("i", "snd_mixer_selem_register", "ppp") + _selem_register = _alsa.func("i", "snd_mixer_selem_register", "ppp") + _selem_id_sizeof = _alsa.func("p", "snd_mixer_selem_id_sizeof", "") + _selem_id_set_index = _alsa.func("v", "snd_mixer_selem_id_set_index", "pI") + _selem_id_set_name = _alsa.func("v", "snd_mixer_selem_id_set_name", "ps") + _find_selem = _alsa.func("p", "snd_mixer_find_selem", "pP") + _selem_get_playback_volume_range = _alsa.func( + "i", "snd_mixer_selem_get_playback_volume_range", "ppp" + ) + _selem_set_playback_volume_all = _alsa.func( + "i", "snd_mixer_selem_set_playback_volume_all", "pl" + ) def __init__(self): - self._mixer = bytearray(calcsize('P')) + self._mixer = bytearray(calcsize("P")) err = Mixer._open(self._mixer, 0) _check_error(err) - self._mixer = unpack('P', self._mixer)[0] + self._mixer = unpack("P", self._mixer)[0] try: # use default sound card - err = Mixer._attach(self._mixer, 'default') + err = Mixer._attach(self._mixer, "default") _check_error(err) err = Mixer._selem_register(self._mixer, 0, 0) _check_error(err) @@ -55,30 +57,28 @@ def __init__(self): self._id_data = bytearray(Mixer._selem_id_sizeof()) self._id = addressof(self._id_data) - min = bytearray(calcsize('l')) - max = bytearray(calcsize('l')) + min = bytearray(calcsize("l")) + max = bytearray(calcsize("l")) # get PCM volume control Mixer._selem_id_set_index(self._id, 0) - Mixer._selem_id_set_name(self._id, 'PCM') + Mixer._selem_id_set_name(self._id, "PCM") self._pcm_elem = Mixer._find_selem(self._mixer, self._id) if not self._pcm_elem: raise AlsaError('Could not find "PCM" mixer element') - Mixer._selem_get_playback_volume_range(self._pcm_elem, - addressof(min), - addressof(max)) - self._pcm_min = unpack('l', min)[0] - self._pcm_max = unpack('l', max)[0] + Mixer._selem_get_playback_volume_range(self._pcm_elem, addressof(min), addressof(max)) + self._pcm_min = unpack("l", min)[0] + self._pcm_max = unpack("l", max)[0] # get Beep volume control Mixer._selem_id_set_index(self._id, 0) - Mixer._selem_id_set_name(self._id, 'Beep') + Mixer._selem_id_set_name(self._id, "Beep") self._beep_elem = Mixer._find_selem(self._mixer, self._id) if not self._beep_elem: raise AlsaError('Could not find "Beep" mixer element') Mixer._selem_get_playback_volume_range(self._beep_elem, min, max) - self._beep_min = unpack('l', min)[0] - self._beep_max = unpack('l', max)[0] + self._beep_min = unpack("l", min)[0] + self._beep_max = unpack("l", max)[0] except: Mixer._close(self._mixer) raise @@ -101,32 +101,31 @@ def set_beep_volume(self, volume): Mixer._selem_set_playback_volume_all(self._beep_elem, volume) -class PCM(): - _open = _alsa.func('i', 'snd_pcm_open', 'pPIi') - _writei = _alsa.func('l', 'snd_pcm_writei', 'ppL') - _prepare = _alsa.func('l', 'snd_pcm_prepare', 'p') - _drop = _alsa.func('l', 'snd_pcm_drop', 'p') - _drain = _alsa.func('l', 'snd_pcm_drain', 'p') - _close = _alsa.func('l', 'snd_pcm_close', 'p') - _hw_params = _alsa.func('i', 'snd_pcm_hw_params', 'pp') - _hw_params_sizeof = _alsa.func('p', 'snd_pcm_hw_params_sizeof', '') - _hw_params_any = _alsa.func('i', 'snd_pcm_hw_params_any', 'pp') - _hw_params_set_access = _alsa.func('i', 'snd_pcm_hw_params_set_access', 'ppI') - _hw_params_set_format = _alsa.func('i', 'snd_pcm_hw_params_set_format', 'ppI') - _hw_params_set_channels = _alsa.func('i', 'snd_pcm_hw_params_set_channels', 'ppI') - _hw_params_set_rate = _alsa.func('i', 'snd_pcm_hw_params_set_rate', 'ppIi') - _hw_params_get_period_size = \ - _alsa.func('i', 'snd_pcm_hw_params_get_period_size', 'ppp') +class PCM: + _open = _alsa.func("i", "snd_pcm_open", "pPIi") + _writei = _alsa.func("l", "snd_pcm_writei", "ppL") + _prepare = _alsa.func("l", "snd_pcm_prepare", "p") + _drop = _alsa.func("l", "snd_pcm_drop", "p") + _drain = _alsa.func("l", "snd_pcm_drain", "p") + _close = _alsa.func("l", "snd_pcm_close", "p") + _hw_params = _alsa.func("i", "snd_pcm_hw_params", "pp") + _hw_params_sizeof = _alsa.func("p", "snd_pcm_hw_params_sizeof", "") + _hw_params_any = _alsa.func("i", "snd_pcm_hw_params_any", "pp") + _hw_params_set_access = _alsa.func("i", "snd_pcm_hw_params_set_access", "ppI") + _hw_params_set_format = _alsa.func("i", "snd_pcm_hw_params_set_format", "ppI") + _hw_params_set_channels = _alsa.func("i", "snd_pcm_hw_params_set_channels", "ppI") + _hw_params_set_rate = _alsa.func("i", "snd_pcm_hw_params_set_rate", "ppIi") + _hw_params_get_period_size = _alsa.func("i", "snd_pcm_hw_params_get_period_size", "ppp") _STREAM_PLAYBACK = 0 _ACCESS_RW_INTERLEAVED = 3 _FORMAT_S16_LE = 2 def __init__(self): - self._pcm = bytearray(calcsize('P')) - err = PCM._open(self._pcm, 'default', PCM._STREAM_PLAYBACK, 0) + self._pcm = bytearray(calcsize("P")) + err = PCM._open(self._pcm, "default", PCM._STREAM_PLAYBACK, 0) _check_error(err) - self._pcm = unpack('P', self._pcm)[0] + self._pcm = unpack("P", self._pcm)[0] try: self._hp = bytearray(PCM._hw_params_sizeof()) err = PCM._hw_params_any(self._pcm, self._hp) @@ -141,26 +140,22 @@ def close(self): self._pcm = None def play(self, sound_file, cancel_token=None): - err = PCM._hw_params_set_access(self._pcm, self._hp, - PCM._ACCESS_RW_INTERLEAVED) + err = PCM._hw_params_set_access(self._pcm, self._hp, PCM._ACCESS_RW_INTERLEAVED) _check_error(err) - err = PCM._hw_params_set_format(self._pcm, self._hp, - PCM._FORMAT_S16_LE) + err = PCM._hw_params_set_format(self._pcm, self._hp, PCM._FORMAT_S16_LE) _check_error(err) - err = PCM._hw_params_set_channels(self._pcm, self._hp, - sound_file._channels) + err = PCM._hw_params_set_channels(self._pcm, self._hp, sound_file._channels) _check_error(err) - err = PCM._hw_params_set_rate(self._pcm, self._hp, - sound_file._samplerate, 0) + err = PCM._hw_params_set_rate(self._pcm, self._hp, sound_file._samplerate, 0) _check_error(err) err = PCM._hw_params(self._pcm, self._hp) _check_error(err) - frames = bytearray(calcsize('L')) - direction = bytearray(calcsize('i')) + frames = bytearray(calcsize("L")) + direction = bytearray(calcsize("i")) err = PCM._hw_params_get_period_size(self._hp, frames, direction) _check_error(err) - frames = unpack('L', frames)[0] + frames = unpack("L", frames)[0] for buf, count in sound_file._read(frames): if cancel_token and cancel_token.canceled: diff --git a/bricks/ev3dev/modules/pybricks/uev3dev/_wand.py b/bricks/ev3dev/modules/pybricks/uev3dev/_wand.py index c8f987e96..4d9efa3cb 100644 --- a/bricks/ev3dev/modules/pybricks/uev3dev/_wand.py +++ b/bricks/ev3dev/modules/pybricks/uev3dev/_wand.py @@ -10,31 +10,31 @@ from uctypes import bytearray_at -_wand = ffi.open('libMagickWand-6.Q16.so.3') -_genisis = _wand.func('v', 'MagickWandGenesis', '') -_terminus = _wand.func('v', 'MagickWandTerminus', '') -_new = _wand.func('p', 'NewMagickWand', '') -_destroy = _wand.func('p', 'DestroyMagickWand', 'p') -_clear_exception = _wand.func('i', 'MagickClearException', 'p') -_get_exception = _wand.func('s', 'MagickGetException', 'pp') +_wand = ffi.open("libMagickWand-6.Q16.so.3") +_genisis = _wand.func("v", "MagickWandGenesis", "") +_terminus = _wand.func("v", "MagickWandTerminus", "") +_new = _wand.func("p", "NewMagickWand", "") +_destroy = _wand.func("p", "DestroyMagickWand", "p") +_clear_exception = _wand.func("i", "MagickClearException", "p") +_get_exception = _wand.func("s", "MagickGetException", "pp") # _get_exception_type = _wand.func('I', 'MagickGetExceptionType', 'p') -_relinquish_memory = _wand.func('p', 'MagickRelinquishMemory', 'p') -_read_image = _wand.func('I', 'MagickReadImage', 'pP') -_write_image = _wand.func('I', 'MagickWriteImage', 'pP') -_export_image_pixels = _wand.func('i', 'MagickExportImagePixels', 'pPPPPPIp') -_reset_iterator = _wand.func('v', 'MagickResetIterator', 'p') -_border_image = _wand.func('i', 'MagickBorderImage', 'pPPPI') -_extent_image = _wand.func('i', 'MagickExtentImage', 'pPPPP') - -_get_image_width = _wand.func('p', 'MagickGetImageWidth', 'p') -_get_image_height = _wand.func('p', 'MagickGetImageHeight', 'p') -_get_image_depth = _wand.func('p', 'MagickGetImageDepth', 'p') -_set_image_depth = _wand.func('i', 'MagickSetImageDepth', 'pP') -_get_image_format = _wand.func('s', 'MagickGetImageFormat', 'p') -_set_image_format = _wand.func('i', 'MagickSetImageFormat', 'pP') -_get_image_blob = _wand.func('p', 'MagickGetImageBlob', 'pp') -_get_image_gravity = _wand.func('I', 'MagickGetImageGravity', 'p') -_set_image_gravity = _wand.func('i', 'MagickSetImageGravity', 'pI') +_relinquish_memory = _wand.func("p", "MagickRelinquishMemory", "p") +_read_image = _wand.func("I", "MagickReadImage", "pP") +_write_image = _wand.func("I", "MagickWriteImage", "pP") +_export_image_pixels = _wand.func("i", "MagickExportImagePixels", "pPPPPPIp") +_reset_iterator = _wand.func("v", "MagickResetIterator", "p") +_border_image = _wand.func("i", "MagickBorderImage", "pPPPI") +_extent_image = _wand.func("i", "MagickExtentImage", "pPPPP") + +_get_image_width = _wand.func("p", "MagickGetImageWidth", "p") +_get_image_height = _wand.func("p", "MagickGetImageHeight", "p") +_get_image_depth = _wand.func("p", "MagickGetImageDepth", "p") +_set_image_depth = _wand.func("i", "MagickSetImageDepth", "pP") +_get_image_format = _wand.func("s", "MagickGetImageFormat", "p") +_set_image_format = _wand.func("i", "MagickSetImageFormat", "pP") +_get_image_blob = _wand.func("p", "MagickGetImageBlob", "pp") +_get_image_gravity = _wand.func("I", "MagickGetImageGravity", "p") +_set_image_gravity = _wand.func("i", "MagickSetImageGravity", "pI") # global library init (a well-mannered program would call _terminus() later) _genisis() @@ -42,10 +42,10 @@ class MagickWandError(Exception): def __init__(self, severity, desc): - super(MagickWandError, self).__init__('{}: {}'.format(severity, desc)) + super(MagickWandError, self).__init__("{}: {}".format(severity, desc)) -class MagickWand(): +class MagickWand: """Object for image manipulation using ImageMagick .. note:: Since micropython does not support ``__del__()`` on user-defined @@ -53,6 +53,7 @@ class MagickWand(): to free the underlying resources. """ + def __init__(self): self._wand = _new() @@ -69,11 +70,11 @@ def __exit__(self, exc_type, exc_val, traceback): self.__del__() def _raise_error(self): - severity = bytearray(calcsize('I')) + severity = bytearray(calcsize("I")) desc = _get_exception(self._wand, severity) # FIXME: this leaks desc (need to call _relinquish_memory()) but not # sure how to marshal pointer to string - severity = unpack('I', severity)[0] + severity = unpack("I", severity)[0] _clear_exception(self._wand) raise MagickWandError(severity, desc) @@ -145,10 +146,10 @@ def _set_image_gravity(self, gravity): def image_blob(self): """Gets the image raw binary data""" _reset_iterator(self._wand) - length = bytearray(calcsize('P')) + length = bytearray(calcsize("P")) data = _get_image_blob(self._wand, length) try: - length = unpack('P', length)[0] + length = unpack("P", length)[0] # It is a bit inefficient to copy the data, but it is needed for # seamless memory management return bytearray_at(data, length)[:] @@ -167,15 +168,13 @@ def export_image_pixels(self, x, y, columns, rows, map_, storage, pixels): storage (StorageType): the pixel data type pixels (bytearray): something big enough to hold all of the data """ - ok = _export_image_pixels(self._wand, x, y, columns, rows, map_, - storage, pixels) + ok = _export_image_pixels(self._wand, x, y, columns, rows, map_, storage, pixels) if not ok: self._raise_error() def border_image(self, border_color, width, height, compose): """Surrounds the image with a border""" - ok = _border_image(self._wand, border_color._wand, int(width), - int(height), int(compose)) + ok = _border_image(self._wand, border_color._wand, int(width), int(height), int(compose)) if not ok: self._raise_error() @@ -193,21 +192,22 @@ def extent_image(self, width, height, x, y): if not ok: self._raise_error() -_new_pixel_wand = _wand.func('p', 'NewPixelWand', '') -_destroy_pixel_wand = _wand.func('p', 'DestroyPixelWand', 'p') -_pixel_get_exception = _wand.func('s', 'PixelGetException', 'pp') -_pixel_clear_exception = _wand.func('i', 'PixelClearException', 'p') -_pixel_get_color = _wand.func('s', 'PixelGetColorAsString', 'p') -_pixel_set_color = _wand.func('i', 'PixelSetColor', 'pP') +_new_pixel_wand = _wand.func("p", "NewPixelWand", "") +_destroy_pixel_wand = _wand.func("p", "DestroyPixelWand", "p") +_pixel_get_exception = _wand.func("s", "PixelGetException", "pp") +_pixel_clear_exception = _wand.func("i", "PixelClearException", "p") + +_pixel_get_color = _wand.func("s", "PixelGetColorAsString", "p") +_pixel_set_color = _wand.func("i", "PixelSetColor", "pP") class PixelError(Exception): def __init__(self, severity, desc): - super(PixelError, self).__init__('{}: {}'.format(severity, desc)) + super(PixelError, self).__init__("{}: {}".format(severity, desc)) -class PixelWand(): +class PixelWand: def __init__(self): self._wand = _new_pixel_wand() @@ -229,16 +229,16 @@ def _set_color(self, color): self._raise_error() def _raise_error(self): - severity = bytearray(calcsize('I')) + severity = bytearray(calcsize("I")) desc = _pixel_get_exception(self._wand, severity) # TODO: we could be leaking desc here (the docs are not clear if it # needs to be freed or not) - severity = unpack('I', severity)[0] + severity = unpack("I", severity)[0] _pixel_clear_exception(self._wand) raise PixelError(severity, desc) -class StorageType(): +class StorageType: UNDEFINED = 0 CHAR = 1 DOUBLE = 2 @@ -249,7 +249,7 @@ class StorageType(): SHORT = 7 -class Gravity(): +class Gravity: UNDEFINED = 0 FORGET = 1 NORTH_WEST = 2 @@ -263,7 +263,7 @@ class Gravity(): SOUTH_EAST = 10 -class CompositeOp(): +class CompositeOp: UNDEFINED = 0 ALPHA = 1 ATOP = 2 diff --git a/bricks/ev3dev/modules/pybricks/uev3dev/display.py b/bricks/ev3dev/modules/pybricks/uev3dev/display.py index 186fd0fa3..e085735b3 100644 --- a/bricks/ev3dev/modules/pybricks/uev3dev/display.py +++ b/bricks/ev3dev/modules/pybricks/uev3dev/display.py @@ -33,83 +33,81 @@ _ALIGN1, _ALIGN2, _ALIGN3 = (0, 0, 0) if ULONG == UINT32 else (4, 8, 12) _fb_fix_screeninfo = { - 'id_name': (ARRAY | 0, UINT8 | 16), - 'smem_start': ULONG | 16, - 'smem_len': UINT32 | 20 + _ALIGN1, - 'type': UINT32 | 24 + _ALIGN1, - 'type_aux': UINT32 | 28 + _ALIGN1, - 'visual': UINT32 | 32 + _ALIGN1, - 'xpanstep': UINT16 | 36 + _ALIGN1, - 'ypanstep': UINT16 | 38 + _ALIGN1, - 'ywrapstep': UINT16 | 40 + _ALIGN1, - 'line_length': UINT32 | 44 + _ALIGN1, - 'mmio_start': ULONG | 48 + _ALIGN2, - 'mmio_len': UINT32 | 52 + _ALIGN3, - 'accel': UINT32 | 56 + _ALIGN3, - 'capabilities': UINT16 | 60 + _ALIGN3, - 'reserved0': UINT16 | 62 + _ALIGN3, - 'reserved1': UINT16 | 64 + _ALIGN3, + "id_name": (ARRAY | 0, UINT8 | 16), + "smem_start": ULONG | 16, + "smem_len": UINT32 | 20 + _ALIGN1, + "type": UINT32 | 24 + _ALIGN1, + "type_aux": UINT32 | 28 + _ALIGN1, + "visual": UINT32 | 32 + _ALIGN1, + "xpanstep": UINT16 | 36 + _ALIGN1, + "ypanstep": UINT16 | 38 + _ALIGN1, + "ywrapstep": UINT16 | 40 + _ALIGN1, + "line_length": UINT32 | 44 + _ALIGN1, + "mmio_start": ULONG | 48 + _ALIGN2, + "mmio_len": UINT32 | 52 + _ALIGN3, + "accel": UINT32 | 56 + _ALIGN3, + "capabilities": UINT16 | 60 + _ALIGN3, + "reserved0": UINT16 | 62 + _ALIGN3, + "reserved1": UINT16 | 64 + _ALIGN3, } _fb_bitfield = { - 'offset': UINT32 | 0, - 'length': UINT32 | 4, - 'msb_right': UINT32 | 8, + "offset": UINT32 | 0, + "length": UINT32 | 4, + "msb_right": UINT32 | 8, } _fb_var_screeninfo = { - 'xres': UINT32 | 0, - 'yres': UINT32 | 4, - 'xres_virtual': UINT32 | 8, - 'yres_virtual': UINT32 | 12, - 'xoffset': UINT32 | 16, - 'yoffset': UINT32 | 20, - 'bits_per_pixel': UINT32 | 24, - 'grayscale': UINT32 | 28, - 'red': (32, _fb_bitfield), - 'green': (44, _fb_bitfield), - 'blue': (56, _fb_bitfield), - 'transp': (68, _fb_bitfield), - 'nonstd': UINT32 | 80, - 'activate': UINT32 | 84, - 'height': UINT32 | 88, - 'width': UINT32 | 92, - 'accel_flags': UINT32 | 96, - 'pixclock': UINT32 | 100, - 'left_margin': UINT32 | 104, - 'right_margin': UINT32 | 108, - 'upper_margin': UINT32 | 112, - 'lower_margin': UINT32 | 116, - 'hsync_len': UINT32 | 120, - 'vsync_len': UINT32 | 124, - 'sync': UINT32 | 128, - 'vmode': UINT32 | 132, - 'rotate': UINT32 | 136, - 'colorspace': UINT32 | 140, - 'reserved0': UINT32 | 144, - 'reserved1': UINT32 | 148, - 'reserved2': UINT32 | 152, - 'reserved3': UINT32 | 156, + "xres": UINT32 | 0, + "yres": UINT32 | 4, + "xres_virtual": UINT32 | 8, + "yres_virtual": UINT32 | 12, + "xoffset": UINT32 | 16, + "yoffset": UINT32 | 20, + "bits_per_pixel": UINT32 | 24, + "grayscale": UINT32 | 28, + "red": (32, _fb_bitfield), + "green": (44, _fb_bitfield), + "blue": (56, _fb_bitfield), + "transp": (68, _fb_bitfield), + "nonstd": UINT32 | 80, + "activate": UINT32 | 84, + "height": UINT32 | 88, + "width": UINT32 | 92, + "accel_flags": UINT32 | 96, + "pixclock": UINT32 | 100, + "left_margin": UINT32 | 104, + "right_margin": UINT32 | 108, + "upper_margin": UINT32 | 112, + "lower_margin": UINT32 | 116, + "hsync_len": UINT32 | 120, + "vsync_len": UINT32 | 124, + "sync": UINT32 | 128, + "vmode": UINT32 | 132, + "rotate": UINT32 | 136, + "colorspace": UINT32 | 140, + "reserved0": UINT32 | 144, + "reserved1": UINT32 | 148, + "reserved2": UINT32 | 152, + "reserved3": UINT32 | 156, } -class _Screen(): +class _Screen: """Object that represents a screen""" BLACK = 0 WHITE = ~0 def __init__(self): - self._fbdev = open('/dev/fb0', 'r+b') + self._fbdev = open("/dev/fb0", "r+b") self._fix_info_data = bytearray(sizeof(_fb_fix_screeninfo)) fd = self._fbdev.fileno() ioctl(fd, _FBIOGET_FSCREENINFO, self._fix_info_data) - self._fix_info = struct(addressof(self._fix_info_data), - _fb_fix_screeninfo) + self._fix_info = struct(addressof(self._fix_info_data), _fb_fix_screeninfo) self._var_info_data = bytearray(sizeof(_fb_var_screeninfo)) ioctl(fd, _FBIOGET_VSCREENINFO, self._var_info_data) - self._var_info = struct(addressof(self._var_info_data), - _fb_var_screeninfo) + self._var_info = struct(addressof(self._var_info_data), _fb_var_screeninfo) self._fb_data = {} self._mmap = mmap(fd, self._fix_info.smem_len) @@ -151,13 +149,15 @@ def framebuffer(self): format = RGB565 else: raise RuntimeError("Unsupported pixel depth") - fbuf = FrameBuffer(data, self.width, self.height, format, - self._fix_info.line_length * 8 // self.bpp) + fbuf = FrameBuffer( + data, self.width, self.height, format, self._fix_info.line_length * 8 // self.bpp + ) return fbuf, data -class Display(): +class Display: """Object that represents a display screen.""" + def __init__(self): self._screen = _Screen() self._fb, self._data = self._screen.framebuffer() @@ -181,7 +181,7 @@ def text_pixels(self, text, clear, x, y, color, font): color = _Screen.BLACK # TODO: micropython framebuf only has one font # TODO: Discuss where origin should be for text and pictures (micropython vs. EV3-G) - self._fb.text(str(text), x, y-7, color) + self._fb.text(str(text), x, y - 7, color) self._screen.update(self._data) def scroll(self, font=0): @@ -225,12 +225,13 @@ def reset_screen(self): self._screen.update(self._data) -class ImageFile(): +class ImageFile: """Object that represents an image file Parameters: filename (str): The file path """ + def __init__(self, filename, display): with MagickWand() as wand: wand.read_image(filename) @@ -243,10 +244,9 @@ def __init__(self, filename, display): # image pass - wand.image_format = 'GRAY' + wand.image_format = "GRAY" wand.image_depth = 1 # then convert to micropython framebuf so we can blit data = wand.image_blob - self._framebuf = FrameBuffer(data, wand.image_width, - wand.image_height, MONO_HLSB) + self._framebuf = FrameBuffer(data, wand.image_width, wand.image_height, MONO_HLSB) diff --git a/bricks/ev3dev/modules/pybricks/uev3dev/i2c.py b/bricks/ev3dev/modules/pybricks/uev3dev/i2c.py index aa206bbcb..b2164a622 100644 --- a/bricks/ev3dev/modules/pybricks/uev3dev/i2c.py +++ b/bricks/ev3dev/modules/pybricks/uev3dev/i2c.py @@ -39,9 +39,9 @@ _I2C_SMBUS_BLOCK_MAX = 32 _i2c_smbus_data = { - 'byte': uctypes.UINT8 | 0, - 'word': uctypes.UINT16 | 0, - 'block': (uctypes.ARRAY | 0, uctypes.UINT8 | (_I2C_SMBUS_BLOCK_MAX + 2)) + "byte": uctypes.UINT8 | 0, + "word": uctypes.UINT16 | 0, + "block": (uctypes.ARRAY | 0, uctypes.UINT8 | (_I2C_SMBUS_BLOCK_MAX + 2)), } _size_of_i2c_smbus_data = uctypes.sizeof(_i2c_smbus_data) @@ -72,16 +72,16 @@ _I2C_SMBUS = 0x0720 _i2c_smbus_ioctl_data = { - 'read_write': uctypes.UINT8 | 0, - 'command': uctypes.UINT8 | 1, - 'size': uctypes.UINT32 | 4, - 'data': uctypes.PTR | 8 + "read_write": uctypes.UINT8 | 0, + "command": uctypes.UINT8 | 1, + "size": uctypes.UINT32 | 4, + "data": uctypes.PTR | 8, } _size_of_i2c_smbus_ioctl_data = uctypes.sizeof(_i2c_smbus_ioctl_data) -class SMBus(): +class SMBus: """Micropython implementation of SMBus""" _slave = 0 @@ -90,37 +90,31 @@ def __init__(self, path): """Create a new SMBus instance :param string path: The path to the I2C device node, e.g. ``/dev/i2c0``. """ - self._devnode = open(path, 'w+') + self._devnode = open(path, "w+") self._fd = self._devnode.fileno() flags = bytes(4) ioctl(self._fd, _I2C_FUNCS, flags) - flags = uctypes.struct(uctypes.addressof(flags), { - 'flags': uctypes.UINT32 # unsigned long - }).flags + flags = uctypes.struct( + uctypes.addressof(flags), {"flags": uctypes.UINT32} # unsigned long + ).flags self._func = { - 'i2c': bool(flags & _I2C_FUNC_I2C), - 'ten_bit_addr': bool(flags & _I2C_FUNC_10BIT_ADDR), - 'protocol_mangling': bool(flags & _I2C_FUNC_PROTOCOL_MANGLING), - 'smbus_pec': bool(flags & _I2C_FUNC_SMBUS_PEC), - 'no_start': bool(flags & _I2C_FUNC_NOSTART), - 'slave': bool(flags & _I2C_FUNC_SLAVE), - 'smbus_block_proc_call': bool(flags & - _I2C_FUNC_SMBUS_BLOCK_PROC_CALL), - 'smbus_quick': bool(flags & _I2C_FUNC_SMBUS_QUICK), - 'smbus_read_byte': bool(flags & _I2C_FUNC_SMBUS_READ_BYTE), - 'smbus_write_byte': bool(flags & _I2C_FUNC_SMBUS_WRITE_BYTE), - 'smbus_write_data': bool(flags & _I2C_FUNC_SMBUS_WRITE_BYTE_DATA), - 'smbus_read_word_data': bool(flags & - _I2C_FUNC_SMBUS_READ_WORD_DATA), - 'smbus_write_word_data': bool(flags & - _I2C_FUNC_SMBUS_WRITE_WORD_DATA), - 'smbus_proc_call': bool(flags & _I2C_FUNC_SMBUS_PROC_CALL), - 'smbus_read_block_data': bool(flags & - _I2C_FUNC_SMBUS_READ_BLOCK_DATA), - 'smbus_read_i2c_block': bool(flags & - _I2C_FUNC_SMBUS_READ_I2C_BLOCK), - 'smbus_write_i2c_block': bool(flags & - _I2C_FUNC_SMBUS_WRITE_I2C_BLOCK), + "i2c": bool(flags & _I2C_FUNC_I2C), + "ten_bit_addr": bool(flags & _I2C_FUNC_10BIT_ADDR), + "protocol_mangling": bool(flags & _I2C_FUNC_PROTOCOL_MANGLING), + "smbus_pec": bool(flags & _I2C_FUNC_SMBUS_PEC), + "no_start": bool(flags & _I2C_FUNC_NOSTART), + "slave": bool(flags & _I2C_FUNC_SLAVE), + "smbus_block_proc_call": bool(flags & _I2C_FUNC_SMBUS_BLOCK_PROC_CALL), + "smbus_quick": bool(flags & _I2C_FUNC_SMBUS_QUICK), + "smbus_read_byte": bool(flags & _I2C_FUNC_SMBUS_READ_BYTE), + "smbus_write_byte": bool(flags & _I2C_FUNC_SMBUS_WRITE_BYTE), + "smbus_write_data": bool(flags & _I2C_FUNC_SMBUS_WRITE_BYTE_DATA), + "smbus_read_word_data": bool(flags & _I2C_FUNC_SMBUS_READ_WORD_DATA), + "smbus_write_word_data": bool(flags & _I2C_FUNC_SMBUS_WRITE_WORD_DATA), + "smbus_proc_call": bool(flags & _I2C_FUNC_SMBUS_PROC_CALL), + "smbus_read_block_data": bool(flags & _I2C_FUNC_SMBUS_READ_BLOCK_DATA), + "smbus_read_i2c_block": bool(flags & _I2C_FUNC_SMBUS_READ_I2C_BLOCK), + "smbus_write_i2c_block": bool(flags & _I2C_FUNC_SMBUS_WRITE_I2C_BLOCK), } def set_address(self, address): @@ -201,21 +195,19 @@ def read_i2c_block_data(self, command, length): else: size = _I2C_SMBUS_I2C_BLOCK_DATA self._access(_I2C_SMBUS_READ, command, size, data) - return data.block[1:][:data.block[0]] + return data.block[1:][: data.block[0]] def write_i2c_block_data(self, command, values): b = bytearray(_size_of_i2c_smbus_data) data = uctypes.struct(uctypes.addressof(b), _i2c_smbus_data) values = values[:32] data.block = [len(values)] + values - self._access(_I2C_SMBUS_WRITE, command, _I2C_SMBUS_I2C_BLOCK_BROKEN, - data) + self._access(_I2C_SMBUS_WRITE, command, _I2C_SMBUS_I2C_BLOCK_BROKEN, data) def block_process_call(self, command, values): b = bytearray(_size_of_i2c_smbus_data) data = uctypes.struct(uctypes.addressof(b), _i2c_smbus_data) values = values[:32] data.block = [len(values)] + values - self._access(_I2C_SMBUS_WRITE, command, _I2C_SMBUS_BLOCK_PROC_CALL, - data) - return data.block[1:][:data.block[0]] + self._access(_I2C_SMBUS_WRITE, command, _I2C_SMBUS_BLOCK_PROC_CALL, data) + return data.block[1:][: data.block[0]] diff --git a/bricks/ev3dev/modules/pybricks/uev3dev/messaging.py b/bricks/ev3dev/modules/pybricks/uev3dev/messaging.py index b9f965992..09bcde5ad 100644 --- a/bricks/ev3dev/modules/pybricks/uev3dev/messaging.py +++ b/bricks/ev3dev/modules/pybricks/uev3dev/messaging.py @@ -19,41 +19,40 @@ _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) + return ":".join(string) -class BluetoothRemote(): +class BluetoothRemote: """Object that represents a Bluetooth connection to a remote EV3 Brick. Parameters: name (str): The MAC address of the remote brick """ + def __init__(self, name): # TODO: Need a way to convert name to MAC address (maybe) self._sock = socket(_AF_BLUETOOTH, SOCK_STREAM, _BTPROTO_RFCOMM) @@ -71,8 +70,9 @@ def close(self): self._sock.close() -class BluetoothServer(): +class BluetoothServer: """Object that enables incoming Bluetooth connections from an EV3""" + def __init__(self): self._sock = socket(_AF_BLUETOOTH, SOCK_STREAM, _BTPROTO_RFCOMM) @@ -94,7 +94,7 @@ def _accept(self): client, addr_data = self._sock.accept() try: addr = struct(addressof(addr_data), _sockaddr_rc) - debug_print('client', _ba2str(addr.rc_bdaddr)) + debug_print("client", _ba2str(addr.rc_bdaddr)) while True: data = client.recv(1) debug_print(data) @@ -106,7 +106,7 @@ def close(self): self._sock.close() -class Messaging(): +class Messaging: def wait_update(self, title): # FIXME: implement messaging self._lock = _thread.allocate_lock() diff --git a/bricks/ev3dev/modules/pybricks/uev3dev/sound.py b/bricks/ev3dev/modules/pybricks/uev3dev/sound.py index f2a83a005..cd4429cea 100644 --- a/bricks/ev3dev/modules/pybricks/uev3dev/sound.py +++ b/bricks/ev3dev/modules/pybricks/uev3dev/sound.py @@ -25,7 +25,7 @@ # TODO: os.SEEK_SET is not defined in micropython-lib _SEEK_SET = 0 -_BEEP_DEV = '/dev/input/by-path/platform-sound-event' +_BEEP_DEV = "/dev/input/by-path/platform-sound-event" # stuff from linux/input.h and linux/input-event-codes.h @@ -33,82 +33,83 @@ _EV_SND = 0x12 _SND_TONE = 0x02 _input_event = { - 'time': UINT64 | 0, # struct timeval - 'type': UINT16 | 8, - 'code': UINT16 | 10, - 'value': INT32 | 12, + "time": UINT64 | 0, # struct timeval + "type": UINT16 | 8, + "code": UINT16 | 10, + "value": INT32 | 12, } # libsndfile -_libsndfile = ffi.open('libsndfile.so.1') +_libsndfile = ffi.open("libsndfile.so.1") _sf_count_t = UINT64 _SF_INFO = { - 'frames': _sf_count_t | 0, - 'samplerate': INT32 | 8, - 'channels': INT32 | 12, - 'format': INT32 | 16, - 'sections': INT32 | 20, - 'seekable': INT32 | 24, + "frames": _sf_count_t | 0, + "samplerate": INT32 | 8, + "channels": INT32 | 12, + "format": INT32 | 16, + "sections": INT32 | 20, + "seekable": INT32 | 24, } _SMF_READ = 0x10 # FIXME: micropython does not have 64-bit integer, using double for now -_sf_open = _libsndfile.func('p', 'sf_open', 'Pip') -_sf_close = _libsndfile.func('i', 'sf_close', 'p') -_sf_seek = _libsndfile.func('d', 'sf_seek', 'pdi') -_sf_readf_short = _libsndfile.func('d', 'sf_readf_short', 'ppd') -_sf_strerror = _libsndfile.func('s', 'sf_strerror', 'p') +_sf_open = _libsndfile.func("p", "sf_open", "Pip") +_sf_close = _libsndfile.func("i", "sf_close", "p") +_sf_seek = _libsndfile.func("d", "sf_seek", "pdi") +_sf_readf_short = _libsndfile.func("d", "sf_readf_short", "ppd") +_sf_strerror = _libsndfile.func("s", "sf_strerror", "p") # from lms2012 _NOTES = { - 'C4': 262, - 'D4': 294, - 'E4': 330, - 'F4': 349, - 'G4': 392, - 'A4': 440, - 'B4': 494, - 'C5': 523, - 'D5': 587, - 'E5': 659, - 'F5': 698, - 'G5': 784, - 'A5': 880, - 'B5': 988, - 'C6': 1047, - 'D6': 1175, - 'E6': 1319, - 'F6': 1397, - 'G6': 1568, - 'A6': 1760, - 'B6': 1976, - 'C#4': 277, - 'D#4': 311, - 'F#4': 370, - 'G#4': 415, - 'A#4': 466, - 'C#5': 554, - 'D#5': 622, - 'F#5': 740, - 'G#5': 831, - 'A#5': 932, - 'C#6': 1109, - 'D#6': 1245, - 'F#6': 1480, - 'G#6': 1661, - 'A#6': 1865, + "C4": 262, + "D4": 294, + "E4": 330, + "F4": 349, + "G4": 392, + "A4": 440, + "B4": 494, + "C5": 523, + "D5": 587, + "E5": 659, + "F5": 698, + "G5": 784, + "A5": 880, + "B5": 988, + "C6": 1047, + "D6": 1175, + "E6": 1319, + "F6": 1397, + "G6": 1568, + "A6": 1760, + "B6": 1976, + "C#4": 277, + "D#4": 311, + "F#4": 370, + "G#4": 415, + "A#4": 466, + "C#5": 554, + "D#5": 622, + "F#5": 740, + "G#5": 831, + "A#5": 932, + "C#6": 1109, + "D#6": 1245, + "F#6": 1480, + "G#6": 1661, + "A#6": 1865, } -class PlayType(): +class PlayType: """List of values for ``play_type`` in sound playback methods""" + WAIT = 0 """Play the sound once and wait until it is finished before returning""" ONCE = 1 @@ -117,10 +118,11 @@ class PlayType(): """Play the sound repeating in the background""" -class Sound(): +class Sound: """Object for making sounds""" + def __init__(self): - self._beep_dev = open(_BEEP_DEV, 'b+') + self._beep_dev = open(_BEEP_DEV, "b+") self._mixer = Mixer() self._pcm = PCM() self._tone_data = bytearray(sizeof(_input_event)) @@ -230,12 +232,13 @@ def __init__(self, message): super(SoundFileError, self).__init__(message) -class SoundFile(): +class SoundFile: """Class that represents a sound file. Parameters: path (str): The path to a sound file """ + def __init__(self, path): info_data = bytearray(sizeof(_SF_INFO)) info = struct(addressof(info_data), _SF_INFO) @@ -256,18 +259,18 @@ def close(self): def _read(self, frames, cancel_token=None): if not self._file: - raise RuntimeError('SoundFile has been closed') - frames_ = unpack('d', pack('Q', 0))[0] + raise RuntimeError("SoundFile has been closed") + frames_ = unpack("d", pack("Q", 0))[0] _sf_seek(self._file, frames_, _SEEK_SET) - buf = bytearray(frames * self._channels * calcsize('h')) + buf = bytearray(frames * self._channels * calcsize("h")) while True: if cancel_token and cancel_token.canceled: break # FIXME: micropython ffi doesn't have 64-bit integer type # double is the only 64-bit type, so using a hack to make it work - frames_ = unpack('d', pack('Q', frames))[0] + frames_ = unpack("d", pack("Q", frames))[0] readcount_ = _sf_readf_short(self._file, buf, frames_) - readcount = unpack('Q', pack('d', readcount_))[0] + readcount = unpack("Q", pack("d", readcount_))[0] if not readcount: break yield buf, readcount @@ -276,7 +279,7 @@ def _cancel_token(self): return _CancelToken() -class _CancelToken(): +class _CancelToken: def __init__(self): self.canceled = False diff --git a/bricks/ev3dev/modules/pybricks/uev3dev/util.py b/bricks/ev3dev/modules/pybricks/uev3dev/util.py index 19a9a4797..0ab463818 100644 --- a/bricks/ev3dev/modules/pybricks/uev3dev/util.py +++ b/bricks/ev3dev/modules/pybricks/uev3dev/util.py @@ -18,17 +18,17 @@ from uctypes import UINT32 from uctypes import UINT64 -_libc = ffi.open('libc.so.6') +_libc = ffi.open("libc.so.6") -_close = _libc.func('i', 'open', 'i') -_eventfd = _libc.func('i', 'eventfd', 'ii') -_errno = _libc.var('i', 'errno') -_write = _libc.func('i', 'write', 'iPi') +_close = _libc.func("i", "open", "i") +_eventfd = _libc.func("i", "eventfd", "ii") +_errno = _libc.var("i", "errno") +_write = _libc.func("i", "write", "iPi") _EFD_CLOEXEC = 0o2000000 -def debug_print(*args, sep=' ', end='\n'): +def debug_print(*args, sep=" ", end="\n"): """Print on stderr for debugging Parameters: @@ -41,7 +41,7 @@ def debug_print(*args, sep=' ', end='\n'): def _thread_runner(lock, function): if not lock.locked(): - raise RuntimeError('Must hold lock before starting thread') + raise RuntimeError("Must hold lock before starting thread") try: function() finally: @@ -67,8 +67,9 @@ def fork(*functions): l.release() -class Timer(): +class Timer: """Object that represents a timer""" + def __init__(self): self._start_time = 0 self.reset() @@ -107,7 +108,7 @@ def write_at_index(array, index, value): return tuple(l) -class Timeout(): +class Timeout: """Object for scheduling a callback. This is a pseudo replacement for ``threading.Timer``. @@ -180,7 +181,7 @@ def start(self): """Start running the timer""" with self._cancel_lock: if self._wait_lock.locked(): - raise RuntimeError('already started') + raise RuntimeError("already started") self._canceled = False self._wait_lock.acquire() _thread.start_new_thread(self._run, ()) diff --git a/bricks/ev3dev/modusignal.c b/bricks/ev3dev/modusignal.c index 85c6b5360..457ef975b 100644 --- a/bricks/ev3dev/modusignal.c +++ b/bricks/ev3dev/modusignal.c @@ -41,9 +41,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(usignal_pthread_kill_obj, usignal_pthread_kill) STATIC const mp_rom_map_elem_t usignal_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_usignal) }, { MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&usignal_pause_obj) }, -#if MICROPY_PY_THREAD + #if MICROPY_PY_THREAD { MP_ROM_QSTR(MP_QSTR_pthread_kill), MP_ROM_PTR(&usignal_pthread_kill_obj) }, -#endif // MICROPY_PY_THREAD + #endif // MICROPY_PY_THREAD { MP_ROM_QSTR(MP_QSTR_SIGHUP), MP_ROM_INT(SIGHUP) }, { MP_ROM_QSTR(MP_QSTR_SIGINT), MP_ROM_INT(SIGINT) }, { MP_ROM_QSTR(MP_QSTR_SIGTERM), MP_ROM_INT(SIGTERM) }, @@ -54,7 +54,7 @@ STATIC MP_DEFINE_CONST_DICT(pb_module_usignal_globals, usignal_globals_table); const mp_obj_module_t pb_module_usignal = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_usignal_globals, + .globals = (mp_obj_dict_t *)&pb_module_usignal_globals, }; #endif // PYBRICKS_PY_USIGNAL diff --git a/bricks/ev3dev/mpconfigport.h b/bricks/ev3dev/mpconfigport.h index b6a29b4c6..faf1047a3 100644 --- a/bricks/ev3dev/mpconfigport.h +++ b/bricks/ev3dev/mpconfigport.h @@ -5,16 +5,16 @@ #include "brickconfig.h" static const char pybricks_ev3dev_help_text[] = -"Welcome to Pybricks MicroPython!\n" -"\n" -"For online docs please visit http://docs.pybricks.com/micropython\n" -"\n" -"Control commands:\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, exit\n" -" CTRL-E -- on a blank line, enter paste mode\n" -"\n" -"For further help on a specific object, type help(obj)\n" + "Welcome to Pybricks MicroPython!\n" + "\n" + "For online docs please visit http://docs.pybricks.com/micropython\n" + "\n" + "Control commands:\n" + " CTRL-C -- interrupt a running program\n" + " CTRL-D -- on a blank line, exit\n" + " CTRL-E -- on a blank line, enter paste mode\n" + "\n" + "For further help on a specific object, type help(obj)\n" ; // options to control how MicroPython is built @@ -29,7 +29,7 @@ static const char pybricks_ev3dev_help_text[] = #endif #if !defined(MICROPY_EMIT_THUMB) && defined(__thumb2__) #define MICROPY_EMIT_THUMB (1) - #define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) + #define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) #endif // Some compilers define __thumb2__ and __arm__ at the same time, let // autodetected thumb2 emitter have priority. @@ -335,7 +335,7 @@ typedef long long mp_off_t; typedef long mp_off_t; #endif -void mp_unix_alloc_exec(size_t min_size, void** ptr, size_t *size); +void mp_unix_alloc_exec(size_t min_size, void **ptr, size_t *size); void mp_unix_free_exec(void *ptr, size_t size); void mp_unix_mark_exec(void); #define MP_PLAT_ALLOC_EXEC(min_size, ptr, size) mp_unix_alloc_exec(min_size, ptr, size) @@ -350,10 +350,10 @@ void mp_unix_mark_exec(void); #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len) #else #define MP_PLAT_PRINT_STRN(str, len) do { \ - MP_THREAD_GIL_EXIT(); \ - ssize_t ret = write(1, str, len); \ - MP_THREAD_GIL_ENTER(); \ - (void)ret; \ + MP_THREAD_GIL_EXIT(); \ + ssize_t ret = write(1, str, len); \ + MP_THREAD_GIL_ENTER(); \ + (void)ret; \ } while (0) #endif diff --git a/bricks/ev3dev/pb_type_ev3dev_font.c b/bricks/ev3dev/pb_type_ev3dev_font.c index 6b2e46060..6f1515db0 100644 --- a/bricks/ev3dev/pb_type_ev3dev_font.c +++ b/bricks/ev3dev/pb_type_ev3dev_font.c @@ -149,7 +149,7 @@ const mp_obj_type_t pb_type_ev3dev_Font = { { &mp_type_type }, .name = MP_QSTR_Font, .make_new = ev3dev_Font_make_new, - .locals_dict = (mp_obj_dict_t*)&ev3dev_Font_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ev3dev_Font_locals_dict, }; GrxFont *pb_ev3dev_Font_obj_get_font(mp_const_obj_t obj) { diff --git a/bricks/ev3dev/pb_type_ev3dev_image.c b/bricks/ev3dev/pb_type_ev3dev_image.c index 0b4cc2c97..8db10341a 100644 --- a/bricks/ev3dev/pb_type_ev3dev_image.c +++ b/bricks/ev3dev/pb_type_ev3dev_image.c @@ -47,31 +47,31 @@ STATIC GrxColor map_color(mp_obj_t *obj) { pbio_light_color_t color = pb_type_enum_get_value(obj, &pb_enum_type_Color); switch (color) { - case PBIO_LIGHT_COLOR_NONE: - return GRX_COLOR_NONE; - case PBIO_LIGHT_COLOR_BLACK: - return GRX_COLOR_BLACK; - case PBIO_LIGHT_COLOR_BLUE: - return grx_color_get(0, 0, 255); - case PBIO_LIGHT_COLOR_GREEN: - return grx_color_get(0, 128, 0); - case PBIO_LIGHT_COLOR_YELLOW: - return grx_color_get(255, 255, 0); - case PBIO_LIGHT_COLOR_RED: - return grx_color_get(255, 0, 0); - case PBIO_LIGHT_COLOR_WHITE: - return GRX_COLOR_WHITE; - case PBIO_LIGHT_COLOR_BROWN: - return grx_color_get(165, 42, 42); - case PBIO_LIGHT_COLOR_ORANGE: - return grx_color_get(255, 165, 0); - case PBIO_LIGHT_COLOR_PURPLE: - return grx_color_get(128, 0, 128); + case PBIO_LIGHT_COLOR_NONE: + return GRX_COLOR_NONE; + case PBIO_LIGHT_COLOR_BLACK: + return GRX_COLOR_BLACK; + case PBIO_LIGHT_COLOR_BLUE: + return grx_color_get(0, 0, 255); + case PBIO_LIGHT_COLOR_GREEN: + return grx_color_get(0, 128, 0); + case PBIO_LIGHT_COLOR_YELLOW: + return grx_color_get(255, 255, 0); + case PBIO_LIGHT_COLOR_RED: + return grx_color_get(255, 0, 0); + case PBIO_LIGHT_COLOR_WHITE: + return GRX_COLOR_WHITE; + case PBIO_LIGHT_COLOR_BROWN: + return grx_color_get(165, 42, 42); + case PBIO_LIGHT_COLOR_ORANGE: + return grx_color_get(255, 165, 0); + case PBIO_LIGHT_COLOR_PURPLE: + return grx_color_get(128, 0, 128); } return grx_color_get_black(); } -STATIC mp_obj_t ev3dev_Image_new(GrxContext* context) { +STATIC mp_obj_t ev3dev_Image_new(GrxContext *context) { ev3dev_Image_obj_t *self = m_new_obj_with_finaliser(ev3dev_Image_obj_t); self->base.type = &pb_type_ev3dev_Image; @@ -110,8 +110,7 @@ STATIC mp_obj_t ev3dev_Image_make_new(const mp_obj_type_t *type, size_t n_args, if (mp_obj_is_qstr(source_in) && MP_OBJ_QSTR_VALUE(source_in) == MP_QSTR__screen_) { // special case '_screen_' creates image that draws directly to screen context = grx_context_ref(grx_get_screen_context()); - } - else if (mp_obj_is_str(source_in)) { + } else if (mp_obj_is_str(source_in)) { const char *filename = mp_obj_str_get_str(source_in); // add file extension if missing @@ -147,8 +146,7 @@ STATIC mp_obj_t ev3dev_Image_make_new(const mp_obj_type_t *type, size_t n_args, } g_free(filename_ext); - } - else if (mp_obj_is_type(source_in, &pb_type_ev3dev_Image)) { + } else if (mp_obj_is_type(source_in, &pb_type_ev3dev_Image)) { ev3dev_Image_obj_t *image = MP_OBJ_TO_PTR(source_in); if (arg_vals[ARG_sub].u_bool) { mp_int_t x1 = pb_obj_get_int(arg_vals[ARG_x1].u_obj); @@ -156,8 +154,7 @@ STATIC mp_obj_t ev3dev_Image_make_new(const mp_obj_type_t *type, size_t n_args, mp_int_t x2 = pb_obj_get_int(arg_vals[ARG_x2].u_obj); mp_int_t y2 = pb_obj_get_int(arg_vals[ARG_y2].u_obj); context = grx_context_new_subcontext(x1, y1, x2, y2, image->context, NULL); - } - else { + } else { gint w = grx_context_get_width(image->context); gint h = grx_context_get_height(image->context); GrxFrameMemory mem; @@ -234,8 +231,7 @@ STATIC mp_obj_t ev3dev_Image_draw_pixel(size_t n_args, const mp_obj_t *pos_args, ev3dev_Image_obj_t, self, PB_ARG_REQUIRED(x), PB_ARG_REQUIRED(y), - PB_ARG_DEFAULT_OBJ(color, pb_Color_BLACK_obj) - ); + PB_ARG_DEFAULT_OBJ(color, pb_Color_BLACK_obj)); mp_int_t x_ = pb_obj_get_int(x); mp_int_t y_ = pb_obj_get_int(y); @@ -257,8 +253,7 @@ STATIC mp_obj_t ev3dev_Image_draw_line(size_t n_args, const mp_obj_t *pos_args, PB_ARG_REQUIRED(x2), PB_ARG_REQUIRED(y2), PB_ARG_DEFAULT_INT(width, 1), - PB_ARG_DEFAULT_OBJ(color, pb_Color_BLACK_obj) - ); + PB_ARG_DEFAULT_OBJ(color, pb_Color_BLACK_obj)); mp_int_t x1_ = pb_obj_get_int(x1); mp_int_t y1_ = pb_obj_get_int(y1); @@ -271,8 +266,7 @@ STATIC mp_obj_t ev3dev_Image_draw_line(size_t n_args, const mp_obj_t *pos_args, grx_set_current_context(self->context); if (width_ == 1) { grx_draw_line(x1_, y1_, x2_, y2_, color_); - } - else { + } else { GrxLineOptions options = { .color = color_, .width = width_ }; grx_draw_line_with_options(x1_, y1_, x2_, y2_, &options); } @@ -290,8 +284,7 @@ STATIC mp_obj_t ev3dev_Image_draw_box(size_t n_args, const mp_obj_t *pos_args, m PB_ARG_REQUIRED(y2), PB_ARG_DEFAULT_INT(r, 0), PB_ARG_DEFAULT_FALSE(fill), - PB_ARG_DEFAULT_OBJ(color, pb_Color_BLACK_obj) - ); + PB_ARG_DEFAULT_OBJ(color, pb_Color_BLACK_obj)); mp_int_t x1_ = pb_obj_get_int(x1); mp_int_t y1_ = pb_obj_get_int(y1); @@ -305,16 +298,13 @@ STATIC mp_obj_t ev3dev_Image_draw_box(size_t n_args, const mp_obj_t *pos_args, m if (mp_obj_is_true(fill)) { if (r_ > 0) { grx_draw_filled_rounded_box(x1_, y1_, x2_, y2_, r_, color_); - } - else { + } else { grx_draw_filled_box(x1_, y1_, x2_, y2_, color_); } - } - else { + } else { if (r_ > 0) { grx_draw_rounded_box(x1_, y1_, x2_, y2_, r_, color_); - } - else { + } else { grx_draw_box(x1_, y1_, x2_, y2_, color_); } } @@ -330,8 +320,7 @@ STATIC mp_obj_t ev3dev_Image_draw_circle(size_t n_args, const mp_obj_t *pos_args PB_ARG_REQUIRED(y), PB_ARG_REQUIRED(r), PB_ARG_DEFAULT_FALSE(fill), - PB_ARG_DEFAULT_OBJ(color, pb_Color_BLACK_obj) - ); + PB_ARG_DEFAULT_OBJ(color, pb_Color_BLACK_obj)); mp_int_t x_ = pb_obj_get_int(x); mp_int_t y_ = pb_obj_get_int(y); @@ -343,8 +332,7 @@ STATIC mp_obj_t ev3dev_Image_draw_circle(size_t n_args, const mp_obj_t *pos_args grx_set_current_context(self->context); if (fill_) { grx_draw_filled_circle(x_, y_, r_, color_); - } - else { + } else { grx_draw_circle(x_, y_, r_, color_); } @@ -358,8 +346,7 @@ STATIC mp_obj_t ev3dev_Image_draw_image(size_t n_args, const mp_obj_t *pos_args, PB_ARG_REQUIRED(x), PB_ARG_REQUIRED(y), PB_ARG_REQUIRED(source), - PB_ARG_DEFAULT_NONE(transparent) - ); + PB_ARG_DEFAULT_NONE(transparent)); mp_int_t x_ = pb_obj_get_int(x); mp_int_t y_ = pb_obj_get_int(y); @@ -438,8 +425,7 @@ STATIC mp_obj_t ev3dev_Image_draw_text(size_t n_args, const mp_obj_t *pos_args, PB_ARG_REQUIRED(y), PB_ARG_REQUIRED(text), PB_ARG_DEFAULT_OBJ(text_color, pb_Color_BLACK_obj), - PB_ARG_DEFAULT_NONE(background_color) - ); + PB_ARG_DEFAULT_NONE(background_color)); mp_int_t x_ = pb_obj_get_int(x); mp_int_t y_ = pb_obj_get_int(y); @@ -538,8 +524,7 @@ STATIC mp_obj_t ev3dev_Image_print(size_t n_args, const mp_obj_t *pos_args, mp_m const GrxColor *scan_line = grx_get_scanline(0, max_x, y + over, NULL); if (scan_line) { grx_put_scanline(0, max_x, y, scan_line, GRX_COLOR_MODE_WRITE); - } - else { + } else { grx_draw_hline(0, max_x, y, GRX_COLOR_WHITE); } } @@ -606,5 +591,5 @@ const mp_obj_type_t pb_type_ev3dev_Image = { { &mp_type_type }, .name = MP_QSTR_Image, .make_new = ev3dev_Image_make_new, - .locals_dict = (mp_obj_dict_t*)&ev3dev_Image_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ev3dev_Image_locals_dict, }; diff --git a/bricks/ev3dev/pb_type_ev3dev_speaker.c b/bricks/ev3dev/pb_type_ev3dev_speaker.c index bb7146e47..8301252a5 100644 --- a/bricks/ev3dev/pb_type_ev3dev_speaker.c +++ b/bricks/ev3dev/pb_type_ev3dev_speaker.c @@ -79,8 +79,7 @@ STATIC mp_obj_t ev3dev_Speaker_make_new(const mp_obj_type_t *type, size_t n_args dest[3] = MP_ROM_QSTR(MP_QSTR__default_); mp_call_method_n_kw(2, 0, dest); nlr_pop(); - } - else { + } else { // ignore error } @@ -114,8 +113,7 @@ STATIC mp_obj_t ev3dev_Speaker_beep(size_t n_args, const mp_obj_t *pos_args, mp_ PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3dev_Speaker_obj_t, self, PB_ARG_DEFAULT_INT(frequency, 500), - PB_ARG_DEFAULT_INT(duration, 100) - ); + PB_ARG_DEFAULT_INT(duration, 100)); mp_int_t freq = pb_obj_get_int(frequency); mp_int_t ms = pb_obj_get_int(duration); @@ -134,8 +132,7 @@ STATIC mp_obj_t ev3dev_Speaker_beep(size_t n_args, const mp_obj_t *pos_args, mp_ mp_hal_delay_ms(ms); set_beep_frequency(self, 0); nlr_pop(); - } - else { + } else { set_beep_frequency(self, 0); nlr_jump(nlr.ret_val); } @@ -152,110 +149,110 @@ STATIC void ev3dev_Speaker_play_note(ev3dev_Speaker_obj_t *self, mp_obj_t obj, i // Note names can be A-G followed by optional # (sharp) or b (flat) or R for rest switch (note[pos++]) { - case 'C': - switch (note[pos++]) { - case 'b': - mp_raise_ValueError("'Cb' is not allowed"); - break; - case '#': - freq = 17.32; - break; - default: - pos--; - freq = 16.35; - break; - } - break; - case 'D': - switch (note[pos++]) { - case 'b': - freq = 17.32; - break; - case '#': - freq = 19.45; - break; - default: - pos--; - freq = 18.35; - break; - } - break; - case 'E': - switch (note[pos++]) { - case 'b': - freq = 19.45; - break; - case '#': - mp_raise_ValueError("'E#' is not allowed"); - break; - default: - pos--; - freq = 20.60; - break; - } - break; - case 'F': - switch (note[pos++]) { - case 'b': - mp_raise_ValueError("'Fb' is not allowed"); - break; - case '#': - freq = 23.12; - break; - default: - pos--; - freq = 21.83; - break; - } - break; - case 'G': - switch (note[pos++]) { - case 'b': - freq = 23.12; + case 'C': + switch (note[pos++]) { + case 'b': + mp_raise_ValueError("'Cb' is not allowed"); + break; + case '#': + freq = 17.32; + break; + default: + pos--; + freq = 16.35; + break; + } break; - case '#': - freq = 25.96; + case 'D': + switch (note[pos++]) { + case 'b': + freq = 17.32; + break; + case '#': + freq = 19.45; + break; + default: + pos--; + freq = 18.35; + break; + } break; - default: - pos--; - freq = 24.50; + case 'E': + switch (note[pos++]) { + case 'b': + freq = 19.45; + break; + case '#': + mp_raise_ValueError("'E#' is not allowed"); + break; + default: + pos--; + freq = 20.60; + break; + } break; - } - break; - case 'A': - switch (note[pos++]) { - case 'b': - freq = 25.96; + case 'F': + switch (note[pos++]) { + case 'b': + mp_raise_ValueError("'Fb' is not allowed"); + break; + case '#': + freq = 23.12; + break; + default: + pos--; + freq = 21.83; + break; + } break; - case '#': - freq = 29.14; + case 'G': + switch (note[pos++]) { + case 'b': + freq = 23.12; + break; + case '#': + freq = 25.96; + break; + default: + pos--; + freq = 24.50; + break; + } break; - default: - pos--; - freq = 27.50; + case 'A': + switch (note[pos++]) { + case 'b': + freq = 25.96; + break; + case '#': + freq = 29.14; + break; + default: + pos--; + freq = 27.50; + break; + } break; - } - break; - case 'B': - switch (note[pos++]) { - case 'b': - freq = 29.14; + case 'B': + switch (note[pos++]) { + case 'b': + freq = 29.14; + break; + case '#': + mp_raise_ValueError("'B#' is not allowed"); + break; + default: + pos--; + freq = 30.87; + break; + } break; - case '#': - mp_raise_ValueError("'B#' is not allowed"); + case 'R': + freq = 0; break; default: - pos--; - freq = 30.87; + mp_raise_ValueError("Missing note name A-G or R"); break; - } - break; - case 'R': - freq = 0; - break; - default: - mp_raise_ValueError("Missing note name A-G or R"); - break; } // Note name must be followed by the octave number @@ -282,8 +279,7 @@ STATIC void ev3dev_Speaker_play_note(ev3dev_Speaker_obj_t *self, mp_obj_t obj, i int fraction2 = note[pos++] - '0'; if (fraction2 < 0 || fraction2 > 9) { pos--; - } - else { + } else { fraction = fraction * 10 + fraction2; } @@ -294,16 +290,14 @@ STATIC void ev3dev_Speaker_play_note(ev3dev_Speaker_obj_t *self, mp_obj_t obj, i if (note[pos++] == '.') { // dotted note has length extended by 1/2 duration = 3 * duration / 2; - } - else { + } else { pos--; } if (note[pos++] == '_') { // note with tie/slur is not released release = false; - } - else { + } else { pos--; } @@ -316,8 +310,7 @@ STATIC void ev3dev_Speaker_play_note(ev3dev_Speaker_obj_t *self, mp_obj_t obj, i mp_hal_delay_ms(7 * duration / 8); set_beep_frequency(self, 0); mp_hal_delay_ms(duration / 8); - } - else { + } else { mp_hal_delay_ms(duration); } } @@ -326,8 +319,7 @@ STATIC mp_obj_t ev3dev_Speaker_play_notes(size_t n_args, const mp_obj_t *pos_arg PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3dev_Speaker_obj_t, self, PB_ARG_REQUIRED(notes), - PB_ARG_DEFAULT_INT(tempo, 120) - ); + PB_ARG_DEFAULT_INT(tempo, 120)); // length of whole note in milliseconds = 4 quarter/whole * 60 s/min * 1000 ms/s / tempo quarter/min int duration = 4 * 60 * 1000 / pb_obj_get_int(tempo); @@ -342,8 +334,7 @@ STATIC mp_obj_t ev3dev_Speaker_play_notes(size_t n_args, const mp_obj_t *pos_arg // in case the last note has '_' set_beep_frequency(self, 0); nlr_pop(); - } - else { + } else { // ensure that sound stops if an exception is raised set_beep_frequency(self, 0); nlr_jump(nlr.ret_val); @@ -364,8 +355,7 @@ STATIC void ev3dev_Speaker_aplay_callback(GObject *source_object, GAsyncResult * STATIC mp_obj_t ev3dev_Speaker_play_file(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3dev_Speaker_obj_t, self, - PB_ARG_REQUIRED(file) - ); + PB_ARG_REQUIRED(file)); const char *path = mp_obj_str_get_str(file); @@ -454,8 +444,7 @@ STATIC void ev3dev_Speaker_splice_callback(GObject *source_object, GAsyncResult STATIC mp_obj_t ev3dev_Speaker_say(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3dev_Speaker_obj_t, self, - PB_ARG_REQUIRED(text) - ); + PB_ARG_REQUIRED(text)); const char *text_ = mp_obj_str_get_str(text); @@ -577,8 +566,7 @@ STATIC mp_obj_t ev3dev_Speaker_set_speech_options(size_t n_args, const mp_obj_t PB_ARG_DEFAULT_NONE(language), PB_ARG_DEFAULT_NONE(voice), PB_ARG_DEFAULT_NONE(speed), - PB_ARG_DEFAULT_NONE(pitch) - ); + PB_ARG_DEFAULT_NONE(pitch)); if (language != mp_const_none) { strncpy(self->language, mp_obj_str_get_str(language), sizeof(self->language)); @@ -603,8 +591,7 @@ STATIC mp_obj_t ev3dev_Speaker_set_volume(size_t n_args, const mp_obj_t *pos_arg PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3dev_Speaker_obj_t, self, PB_ARG_REQUIRED(volume), - PB_ARG_DEFAULT_QSTR(which, _all_) - ); + PB_ARG_DEFAULT_QSTR(which, _all_)); (void)self; // unused @@ -613,8 +600,7 @@ STATIC mp_obj_t ev3dev_Speaker_set_volume(size_t n_args, const mp_obj_t *pos_arg if (volume_ > 100) { volume_ = 100; - } - else if (volume_ < 0) { + } else if (volume_ < 0) { volume_ = 0; } @@ -626,18 +612,14 @@ STATIC mp_obj_t ev3dev_Speaker_set_volume(size_t n_args, const mp_obj_t *pos_arg if (strcmp(which_, "_default_") == 0) { // internal value to set sane defaults (PCM 70%, Beep 30%). volume parameter is ignored. snprintf(amixer_stdin, sizeof(amixer_stdin), "sset PCM 179 \nsset Beep 77\n"); - } - else if (strcmp(which_, "_all_") == 0) { + } else if (strcmp(which_, "_all_") == 0) { snprintf(amixer_stdin, sizeof(amixer_stdin), "sset PCM " INT_FMT " \nsset Beep " INT_FMT "\n", volume_, volume_); - } - else if (strcmp(which_, "Beep") == 0) { + } else if (strcmp(which_, "Beep") == 0) { snprintf(amixer_stdin, sizeof(amixer_stdin), "sset Beep " INT_FMT "\n", volume_); - } - else if (strcmp(which_, "PCM") == 0) { + } else if (strcmp(which_, "PCM") == 0) { snprintf(amixer_stdin, sizeof(amixer_stdin), "sset PCM " INT_FMT "\n", volume_); - } - else { + } else { // Note: '_default_' isn't listed since it is considered an internal option mp_raise_ValueError("which must be one of '_all_', 'Beep', 'PCM'"); } @@ -685,5 +667,5 @@ const mp_obj_type_t pb_type_ev3dev_Speaker = { { &mp_type_type }, .name = MP_QSTR_Speaker, .make_new = ev3dev_Speaker_make_new, - .locals_dict = (mp_obj_dict_t*)&ev3dev_Speaker_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ev3dev_Speaker_locals_dict, }; diff --git a/bricks/ev3dev/pbdevice.c b/bricks/ev3dev/pbdevice.c index 42d82efa1..7b3418c06 100644 --- a/bricks/ev3dev/pbdevice.c +++ b/bricks/ev3dev/pbdevice.c @@ -68,7 +68,7 @@ static pbio_error_t get_device(pbdevice_t **pbdev, pbio_iodev_type_id_t valid_id _pbdev->type_id = valid_id; // For special sensor classes we are done. No need to read mode. - if (valid_id == PBIO_IODEV_TYPE_ID_CUSTOM_I2C || + if (valid_id == PBIO_IODEV_TYPE_ID_CUSTOM_I2C || valid_id == PBIO_IODEV_TYPE_ID_CUSTOM_UART || valid_id == PBIO_IODEV_TYPE_ID_NXT_COLOR_SENSOR) { *pbdev = _pbdev; @@ -94,7 +94,7 @@ static pbio_error_t get_device(pbdevice_t **pbdev, pbio_iodev_type_id_t valid_id // Get the required mode switch time delay for a given sensor type and/or mode static uint32_t get_mode_switch_delay(pbio_iodev_type_id_t id, uint8_t mode) { - switch(id) { + switch (id) { case PBIO_IODEV_TYPE_ID_EV3_COLOR_SENSOR: return 30; case PBIO_IODEV_TYPE_ID_EV3_IR_SENSOR: @@ -123,7 +123,7 @@ static pbio_error_t get_values(pbdevice_t *pbdev, uint8_t mode, int32_t *values) if (pbdev->mode != mode || ( // and also if this sensor/mode requires setting it every time: pbdev->type_id == PBIO_IODEV_TYPE_ID_EV3_ULTRASONIC_SENSOR && mode >= PBIO_IODEV_MODE_EV3_ULTRASONIC_SENSOR__SI_CM - )) { + )) { err = lego_sensor_set_mode(pbdev->sensor, mode); if (err != PBIO_SUCCESS) { return err; @@ -171,13 +171,13 @@ static pbio_error_t get_values(pbdevice_t *pbdev, uint8_t mode, int32_t *values) values[i] = *((uint32_t *)(data + i * 4)); break; case LEGO_SENSOR_DATA_TYPE_INT16_BE: - values[i] = (int16_t) __builtin_bswap16(*(uint16_t *) (data + i * 2)); + values[i] = (int16_t)__builtin_bswap16(*(uint16_t *)(data + i * 2)); break; case LEGO_SENSOR_DATA_TYPE_FLOAT: *(float *)(values + i) = *((float *)(data + i * 4)); break; default: - return(PBIO_ERROR_IO); + return PBIO_ERROR_IO; } } @@ -200,7 +200,7 @@ pbdevice_t *pbdevice_get_device(pbio_port_t port, pbio_iodev_type_id_t valid_id) if (err == PBIO_SUCCESS) { break; } - mp_hal_delay_ms(1000*(i+1)); + mp_hal_delay_ms(1000 * (i + 1)); } } pb_assert(err); @@ -238,7 +238,7 @@ int8_t pbdevice_get_mode_id_from_str(pbdevice_t *pbdev, const char *mode_str) { void pbdevice_color_light_on(pbdevice_t *pbdev, pbio_light_color_t color) { // Turn on the light through device specific mode uint8_t mode; - switch(pbdev->type_id) { + switch (pbdev->type_id) { case PBIO_IODEV_TYPE_ID_NXT_COLOR_SENSOR: switch (color) { case PBIO_LIGHT_COLOR_GREEN: diff --git a/bricks/ev3dev/pbinit.c b/bricks/ev3dev/pbinit.c index f06f27b3c..9e9b641d8 100644 --- a/bricks/ev3dev/pbinit.c +++ b/bricks/ev3dev/pbinit.c @@ -36,7 +36,8 @@ static void *task_caller(void *arg) { while (!stopping_thread) { MP_THREAD_GIL_ENTER(); - while (pbio_do_one_event()) { } + while (pbio_do_one_event()) { + } MP_THREAD_GIL_EXIT(); clock_nanosleep(CLOCK_MONOTONIC, 0, &ts, NULL); @@ -55,8 +56,8 @@ void pybricks_init() { grx_clear_screen(GRX_COLOR_WHITE); // Screen center - gint cx = grx_get_width()/2; - gint cy = grx_get_height()/2; + gint cx = grx_get_width() / 2; + gint cy = grx_get_height() / 2; // One side of the triangle gint base = MIN(grx_get_width(), grx_get_height()) * 7 / 16; @@ -70,18 +71,18 @@ void pybricks_init() { gint width = 5; gint cr = r * 3 / 2; grx_draw_filled_circle(cx, cy, cr, GRX_COLOR_BLACK); - grx_draw_filled_circle(cx, cy, cr-width, GRX_COLOR_WHITE); + grx_draw_filled_circle(cx, cy, cr - width, GRX_COLOR_WHITE); GrxPoint triangle[3] = { { // Upper left vertex .x = cx - s, - .y = cy - base/2 + .y = cy - base / 2 }, { // Bottom left vertex .x = cx - s, - .y = cy + base/2 + .y = cy + base / 2 }, { // Right vertex @@ -97,7 +98,7 @@ void pybricks_init() { } // Pybricks deinitialization tasks -void pybricks_deinit(){ +void pybricks_deinit() { // Signal motor thread to stop and wait for it to do so. stopping_thread = true; pthread_join(task_caller_thread, NULL); diff --git a/bricks/ev3dev/pbsmbus.c b/bricks/ev3dev/pbsmbus.c index 88b7d2992..3cb1ec1f8 100644 --- a/bricks/ev3dev/pbsmbus.c +++ b/bricks/ev3dev/pbsmbus.c @@ -27,7 +27,7 @@ struct _smbus_t { int address; }; -smbus_t buses[BUS_NUM_MAX-BUS_NUM_MIN+1]; +smbus_t buses[BUS_NUM_MAX - BUS_NUM_MIN + 1]; static pbio_error_t pb_smbus_set_address(smbus_t *bus, int address) { @@ -47,7 +47,7 @@ pbio_error_t pb_smbus_get(smbus_t **_bus, int bus_num) { return PBIO_ERROR_INVALID_PORT; } - smbus_t *bus = &buses[bus_num-BUS_NUM_MIN]; + smbus_t *bus = &buses[bus_num - BUS_NUM_MIN]; char devpath[MAXDEVPATH]; @@ -103,12 +103,12 @@ pbio_error_t pb_smbus_read_no_reg(smbus_t *bus, uint8_t address, uint8_t *buf) { return err; } - int result = i2c_smbus_read_byte(bus->file); + int result = i2c_smbus_read_byte(bus->file); if (result < 0) { return PBIO_ERROR_IO; } - *buf = (uint8_t) result; + *buf = (uint8_t)result; return PBIO_SUCCESS; } diff --git a/bricks/ev3rt/mpconfigport.h b/bricks/ev3rt/mpconfigport.h index 6d9d24641..bfa92c94d 100644 --- a/bricks/ev3rt/mpconfigport.h +++ b/bricks/ev3rt/mpconfigport.h @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) diff --git a/bricks/ev3rt/mphal.c b/bricks/ev3rt/mphal.c index cd99ce531..752fef15b 100644 --- a/bricks/ev3rt/mphal.c +++ b/bricks/ev3rt/mphal.c @@ -45,7 +45,9 @@ mp_import_stat_t mp_import_stat(const char *path) { } void nlr_jump_fail(void *val) { - while (1); + while (1) { + ; + } } // cooked is same as uncooked because the terminal does some postprocessing diff --git a/bricks/movehub/accel.c b/bricks/movehub/accel.c index 5caadd658..e204bc9ba 100644 --- a/bricks/movehub/accel.c +++ b/bricks/movehub/accel.c @@ -54,7 +54,8 @@ static void accel_spi_read(uint8_t reg, uint8_t *value) { // busy wait do { - while (!(SPI1->SR & SPI_SR_RXNE)) { } + while (!(SPI1->SR & SPI_SR_RXNE)) { + } } while (SPI1->SR & SPI_SR_BSY); while (SPI1->SR & SPI_SR_RXNE) { @@ -65,7 +66,8 @@ static void accel_spi_read(uint8_t reg, uint8_t *value) { // busy wait do { - while (!(SPI1->SR & SPI_SR_RXNE)) { } + while (!(SPI1->SR & SPI_SR_RXNE)) { + } } while (SPI1->SR & SPI_SR_BSY); *value = BYTE_ACCESS(SPI1->DR); @@ -82,14 +84,16 @@ static void accel_spi_write(uint8_t reg, uint8_t value) { // busy wait do { - while (!(SPI1->SR & SPI_SR_RXNE)) { } + while (!(SPI1->SR & SPI_SR_RXNE)) { + } } while (SPI1->SR & SPI_SR_BSY); BYTE_ACCESS(SPI1->DR) = value; // busy wait do { - while (!(SPI1->SR & SPI_SR_RXNE)) { } + while (!(SPI1->SR & SPI_SR_RXNE)) { + } } while (SPI1->SR & SPI_SR_BSY); // clear chip select @@ -129,6 +133,5 @@ void accel_init(void) { void accel_get_values(int *x, int *y, int *z) { } -void accel_deinit(void) -{ +void accel_deinit(void) { } diff --git a/bricks/nxt/main.c b/bricks/nxt/main.c index e9386b3aa..b405d334f 100644 --- a/bricks/nxt/main.c +++ b/bricks/nxt/main.c @@ -65,8 +65,8 @@ static bool user_program_stdin_event_func(uint8_t c) { } static const pbsys_user_program_callbacks_t user_program_callbacks = { - .stop = user_program_stop_func, - .stdin_event = user_program_stdin_event_func, + .stop = user_program_stop_func, + .stdin_event = user_program_stdin_event_func, }; static void pb_imports() { @@ -87,7 +87,7 @@ static void pb_imports() { int main(int argc, char **argv) { int stack_dummy; - stack_top = (char*)&stack_dummy; + stack_top = (char *)&stack_dummy; pbio_init(); nxt_init(); @@ -132,7 +132,7 @@ void gc_collect(void) { uintptr_t sp = gc_helper_get_regs_and_sp(regs); // trace the stack, including the registers (since they live on the stack in this function) - gc_collect_root((void**)sp, ((uint32_t)&_estack - sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, ((uint32_t)&_estack - sp) / sizeof(uint32_t)); // end the GC gc_collect_end(); @@ -150,11 +150,15 @@ mp_import_stat_t mp_import_stat(const char *path) { } void nlr_jump_fail(void *val) { - while (1); + while (1) { + ; + } } void NORETURN __fatal_error(const char *msg) { - while (1); + while (1) { + ; + } } #ifndef NDEBUG diff --git a/bricks/nxt/mpconfigport.h b/bricks/nxt/mpconfigport.h index fde28da91..217c253f3 100644 --- a/bricks/nxt/mpconfigport.h +++ b/bricks/nxt/mpconfigport.h @@ -80,7 +80,7 @@ // type definitions for the specific machine -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) // This port is intended to be 32-bit, but unfortunately, int32_t for // different targets may be defined in different ways - either as int diff --git a/bricks/pybricks_config.h b/bricks/pybricks_config.h index cd24760e1..7aee08ce4 100644 --- a/bricks/pybricks_config.h +++ b/bricks/pybricks_config.h @@ -23,11 +23,11 @@ #endif // hex value format comes from https://docs.python.org/3/c-api/apiabiversion.html#apiabiversion -#define PYBRICKS_HEXVERSION (\ +#define PYBRICKS_HEXVERSION ( \ ((PYBRICKS_VERSION_MAJOR & 0xFF) << 24) | \ ((PYBRICKS_VERSION_MINOR & 0xFF) << 16) | \ - ((PYBRICKS_VERSION_MICRO & 0xFF) << 8) | \ - ((PYBRICKS_VERSION_LEVEL_HEX & 0xF) << 4) | \ + ((PYBRICKS_VERSION_MICRO & 0xFF) << 8) | \ + ((PYBRICKS_VERSION_LEVEL_HEX & 0xF) << 4) | \ (PYBRICKS_VERSION_SERIAL & 0xF)) // Hub name diff --git a/bricks/stm32/configport.h b/bricks/stm32/configport.h index c2445eda7..d79a74271 100644 --- a/bricks/stm32/configport.h +++ b/bricks/stm32/configport.h @@ -84,7 +84,7 @@ // type definitions for the specific machine -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) // This port is intended to be 32-bit, but unfortunately, int32_t for // different targets may be defined in different ways - either as int diff --git a/bricks/stm32/main.c b/bricks/stm32/main.c index 8391c2341..5d6cb75d1 100644 --- a/bricks/stm32/main.c +++ b/bricks/stm32/main.c @@ -117,8 +117,7 @@ static pbio_error_t get_message(uint8_t *buf, uint32_t rx_len, int32_t time_out) if (time_out != -1 && time_now - time_start > time_out) { return PBIO_ERROR_TIMEDOUT; } - } - else if (time_now - time_start > time_interval) { + } else if (time_now - time_start > time_interval) { // After the first byte, apply much shorter interval timeout return PBIO_ERROR_TIMEDOUT; } @@ -144,7 +143,8 @@ static uint32_t get_user_program(uint8_t **buf, uint32_t *free_len) { // flush any buffered bytes from stdin uint8_t c; - while (pbsys_stdin_get_char(&c) == PBIO_SUCCESS) { } + while (pbsys_stdin_get_char(&c) == PBIO_SUCCESS) { + } // Get the program length uint32_t len; @@ -284,13 +284,13 @@ static bool user_program_stdin_event_func(uint8_t c) { } static const pbsys_user_program_callbacks_t user_program_callbacks = { - .stop = user_program_stop_func, - .stdin_event = user_program_stdin_event_func, + .stop = user_program_stop_func, + .stdin_event = user_program_stdin_event_func, }; int main(int argc, char **argv) { int stack_dummy; - stack_top = (char*)&stack_dummy; + stack_top = (char *)&stack_dummy; pbio_init(); @@ -347,7 +347,7 @@ void gc_collect(void) { uintptr_t sp = gc_helper_get_regs_and_sp(regs); // trace the stack, including the registers (since they live on the stack in this function) - gc_collect_root((void**)sp, ((uint32_t)&_estack - sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, ((uint32_t)&_estack - sp) / sizeof(uint32_t)); // end the GC gc_collect_end(); @@ -369,11 +369,15 @@ mp_import_stat_t mp_import_stat(const char *path) { } void nlr_jump_fail(void *val) { - while (1); + while (1) { + ; + } } void NORETURN __fatal_error(const char *msg) { - while (1); + while (1) { + ; + } } #ifndef NDEBUG diff --git a/bricks/stm32/pbdevice.c b/bricks/stm32/pbdevice.c index 7838267bb..3998edc07 100644 --- a/bricks/stm32/pbdevice.c +++ b/bricks/stm32/pbdevice.c @@ -21,7 +21,7 @@ struct _pbdevice_t { pbio_iodev_t iodev; }; -static void wait(pbio_error_t (*end)(pbio_iodev_t *), void (*cancel)(pbio_iodev_t *), pbio_iodev_t* iodev) { +static void wait(pbio_error_t (*end)(pbio_iodev_t *), void (*cancel)(pbio_iodev_t *), pbio_iodev_t *iodev) { nlr_buf_t nlr; pbio_error_t err; @@ -43,11 +43,13 @@ static void wait(pbio_error_t (*end)(pbio_iodev_t *), void (*cancel)(pbio_iodev_ static void set_mode(pbio_iodev_t *iodev, uint8_t new_mode) { pbio_error_t err; - if (iodev->mode == new_mode){ + if (iodev->mode == new_mode) { return; } - while ((err = pbio_iodev_set_mode_begin(iodev, new_mode)) == PBIO_ERROR_AGAIN); + while ((err = pbio_iodev_set_mode_begin(iodev, new_mode)) == PBIO_ERROR_AGAIN) { + ; + } pb_assert(err); wait(pbio_iodev_set_mode_end, pbio_iodev_set_mode_cancel, iodev); } @@ -70,7 +72,7 @@ pbdevice_t *pbdevice_get_device(pbio_port_t port, pbio_iodev_type_id_t valid_id) // Return pointer to device iodev->port = port; - return (pbdevice_t *) iodev; + return (pbdevice_t *)iodev; } void pbdevice_get_values(pbdevice_t *pbdev, uint8_t mode, int32_t *values) { @@ -101,11 +103,11 @@ void pbdevice_get_values(pbdevice_t *pbdev, uint8_t mode, int32_t *values) { case PBIO_IODEV_DATA_TYPE_INT32: values[i] = *((int32_t *)(data + i * 4)); break; -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case PBIO_IODEV_DATA_TYPE_FLOAT: *(float *)(values + i) = *((float *)(data + i * 4)); break; -#endif + #endif default: pb_assert(PBIO_ERROR_IO); } @@ -139,17 +141,19 @@ void pbdevice_set_values(pbdevice_t *pbdev, uint8_t mode, int32_t *values, uint8 case PBIO_IODEV_DATA_TYPE_INT32: *(int32_t *)(data + i * 4) = values[i]; break; -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case PBIO_IODEV_DATA_TYPE_FLOAT: *(float *)(data + i * 4) = values[i]; break; -#endif + #endif default: pb_assert(PBIO_ERROR_IO); } } pbio_error_t err; - while ((err = pbio_iodev_set_data_begin(iodev, iodev->mode, data)) == PBIO_ERROR_AGAIN); + while ((err = pbio_iodev_set_data_begin(iodev, iodev->mode, data)) == PBIO_ERROR_AGAIN) { + ; + } pb_assert(err); wait(pbio_iodev_set_data_end, pbio_iodev_set_data_cancel, iodev); } @@ -157,8 +161,7 @@ void pbdevice_set_values(pbdevice_t *pbdev, uint8_t mode, int32_t *values, uint8 void pbdevice_set_power_supply(pbdevice_t *pbdev, bool on) { if (on) { pb_assert(pbdrv_motor_set_duty_cycle(pbdev->iodev.port, -10000)); - } - else { + } else { pb_assert(pbdrv_motor_coast(pbdev->iodev.port)); } } @@ -178,7 +181,7 @@ int8_t pbdevice_get_mode_id_from_str(pbdevice_t *pbdev, const char *mode_str) { void pbdevice_color_light_on(pbdevice_t *pbdev, pbio_light_color_t color) { // Turn on the light through device specific mode uint8_t mode; - switch(pbdev->iodev.info->type_id) { + switch (pbdev->iodev.info->type_id) { case PBIO_IODEV_TYPE_ID_COLOR_DIST_SENSOR: switch (color) { case PBIO_LIGHT_COLOR_GREEN: diff --git a/extmod/modbattery.c b/extmod/modbattery.c index 573c4f630..8ce49ec18 100644 --- a/extmod/modbattery.c +++ b/extmod/modbattery.c @@ -34,7 +34,7 @@ STATIC MP_DEFINE_CONST_DICT(pb_module_battery_globals, battery_globals_table); const mp_obj_module_t pb_module_battery = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_battery_globals, + .globals = (mp_obj_dict_t *)&pb_module_battery_globals, }; #endif // PBDRV_CONFIG_BATTERY diff --git a/extmod/modbuiltins.c b/extmod/modbuiltins.c index ca492a654..dd7f75c87 100644 --- a/extmod/modbuiltins.c +++ b/extmod/modbuiltins.c @@ -35,8 +35,7 @@ STATIC mp_obj_t builtins_ColorLight_on(size_t n_args, const mp_obj_t *pos_args, PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, builtins_Light_obj_t, self, PB_ARG_REQUIRED(color), - PB_ARG_DEFAULT_INT(brightness, 100) - ); + PB_ARG_DEFAULT_INT(brightness, 100)); if (color == mp_const_none) { color = pb_const_color_black; @@ -45,7 +44,7 @@ STATIC mp_obj_t builtins_ColorLight_on(size_t n_args, const mp_obj_t *pos_args, pbio_light_color_t color_id = pb_type_enum_get_value(color, &pb_enum_type_Color); mp_int_t bright = pb_obj_get_int(brightness); - bright = bright < 0 ? 0 : bright > 100 ? 100: bright; + bright = bright < 0 ? 0 : bright > 100 ? 100 : bright; // TODO: Brightness control is not yet implemented if (bright != 100) { @@ -55,8 +54,7 @@ STATIC mp_obj_t builtins_ColorLight_on(size_t n_args, const mp_obj_t *pos_args, if (!self->pbdev) { // No external device, so assume command is for the internal light pb_assert(pbio_light_on(PBIO_PORT_SELF, color_id)); - } - else { + } else { pbdevice_color_light_on(self->pbdev, color_id); } @@ -74,8 +72,7 @@ STATIC mp_obj_t builtins_Light_off(mp_obj_t self_in) { if (!self->pbdev) { // No external device, so assume command is for the internal light pb_assert(pbio_light_off(PBIO_PORT_SELF)); - } - else { + } else { pbdevice_color_light_on(self->pbdev, PBIO_LIGHT_COLOR_NONE); } return mp_const_none; @@ -84,8 +81,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(builtins_Light_off_obj, builtins_Light_off); // dir(pybricks.builtins.Light) STATIC const mp_rom_map_elem_t builtins_Light_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_on ), MP_ROM_PTR(&builtins_Light_on_obj) }, - { MP_ROM_QSTR(MP_QSTR_off ), MP_ROM_PTR(&builtins_Light_off_obj) }, + { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&builtins_Light_on_obj) }, + { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&builtins_Light_off_obj) }, }; STATIC MP_DEFINE_CONST_DICT(builtins_Light_locals_dict, builtins_Light_locals_dict_table); @@ -93,13 +90,13 @@ STATIC MP_DEFINE_CONST_DICT(builtins_Light_locals_dict, builtins_Light_locals_di const mp_obj_type_t builtins_Light_type = { { &mp_type_type }, .name = MP_QSTR_Light, - .locals_dict = (mp_obj_dict_t*)&builtins_Light_locals_dict, + .locals_dict = (mp_obj_dict_t *)&builtins_Light_locals_dict, }; // dir(pybricks.builtins.ColorLight) STATIC const mp_rom_map_elem_t builtins_ColorLight_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_on ), MP_ROM_PTR(&builtins_ColorLight_on_obj) }, - { MP_ROM_QSTR(MP_QSTR_off ), MP_ROM_PTR(&builtins_Light_off_obj) }, + { MP_ROM_QSTR(MP_QSTR_on), MP_ROM_PTR(&builtins_ColorLight_on_obj) }, + { MP_ROM_QSTR(MP_QSTR_off), MP_ROM_PTR(&builtins_Light_off_obj) }, }; STATIC MP_DEFINE_CONST_DICT(builtins_ColorLight_locals_dict, builtins_ColorLight_locals_dict_table); @@ -107,7 +104,7 @@ STATIC MP_DEFINE_CONST_DICT(builtins_ColorLight_locals_dict, builtins_ColorLight const mp_obj_type_t builtins_ColorLight_type = { { &mp_type_type }, .name = MP_QSTR_ColorLight, - .locals_dict = (mp_obj_dict_t*)&builtins_ColorLight_locals_dict, + .locals_dict = (mp_obj_dict_t *)&builtins_ColorLight_locals_dict, }; mp_obj_t builtins_Light_obj_make_new(pbdevice_t *pbdev, const mp_obj_type_t *type) { @@ -156,8 +153,7 @@ STATIC mp_obj_t builtins_Control_limits(size_t n_args, const mp_obj_t *pos_args, builtins_Control_obj_t, self, PB_ARG_DEFAULT_NONE(speed), PB_ARG_DEFAULT_NONE(acceleration), - PB_ARG_DEFAULT_NONE(actuation) - ); + PB_ARG_DEFAULT_NONE(actuation)); // Read current values int32_t _speed, _acceleration, _actuation; @@ -196,8 +192,7 @@ STATIC mp_obj_t builtins_Control_pid(size_t n_args, const mp_obj_t *pos_args, mp PB_ARG_DEFAULT_NONE(kd), PB_ARG_DEFAULT_NONE(integral_range), PB_ARG_DEFAULT_NONE(integral_rate), - PB_ARG_DEFAULT_NONE(feed_forward) - ); + PB_ARG_DEFAULT_NONE(feed_forward)); // Read current values int16_t _kp, _ki, _kd; @@ -240,8 +235,7 @@ STATIC mp_obj_t builtins_Control_target_tolerances(size_t n_args, const mp_obj_t PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, builtins_Control_obj_t, self, PB_ARG_DEFAULT_NONE(speed), - PB_ARG_DEFAULT_NONE(position) - ); + PB_ARG_DEFAULT_NONE(position)); // Read current values int32_t _speed, _position; @@ -274,8 +268,7 @@ STATIC mp_obj_t builtins_Control_stall_tolerances(size_t n_args, const mp_obj_t PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, builtins_Control_obj_t, self, PB_ARG_DEFAULT_NONE(speed), - PB_ARG_DEFAULT_NONE(time) - ); + PB_ARG_DEFAULT_NONE(time)); // Read current values int32_t _speed, _time; @@ -312,10 +305,10 @@ STATIC mp_obj_t builtins_Control_trajectory(mp_obj_t self_in) { trajectory = self->control->trajectory; if (self->control->type != PBIO_CONTROL_NONE) { - parms[0] = mp_obj_new_int((trajectory.t0-trajectory.t0)/1000); - parms[1] = mp_obj_new_int((trajectory.t1-trajectory.t0)/1000); - parms[2] = mp_obj_new_int((trajectory.t2-trajectory.t0)/1000); - parms[3] = mp_obj_new_int((trajectory.t3-trajectory.t0)/1000); + parms[0] = mp_obj_new_int((trajectory.t0 - trajectory.t0) / 1000); + parms[1] = mp_obj_new_int((trajectory.t1 - trajectory.t0) / 1000); + parms[2] = mp_obj_new_int((trajectory.t2 - trajectory.t0) / 1000); + parms[3] = mp_obj_new_int((trajectory.t3 - trajectory.t0) / 1000); parms[4] = mp_obj_new_int(trajectory.th0); parms[5] = mp_obj_new_int(trajectory.th1); parms[6] = mp_obj_new_int(trajectory.th2); @@ -346,14 +339,14 @@ MP_DEFINE_CONST_FUN_OBJ_1(builtins_Control_stalled_obj, builtins_Control_stalled // dir(pybricks.builtins.Control) STATIC const mp_rom_map_elem_t builtins_Control_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_limits ), MP_ROM_PTR(&builtins_Control_limits_obj ) }, - { MP_ROM_QSTR(MP_QSTR_pid ), MP_ROM_PTR(&builtins_Control_pid_obj ) }, + { MP_ROM_QSTR(MP_QSTR_limits), MP_ROM_PTR(&builtins_Control_limits_obj) }, + { MP_ROM_QSTR(MP_QSTR_pid), MP_ROM_PTR(&builtins_Control_pid_obj) }, { MP_ROM_QSTR(MP_QSTR_target_tolerances), MP_ROM_PTR(&builtins_Control_target_tolerances_obj) }, - { MP_ROM_QSTR(MP_QSTR_stall_tolerances ), MP_ROM_PTR(&builtins_Control_stall_tolerances_obj ) }, - { MP_ROM_QSTR(MP_QSTR_trajectory ), MP_ROM_PTR(&builtins_Control_trajectory_obj ) }, - { MP_ROM_QSTR(MP_QSTR_done ), MP_ROM_PTR(&builtins_Control_done_obj ) }, - { MP_ROM_QSTR(MP_QSTR_stalled ), MP_ROM_PTR(&builtins_Control_stalled_obj ) }, - { MP_ROM_QSTR(MP_QSTR_scale ), MP_ROM_ATTRIBUTE_OFFSET(builtins_Control_obj_t, scale) }, + { MP_ROM_QSTR(MP_QSTR_stall_tolerances), MP_ROM_PTR(&builtins_Control_stall_tolerances_obj) }, + { MP_ROM_QSTR(MP_QSTR_trajectory), MP_ROM_PTR(&builtins_Control_trajectory_obj) }, + { MP_ROM_QSTR(MP_QSTR_done), MP_ROM_PTR(&builtins_Control_done_obj) }, + { MP_ROM_QSTR(MP_QSTR_stalled), MP_ROM_PTR(&builtins_Control_stalled_obj) }, + { MP_ROM_QSTR(MP_QSTR_scale), MP_ROM_ATTRIBUTE_OFFSET(builtins_Control_obj_t, scale) }, }; STATIC MP_DEFINE_CONST_DICT(builtins_Control_locals_dict, builtins_Control_locals_dict_table); @@ -361,5 +354,5 @@ STATIC MP_DEFINE_CONST_DICT(builtins_Control_locals_dict, builtins_Control_local const mp_obj_type_t builtins_Control_type = { { &mp_type_type }, .name = MP_QSTR_Control, - .locals_dict = (mp_obj_dict_t*)&builtins_Control_locals_dict, + .locals_dict = (mp_obj_dict_t *)&builtins_Control_locals_dict, }; diff --git a/extmod/modbuttons.c b/extmod/modbuttons.c index 4ff7e4e5e..f3a14dcdc 100644 --- a/extmod/modbuttons.c +++ b/extmod/modbuttons.c @@ -52,7 +52,7 @@ STATIC MP_DEFINE_CONST_DICT(pb_module_buttons_globals, buttons_globals_table); const mp_obj_module_t pb_module_buttons = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_buttons_globals, + .globals = (mp_obj_dict_t *)&pb_module_buttons_globals, }; #endif // PYBRICKS_PY_BUTTONS diff --git a/extmod/moddebug.c b/extmod/moddebug.c index 05b1473ff..68892fd0a 100644 --- a/extmod/moddebug.c +++ b/extmod/moddebug.c @@ -112,5 +112,5 @@ STATIC MP_DEFINE_CONST_DICT(pb_module_debug_globals, debug_globals_table); const mp_obj_module_t pb_module_debug = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_debug_globals, + .globals = (mp_obj_dict_t *)&pb_module_debug_globals, }; diff --git a/extmod/modev3devices.c b/extmod/modev3devices.c index 8556078bf..2f1298daf 100644 --- a/extmod/modev3devices.c +++ b/extmod/modev3devices.c @@ -25,13 +25,12 @@ typedef struct _ev3devices_TouchSensor_obj_t { } ev3devices_TouchSensor_obj_t; // pybricks.ev3devices.TouchSensor.__init__ -STATIC mp_obj_t ev3devices_TouchSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t ev3devices_TouchSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); ev3devices_TouchSensor_obj_t *self = m_new_obj(ev3devices_TouchSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -61,7 +60,7 @@ STATIC const mp_obj_type_t ev3devices_TouchSensor_type = { { &mp_type_type }, .name = MP_QSTR_TouchSensor, .make_new = ev3devices_TouchSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&ev3devices_TouchSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ev3devices_TouchSensor_locals_dict, }; // pybricks.ev3devices.InfraredSensor class object @@ -71,13 +70,12 @@ typedef struct _ev3devices_InfraredSensor_obj_t { } ev3devices_InfraredSensor_obj_t; // pybricks.ev3devices.InfraredSensor.__init__ -STATIC mp_obj_t ev3devices_InfraredSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t ev3devices_InfraredSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); ev3devices_InfraredSensor_obj_t *self = m_new_obj(ev3devices_InfraredSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -100,8 +98,7 @@ STATIC mp_obj_t ev3devices_InfraredSensor_beacon(size_t n_args, const mp_obj_t * PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3devices_InfraredSensor_obj_t, self, - PB_ARG_REQUIRED(channel) - ); + PB_ARG_REQUIRED(channel)); mp_int_t channel_no = pb_obj_get_int(channel); if (channel_no < 1 || channel_no > 4) { @@ -111,16 +108,15 @@ STATIC mp_obj_t ev3devices_InfraredSensor_beacon(size_t n_args, const mp_obj_t * int32_t beacon_data[8]; pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_EV3_INFRARED_SENSOR__SEEK, beacon_data); - mp_int_t heading = beacon_data[channel_no*2-2]*3; - mp_int_t distance = beacon_data[channel_no*2-1]; + mp_int_t heading = beacon_data[channel_no * 2 - 2] * 3; + mp_int_t distance = beacon_data[channel_no * 2 - 1]; mp_obj_t ret[2]; if (distance == -128) { ret[0] = mp_const_none; ret[1] = mp_const_none; - } - else { + } else { ret[0] = mp_obj_new_int(distance); ret[1] = mp_obj_new_int(heading); } @@ -134,8 +130,7 @@ STATIC mp_obj_t ev3devices_InfraredSensor_buttons(size_t n_args, const mp_obj_t PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3devices_InfraredSensor_obj_t, self, - PB_ARG_REQUIRED(channel) - ); + PB_ARG_REQUIRED(channel)); mp_int_t channel_no = pb_obj_get_int(channel); if (channel_no < 1 || channel_no > 4) { @@ -145,11 +140,11 @@ STATIC mp_obj_t ev3devices_InfraredSensor_buttons(size_t n_args, const mp_obj_t int32_t buttons_data[4]; pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_EV3_INFRARED_SENSOR__REMOTE, buttons_data); - mp_int_t encoded = buttons_data[channel_no-1]; + mp_int_t encoded = buttons_data[channel_no - 1]; mp_obj_t pressed[2]; uint8_t len = 0; - switch(encoded) { + switch (encoded) { case 0: break; case 1: @@ -246,7 +241,7 @@ STATIC const mp_obj_type_t ev3devices_InfraredSensor_type = { { &mp_type_type }, .name = MP_QSTR_InfraredSensor, .make_new = ev3devices_InfraredSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&ev3devices_InfraredSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ev3devices_InfraredSensor_locals_dict, }; // pybricks.ev3devices.ColorSensor class object @@ -256,12 +251,11 @@ typedef struct _ev3devices_ColorSensor_obj_t { } ev3devices_ColorSensor_obj_t; // pybricks.ev3devices.ColorSensor.__init__ -STATIC mp_obj_t ev3devices_ColorSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t ev3devices_ColorSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); ev3devices_ColorSensor_obj_t *self = m_new_obj(ev3devices_ColorSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -276,7 +270,7 @@ STATIC mp_obj_t ev3devices_ColorSensor_color(mp_obj_t self_in) { int32_t color; pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_EV3_COLOR_SENSOR__COLOR, &color); - switch(color) { + switch (color) { case 1: return pb_const_color_black; case 2: @@ -322,9 +316,9 @@ STATIC mp_obj_t ev3devices_ColorSensor_rgb(mp_obj_t self_in) { pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_EV3_COLOR_SENSOR__RGB_RAW, rgb); mp_obj_t tup[3]; - rgb[0] = (0.258*rgb[0])-0.3; - rgb[1] = (0.280*rgb[1])-0.8; - rgb[2] = (0.523*rgb[2])-3.7; + rgb[0] = (0.258 * rgb[0]) - 0.3; + rgb[1] = (0.280 * rgb[1]) - 0.8; + rgb[2] = (0.523 * rgb[2]) - 3.7; for (uint8_t i = 0; i < 3; i++) { rgb[i] = (rgb[i] > 100 ? 100 : rgb[i]); @@ -338,9 +332,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(ev3devices_ColorSensor_rgb_obj, ev3devices_Colo // dir(pybricks.ev3devices.ColorSensor) STATIC const mp_rom_map_elem_t ev3devices_ColorSensor_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_reflection), MP_ROM_PTR(&ev3devices_ColorSensor_reflection_obj) }, - { MP_ROM_QSTR(MP_QSTR_ambient ), MP_ROM_PTR(&ev3devices_ColorSensor_ambient_obj) }, - { MP_ROM_QSTR(MP_QSTR_color ), MP_ROM_PTR(&ev3devices_ColorSensor_color_obj) }, - { MP_ROM_QSTR(MP_QSTR_rgb ), MP_ROM_PTR(&ev3devices_ColorSensor_rgb_obj) }, + { MP_ROM_QSTR(MP_QSTR_ambient), MP_ROM_PTR(&ev3devices_ColorSensor_ambient_obj) }, + { MP_ROM_QSTR(MP_QSTR_color), MP_ROM_PTR(&ev3devices_ColorSensor_color_obj) }, + { MP_ROM_QSTR(MP_QSTR_rgb), MP_ROM_PTR(&ev3devices_ColorSensor_rgb_obj) }, }; STATIC MP_DEFINE_CONST_DICT(ev3devices_ColorSensor_locals_dict, ev3devices_ColorSensor_locals_dict_table); @@ -349,7 +343,7 @@ STATIC const mp_obj_type_t ev3devices_ColorSensor_type = { { &mp_type_type }, .name = MP_QSTR_ColorSensor, .make_new = ev3devices_ColorSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&ev3devices_ColorSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ev3devices_ColorSensor_locals_dict, }; // pybricks.ev3devices.UltrasonicSensor class object @@ -360,13 +354,12 @@ typedef struct _ev3devices_UltrasonicSensor_obj_t { // pybricks.ev3devices.UltrasonicSensor.__init__ -STATIC mp_obj_t ev3devices_UltrasonicSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t ev3devices_UltrasonicSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); ev3devices_UltrasonicSensor_obj_t *self = m_new_obj(ev3devices_UltrasonicSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -380,14 +373,12 @@ STATIC mp_obj_t ev3devices_UltrasonicSensor_distance(size_t n_args, const mp_obj PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3devices_UltrasonicSensor_obj_t, self, - PB_ARG_DEFAULT_FALSE(silent) - ); + PB_ARG_DEFAULT_FALSE(silent)); int32_t distance; if (mp_obj_is_true(silent)) { pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_EV3_ULTRASONIC_SENSOR__SI_CM, &distance); - } - else { + } else { pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_EV3_ULTRASONIC_SENSOR__DIST_CM, &distance); } return mp_obj_new_int(distance); @@ -415,7 +406,7 @@ STATIC const mp_obj_type_t ev3devices_UltrasonicSensor_type = { { &mp_type_type }, .name = MP_QSTR_UltrasonicSensor, .make_new = ev3devices_UltrasonicSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&ev3devices_UltrasonicSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ev3devices_UltrasonicSensor_locals_dict, }; // pybricks.ev3devices.GyroSensor class object @@ -436,21 +427,19 @@ STATIC mp_int_t ev3devices_GyroSensor_get_angle_offset(pbdevice_t *pbdev, pbio_d // Get new offset using arguments and raw values if (direction == PBIO_DIRECTION_CLOCKWISE) { return raw_angle - new_angle; - } - else { + } else { return -raw_angle - new_angle; } } // pybricks.ev3devices.GyroSensor.__init__ -STATIC mp_obj_t ev3devices_GyroSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t ev3devices_GyroSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, PB_ARG_REQUIRED(port), - PB_ARG_DEFAULT_OBJ(direction, pb_Direction_CLOCKWISE_obj) - ); + PB_ARG_DEFAULT_OBJ(direction, pb_Direction_CLOCKWISE_obj)); ev3devices_GyroSensor_obj_t *self = m_new_obj(ev3devices_GyroSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; self->direction = pb_type_enum_get_value(direction, &pb_enum_type_Direction); mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -473,8 +462,7 @@ STATIC mp_obj_t ev3devices_GyroSensor_speed(mp_obj_t self_in) { if (self->direction == PBIO_DIRECTION_CLOCKWISE) { return mp_obj_new_int(raw_speed); - } - else { + } else { return mp_obj_new_int(-raw_speed); } } @@ -488,8 +476,7 @@ STATIC mp_obj_t ev3devices_GyroSensor_angle(mp_obj_t self_in) { if (self->direction == PBIO_DIRECTION_CLOCKWISE) { return mp_obj_new_int(raw_angle - self->offset); - } - else { + } else { return mp_obj_new_int(-raw_angle - self->offset); } } @@ -499,8 +486,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(ev3devices_GyroSensor_angle_obj, ev3devices_Gyr STATIC mp_obj_t ev3devices_GyroSensor_reset_angle(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, ev3devices_GyroSensor_obj_t, self, - PB_ARG_REQUIRED(angle) - ); + PB_ARG_REQUIRED(angle)); self->offset = ev3devices_GyroSensor_get_angle_offset(self->pbdev, self->direction, pb_obj_get_int(angle)); return mp_const_none; @@ -520,7 +506,7 @@ STATIC const mp_obj_type_t ev3devices_GyroSensor_type = { { &mp_type_type }, .name = MP_QSTR_GyroSensor, .make_new = ev3devices_GyroSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&ev3devices_GyroSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ev3devices_GyroSensor_locals_dict, }; // dir(pybricks.ev3devices) @@ -537,5 +523,5 @@ STATIC const mp_rom_map_elem_t ev3devices_globals_table[] = { STATIC MP_DEFINE_CONST_DICT(pb_module_ev3devices_globals, ev3devices_globals_table); const mp_obj_module_t pb_module_ev3devices = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_ev3devices_globals, + .globals = (mp_obj_dict_t *)&pb_module_ev3devices_globals, }; diff --git a/extmod/modexperimental.c b/extmod/modexperimental.c index 9efae8757..7220c2ba4 100644 --- a/extmod/modexperimental.c +++ b/extmod/modexperimental.c @@ -57,7 +57,7 @@ STATIC MP_DEFINE_CONST_DICT(mod_experimental_globals, mod_experimental_globals_t const mp_obj_module_t pb_module_experimental = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mod_experimental_globals, + .globals = (mp_obj_dict_t *)&mod_experimental_globals, }; #endif // PYBRICKS_PY_EXPERIMENTAL diff --git a/extmod/modhubs.c b/extmod/modhubs.c index ec43b8374..60b17c2a1 100644 --- a/extmod/modhubs.c +++ b/extmod/modhubs.c @@ -30,7 +30,7 @@ typedef struct _hubs_EV3Brick_obj_t { STATIC mp_obj_t hubs_EV3Brick_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { hubs_EV3Brick_obj_t *self = m_new_obj(hubs_EV3Brick_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_obj_t screen_args[] = { MP_ROM_QSTR(MP_QSTR__screen_) }; self->screen = pb_type_ev3dev_Image.make_new(&pb_type_ev3dev_Image, 1, 0, screen_args); @@ -50,7 +50,7 @@ STATIC const mp_rom_map_elem_t hubs_EV3Brick_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_battery), MP_ROM_PTR(&pb_module_battery) }, { MP_ROM_QSTR(MP_QSTR_screen), MP_ROM_ATTRIBUTE_OFFSET(hubs_EV3Brick_obj_t, screen) }, { MP_ROM_QSTR(MP_QSTR_speaker), MP_ROM_ATTRIBUTE_OFFSET(hubs_EV3Brick_obj_t, speaker) }, - { MP_ROM_QSTR(MP_QSTR_light), MP_ROM_ATTRIBUTE_OFFSET(hubs_EV3Brick_obj_t, light ) }, + { MP_ROM_QSTR(MP_QSTR_light), MP_ROM_ATTRIBUTE_OFFSET(hubs_EV3Brick_obj_t, light) }, }; STATIC MP_DEFINE_CONST_DICT(hubs_EV3Brick_locals_dict, hubs_EV3Brick_locals_dict_table); @@ -58,7 +58,7 @@ STATIC const mp_obj_type_t hubs_EV3Brick_type = { { &mp_type_type }, .name = MP_QSTR_EV3Brick, .make_new = hubs_EV3Brick_make_new, - .locals_dict = (mp_obj_dict_t*)&hubs_EV3Brick_locals_dict, + .locals_dict = (mp_obj_dict_t *)&hubs_EV3Brick_locals_dict, }; #endif // PYBRICKS_HUB_EV3 @@ -71,9 +71,9 @@ typedef struct _hubs_MoveHub_obj_t { mp_obj_t light; } hubs_MoveHub_obj_t; -STATIC mp_obj_t hubs_MoveHub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t hubs_MoveHub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { hubs_MoveHub_obj_t *self = m_new_obj(hubs_MoveHub_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; // Create an instance of the Light class, representing the hub light self->light = builtins_Light_obj_make_new(NULL, &builtins_ColorLight_type); @@ -97,7 +97,7 @@ STATIC const mp_obj_type_t hubs_MoveHub_type = { { &mp_type_type }, .name = MP_QSTR_MoveHub, .make_new = hubs_MoveHub_make_new, - .locals_dict = (mp_obj_dict_t*)&hubs_MoveHub_locals_dict, + .locals_dict = (mp_obj_dict_t *)&hubs_MoveHub_locals_dict, }; #endif // PYBRICKS_HUB_MOVEHUB @@ -110,9 +110,9 @@ typedef struct _hubs_CityHub_obj_t { mp_obj_t light; } hubs_CityHub_obj_t; -STATIC mp_obj_t hubs_CityHub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t hubs_CityHub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { hubs_CityHub_obj_t *self = m_new_obj(hubs_CityHub_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; // Create an instance of the Light class, representing the hub light self->light = builtins_Light_obj_make_new(NULL, &builtins_ColorLight_type); @@ -136,7 +136,7 @@ STATIC const mp_obj_type_t hubs_CityHub_type = { { &mp_type_type }, .name = MP_QSTR_CityHub, .make_new = hubs_CityHub_make_new, - .locals_dict = (mp_obj_dict_t*)&hubs_CityHub_locals_dict, + .locals_dict = (mp_obj_dict_t *)&hubs_CityHub_locals_dict, }; #endif // PYBRICKS_HUB_CITYHUB @@ -149,9 +149,9 @@ typedef struct _hubs_CPlusHub_obj_t { mp_obj_t light; } hubs_CPlusHub_obj_t; -STATIC mp_obj_t hubs_CPlusHub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t hubs_CPlusHub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { hubs_CPlusHub_obj_t *self = m_new_obj(hubs_CPlusHub_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; // Create an instance of the Light class, representing the hub light self->light = builtins_Light_obj_make_new(NULL, &builtins_ColorLight_type); @@ -175,7 +175,7 @@ STATIC const mp_obj_type_t hubs_CPlusHub_type = { { &mp_type_type }, .name = MP_QSTR_CPlusHub, .make_new = hubs_CPlusHub_make_new, - .locals_dict = (mp_obj_dict_t*)&hubs_CPlusHub_locals_dict, + .locals_dict = (mp_obj_dict_t *)&hubs_CPlusHub_locals_dict, }; #endif // PYBRICKS_HUB_CPLUSHUB @@ -192,9 +192,9 @@ STATIC void hubs_PrimeHub_print(const mp_print_t *print, mp_obj_t self_in, mp_p mp_printf(print, qstr_str(MP_QSTR_PrimeHub)); } -STATIC mp_obj_t hubs_PrimeHub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t hubs_PrimeHub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { hubs_PrimeHub_obj_t *self = m_new_obj(hubs_PrimeHub_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; // Create an instance of the Light class, representing the hub light self->light = builtins_Light_obj_make_new(NULL, &builtins_ColorLight_type); @@ -219,7 +219,7 @@ STATIC const mp_obj_type_t hubs_PrimeHub_type = { .name = MP_QSTR_PrimeHub, .print = hubs_PrimeHub_print, .make_new = hubs_PrimeHub_make_new, - .locals_dict = (mp_obj_dict_t*)&hubs_PrimeHub_locals_dict, + .locals_dict = (mp_obj_dict_t *)&hubs_PrimeHub_locals_dict, }; #endif // PBDRV_CONFIG_HUB_PRIMEHUB @@ -231,9 +231,9 @@ typedef struct _hubs_NXTBrick_obj_t { mp_obj_base_t base; } hubs_NXTBrick_obj_t; -STATIC mp_obj_t hubs_NXTBrick_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t hubs_NXTBrick_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { hubs_NXTBrick_obj_t *self = m_new_obj(hubs_NXTBrick_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; return MP_OBJ_FROM_PTR(self); } @@ -249,7 +249,7 @@ STATIC const mp_obj_type_t hubs_NXTBrick_type = { { &mp_type_type }, .name = MP_QSTR_NXTBrick, .make_new = hubs_NXTBrick_make_new, - .locals_dict = (mp_obj_dict_t*)&hubs_NXTBrick_locals_dict, + .locals_dict = (mp_obj_dict_t *)&hubs_NXTBrick_locals_dict, }; #endif // PYBRICKS_HUB_NXT @@ -257,29 +257,29 @@ STATIC const mp_obj_type_t hubs_NXTBrick_type = { /* Module table */ STATIC const mp_rom_map_elem_t hubs_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_hubs ) }, -#if PYBRICKS_HUB_MOVEHUB + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_hubs) }, + #if PYBRICKS_HUB_MOVEHUB { MP_ROM_QSTR(MP_QSTR_MoveHub), MP_ROM_PTR(&hubs_MoveHub_type) }, -#endif -#if PYBRICKS_HUB_CITYHUB + #endif + #if PYBRICKS_HUB_CITYHUB { MP_ROM_QSTR(MP_QSTR_CityHub), MP_ROM_PTR(&hubs_CityHub_type) }, -#endif -#if PYBRICKS_HUB_CPLUSHUB + #endif + #if PYBRICKS_HUB_CPLUSHUB { MP_ROM_QSTR(MP_QSTR_CPlusHub), MP_ROM_PTR(&hubs_CPlusHub_type) }, -#endif -#ifdef PBDRV_CONFIG_HUB_PRIMEHUB + #endif + #ifdef PBDRV_CONFIG_HUB_PRIMEHUB { MP_ROM_QSTR(MP_QSTR_PrimeHub), MP_ROM_PTR(&hubs_PrimeHub_type) }, -#endif -#if PYBRICKS_HUB_NXT + #endif + #if PYBRICKS_HUB_NXT { MP_ROM_QSTR(MP_QSTR_NXTBrick), MP_ROM_PTR(&hubs_NXTBrick_type) }, -#endif -#if PYBRICKS_HUB_EV3 + #endif + #if PYBRICKS_HUB_EV3 { MP_ROM_QSTR(MP_QSTR_EV3Brick), MP_ROM_PTR(&hubs_EV3Brick_type) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(pb_module_hubs_globals, hubs_globals_table); const mp_obj_module_t pb_module_hubs = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_hubs_globals, + .globals = (mp_obj_dict_t *)&pb_module_hubs_globals, }; diff --git a/extmod/modiodevices.c b/extmod/modiodevices.c index 494b351ca..a5ea6555f 100644 --- a/extmod/modiodevices.c +++ b/extmod/modiodevices.c @@ -28,13 +28,12 @@ typedef struct _iodevices_LUMPDevice_obj_t { } iodevices_LUMPDevice_obj_t; // pybricks.iodevices.LUMPDevice.__init__ -STATIC mp_obj_t iodevices_LUMPDevice_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t iodevices_LUMPDevice_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); iodevices_LUMPDevice_obj_t *self = m_new_obj(iodevices_LUMPDevice_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -59,8 +58,7 @@ STATIC mp_obj_t iodevices_LUMPDevice_make_new(const mp_obj_type_t *type, size_t STATIC mp_obj_t iodevices_LUMPDevice_read(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, iodevices_LUMPDevice_obj_t, self, - PB_ARG_REQUIRED(mode) - ); + PB_ARG_REQUIRED(mode)); // Get data already in correct data format int32_t data[PBIO_IODEV_MAX_DATA_SIZE]; @@ -88,8 +86,7 @@ STATIC mp_obj_t iodevices_LUMPDevice_write(size_t n_args, const mp_obj_t *pos_ar PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, iodevices_LUMPDevice_obj_t, self, PB_ARG_REQUIRED(mode), - PB_ARG_REQUIRED(data) - ); + PB_ARG_REQUIRED(data)); // Unpack the user data tuple mp_obj_t *objs; @@ -123,7 +120,7 @@ STATIC MP_DEFINE_CONST_DICT(iodevices_LUMPDevice_locals_dict, iodevices_LUMPDevi STATIC const mp_obj_type_t iodevices_LUMPDevice_type = { { &mp_type_type }, .make_new = iodevices_LUMPDevice_make_new, - .locals_dict = (mp_obj_dict_t*)&iodevices_LUMPDevice_locals_dict, + .locals_dict = (mp_obj_dict_t *)&iodevices_LUMPDevice_locals_dict, }; #if PYBRICKS_PY_EV3DEVICES @@ -132,7 +129,7 @@ STATIC const mp_obj_type_t iodevices_LUMPDevice_type = { #include -#define UART_MAX_LEN (32*1024) +#define UART_MAX_LEN (32 * 1024) // pybricks.iodevices.AnalogSensor class object typedef struct _iodevices_AnalogSensor_obj_t { @@ -142,12 +139,11 @@ typedef struct _iodevices_AnalogSensor_obj_t { } iodevices_AnalogSensor_obj_t; // pybricks.iodevices.AnalogSensor.__init__ -STATIC mp_obj_t iodevices_AnalogSensor_make_new(const mp_obj_type_t *otype, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t iodevices_AnalogSensor_make_new(const mp_obj_type_t *otype, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); iodevices_AnalogSensor_obj_t *self = m_new_obj(iodevices_AnalogSensor_obj_t); - self->base.type = (mp_obj_type_t*) otype; + self->base.type = (mp_obj_type_t *)otype; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -183,7 +179,7 @@ STATIC mp_obj_t iodevices_AnalogSensor_resistance(mp_obj_t self_in) { return mp_obj_new_int(MP_SSIZE_MAX); } // Return as if a pure voltage divider between load and 10K internal resistor - return mp_obj_new_int((10000*voltage)/(vmax-voltage)); + return mp_obj_new_int((10000 * voltage) / (vmax - voltage)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(iodevices_AnalogSensor_resistance_obj, iodevices_AnalogSensor_resistance); @@ -211,7 +207,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(iodevices_AnalogSensor_passive_obj, iodevices_A STATIC const mp_rom_map_elem_t iodevices_AnalogSensor_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_voltage), MP_ROM_PTR(&iodevices_AnalogSensor_voltage_obj) }, { MP_ROM_QSTR(MP_QSTR_resistance), MP_ROM_PTR(&iodevices_AnalogSensor_resistance_obj) }, - { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&iodevices_AnalogSensor_active_obj ) }, + { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&iodevices_AnalogSensor_active_obj) }, { MP_ROM_QSTR(MP_QSTR_passive), MP_ROM_PTR(&iodevices_AnalogSensor_passive_obj) }, }; STATIC MP_DEFINE_CONST_DICT(iodevices_AnalogSensor_locals_dict, iodevices_AnalogSensor_locals_dict_table); @@ -221,7 +217,7 @@ STATIC const mp_obj_type_t iodevices_AnalogSensor_type = { { &mp_type_type }, .name = MP_QSTR_AnalogSensor, .make_new = iodevices_AnalogSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&iodevices_AnalogSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&iodevices_AnalogSensor_locals_dict, }; // pybricks.iodevices.I2CDevice class object @@ -233,13 +229,12 @@ typedef struct _iodevices_I2CDevice_obj_t { } iodevices_I2CDevice_obj_t; // pybricks.iodevices.I2CDevice.__init__ -STATIC mp_obj_t iodevices_I2CDevice_make_new(const mp_obj_type_t *otype, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t iodevices_I2CDevice_make_new(const mp_obj_type_t *otype, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, PB_ARG_REQUIRED(port), - PB_ARG_REQUIRED(address) - ); + PB_ARG_REQUIRED(address)); iodevices_I2CDevice_obj_t *self = m_new_obj(iodevices_I2CDevice_obj_t); - self->base.type = (mp_obj_type_t*) otype; + self->base.type = (mp_obj_type_t *)otype; // Get port number mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -266,8 +261,7 @@ STATIC mp_obj_t iodevices_I2CDevice_read(size_t n_args, const mp_obj_t *pos_args PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, iodevices_I2CDevice_obj_t, self, PB_ARG_REQUIRED(reg), - PB_ARG_DEFAULT_INT(length, 1) - ); + PB_ARG_DEFAULT_INT(length, 1)); // Get requested data length mp_int_t len = mp_obj_get_int(length); @@ -314,8 +308,7 @@ STATIC mp_obj_t iodevices_I2CDevice_write(size_t n_args, const mp_obj_t *pos_arg PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, iodevices_I2CDevice_obj_t, self, PB_ARG_REQUIRED(reg), - PB_ARG_DEFAULT_NONE(data) - ); + PB_ARG_DEFAULT_NONE(data)); // No data means an empty byte array if (data == mp_const_none) { @@ -373,7 +366,7 @@ STATIC const mp_obj_type_t iodevices_I2CDevice_type = { { &mp_type_type }, .name = MP_QSTR_I2CDevice, .make_new = iodevices_I2CDevice_make_new, - .locals_dict = (mp_obj_dict_t*)&iodevices_I2CDevice_locals_dict, + .locals_dict = (mp_obj_dict_t *)&iodevices_I2CDevice_locals_dict, }; // pybricks.iodevices.UARTDevice class object @@ -384,14 +377,13 @@ typedef struct _iodevices_UARTDevice_obj_t { } iodevices_UARTDevice_obj_t; // pybricks.iodevices.UARTDevice.__init__ -STATIC mp_obj_t iodevices_UARTDevice_make_new(const mp_obj_type_t *otype, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t iodevices_UARTDevice_make_new(const mp_obj_type_t *otype, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, PB_ARG_REQUIRED(port), PB_ARG_REQUIRED(baudrate), - PB_ARG_DEFAULT_NONE(timeout) - ); + PB_ARG_DEFAULT_NONE(timeout)); iodevices_UARTDevice_obj_t *self = m_new_obj(iodevices_UARTDevice_obj_t); - self->base.type = (mp_obj_type_t*) otype; + self->base.type = (mp_obj_type_t *)otype; // Get port number mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -405,7 +397,7 @@ STATIC mp_obj_t iodevices_UARTDevice_make_new(const mp_obj_type_t *otype, size_t port_num, pb_obj_get_int(baudrate), timeout == mp_const_none ? -1 : pb_obj_get_int(timeout) - )); + )); pb_assert(pbio_serial_clear(self->serial)); return MP_OBJ_FROM_PTR(self); @@ -416,8 +408,7 @@ STATIC mp_obj_t iodevices_UARTDevice_write(size_t n_args, const mp_obj_t *pos_ar PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, iodevices_UARTDevice_obj_t, self, - PB_ARG_REQUIRED(data) - ); + PB_ARG_REQUIRED(data)); // Assert that data argument are bytes if (!(mp_obj_is_str_or_bytes(data) || mp_obj_is_type(data, &mp_type_bytearray))) { @@ -483,8 +474,7 @@ STATIC mp_obj_t iodevices_UARTDevice_read(size_t n_args, const mp_obj_t *pos_arg PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, iodevices_UARTDevice_obj_t, self, - PB_ARG_DEFAULT_INT(length, 1) - ); + PB_ARG_DEFAULT_INT(length, 1)); size_t len = mp_obj_get_int(length); return iodevices_UARTDevice_read_internal(self, len); @@ -526,7 +516,7 @@ STATIC const mp_obj_type_t iodevices_UARTDevice_type = { { &mp_type_type }, .name = MP_QSTR_UARTDevice, .make_new = iodevices_UARTDevice_make_new, - .locals_dict = (mp_obj_dict_t*)&iodevices_UARTDevice_locals_dict, + .locals_dict = (mp_obj_dict_t *)&iodevices_UARTDevice_locals_dict, }; // Class structure for Ev3devSensor @@ -538,13 +528,12 @@ typedef struct _iodevices_Ev3devSensor_obj_t { } iodevices_Ev3devSensor_obj_t; // pybricks.iodevices.Ev3devSensor.__init__ -STATIC mp_obj_t iodevices_Ev3devSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t iodevices_Ev3devSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); iodevices_Ev3devSensor_obj_t *self = m_new_obj(iodevices_Ev3devSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -565,8 +554,7 @@ STATIC mp_obj_t iodevices_Ev3devSensor_make_new(const mp_obj_type_t *type, size_ STATIC mp_obj_t iodevices_Ev3devSensor_read(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, iodevices_Ev3devSensor_obj_t, self, - PB_ARG_REQUIRED(mode) - ); + PB_ARG_REQUIRED(mode)); // Get mode index from mode string uint8_t mode_idx = pbdevice_get_mode_id_from_str(self->pbdev, mp_obj_str_get_str(mode)); @@ -604,7 +592,7 @@ STATIC MP_DEFINE_CONST_DICT(iodevices_Ev3devSensor_locals_dict, iodevices_Ev3dev STATIC const mp_obj_type_t iodevices_Ev3devSensor_type = { { &mp_type_type }, .make_new = iodevices_Ev3devSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&iodevices_Ev3devSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&iodevices_Ev3devSensor_locals_dict, }; #endif // PYBRICKS_PY_EV3DEVICES @@ -613,19 +601,19 @@ STATIC const mp_obj_type_t iodevices_Ev3devSensor_type = { STATIC const mp_rom_map_elem_t iodevices_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_iodevices) }, { MP_ROM_QSTR(MP_QSTR_LUMPDevice), MP_ROM_PTR(&iodevices_LUMPDevice_type) }, -#if PYBRICKS_PY_EV3DEVICES + #if PYBRICKS_PY_EV3DEVICES { MP_ROM_QSTR(MP_QSTR_AnalogSensor), MP_ROM_PTR(&iodevices_AnalogSensor_type) }, - { MP_ROM_QSTR(MP_QSTR_I2CDevice), MP_ROM_PTR(&iodevices_I2CDevice_type ) }, - { MP_ROM_QSTR(MP_QSTR_UARTDevice), MP_ROM_PTR(&iodevices_UARTDevice_type ) }, + { MP_ROM_QSTR(MP_QSTR_I2CDevice), MP_ROM_PTR(&iodevices_I2CDevice_type) }, + { MP_ROM_QSTR(MP_QSTR_UARTDevice), MP_ROM_PTR(&iodevices_UARTDevice_type) }, { MP_ROM_QSTR(MP_QSTR_DCMotor), MP_ROM_PTR(&motor_DCMotor_type) }, { MP_ROM_QSTR(MP_QSTR_Ev3devSensor), MP_ROM_PTR(&iodevices_Ev3devSensor_type) }, -#endif // PYBRICKS_PY_EV3DEVICES + #endif // PYBRICKS_PY_EV3DEVICES }; STATIC MP_DEFINE_CONST_DICT(pb_module_iodevices_globals, iodevices_globals_table); const mp_obj_module_t pb_module_iodevices = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_iodevices_globals, + .globals = (mp_obj_dict_t *)&pb_module_iodevices_globals, }; -#endif //if PYBRICKS_PY_IODEVICES +#endif // if PYBRICKS_PY_IODEVICES diff --git a/extmod/modlogger.c b/extmod/modlogger.c index dadf0e2f7..45622330e 100644 --- a/extmod/modlogger.c +++ b/extmod/modlogger.c @@ -30,8 +30,7 @@ STATIC mp_obj_t tools_Logger_start(size_t n_args, const mp_obj_t *pos_args, mp_m PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, tools_Logger_obj_t, self, PB_ARG_REQUIRED(duration), - PB_ARG_DEFAULT_INT(divisor, 1) - ); + PB_ARG_DEFAULT_INT(divisor, 1)); mp_int_t div = pb_obj_get_int(divisor); div = max(div, 1); @@ -49,8 +48,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_KW(tools_Logger_start_obj, 1, tools_Logger_start) STATIC mp_obj_t tools_Logger_get(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, tools_Logger_obj_t, self, - PB_ARG_DEFAULT_NONE(index) - ); + PB_ARG_DEFAULT_NONE(index)); mp_int_t index_val = pb_obj_get_default_int(index, -1); @@ -96,8 +94,8 @@ static void make_data_row_str(char *row, int32_t *data, uint8_t n) { idx += s; // For the last value, replace , by \n - if (v == n-1) { - row[idx-1] = '\n'; + if (v == n - 1) { + row[idx - 1] = '\n'; } } } @@ -106,11 +104,10 @@ STATIC mp_obj_t tools_Logger_save(size_t n_args, const mp_obj_t *pos_args, mp_ma PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, tools_Logger_obj_t, self, - PB_ARG_DEFAULT_NONE(path) - ); + PB_ARG_DEFAULT_NONE(path)); const char *file_path = path == mp_const_none ? "log.txt" : mp_obj_str_get_str(path); -#if PYBRICKS_HUB_EV3 + #if PYBRICKS_HUB_EV3 // Create an empty log file FILE *log_file; @@ -119,9 +116,9 @@ STATIC mp_obj_t tools_Logger_save(size_t n_args, const mp_obj_t *pos_args, mp_ma if (log_file == NULL) { pb_assert(PBIO_ERROR_IO); } -#else + #else mp_printf(&mp_plat_print, "PB_OF:%s\n", file_path); -#endif //PYBRICKS_HUB_EV3 + #endif // PYBRICKS_HUB_EV3 // Read log size information int32_t data[MAX_LOG_VALUES]; @@ -133,7 +130,7 @@ STATIC mp_obj_t tools_Logger_save(size_t n_args, const mp_obj_t *pos_args, mp_ma pbio_error_t err; // Allocate space for one null-terminated row of data - char row_str[max_val_strln*MAX_LOG_VALUES+1]; + char row_str[max_val_strln * MAX_LOG_VALUES + 1]; // Write data to file line by line for (int32_t i = 0; i < sampled; i++) { @@ -147,26 +144,26 @@ STATIC mp_obj_t tools_Logger_save(size_t n_args, const mp_obj_t *pos_args, mp_ma // Make one string of values make_data_row_str(row_str, data, num_values); -#if PYBRICKS_HUB_EV3 + #if PYBRICKS_HUB_EV3 // Append the row to file if (fprintf(log_file, "%s", row_str) < 0) { err = PBIO_ERROR_IO; break; } -#else + #else // Print the row mp_print_str(&mp_plat_print, row_str); -#endif // PYBRICKS_HUB_EV3 + #endif // PYBRICKS_HUB_EV3 } -#if PYBRICKS_HUB_EV3 + #if PYBRICKS_HUB_EV3 // Close the file if (fclose(log_file) != 0) { err = PBIO_ERROR_IO; } -#else + #else mp_print_str(&mp_plat_print, "PB_EOF\n"); -#endif // PYBRICKS_HUB_EV3 + #endif // PYBRICKS_HUB_EV3 pb_assert(err); return mp_const_none; @@ -195,7 +192,7 @@ STATIC MP_DEFINE_CONST_DICT(tools_Logger_locals_dict, tools_Logger_locals_dict_t // type(pybricks.tools.Logger) STATIC const mp_obj_type_t tools_Logger_type = { { &mp_type_type }, - .locals_dict = (mp_obj_dict_t*)&tools_Logger_locals_dict, + .locals_dict = (mp_obj_dict_t *)&tools_Logger_locals_dict, .unary_op = tools_Logger_unary_op, }; @@ -203,7 +200,7 @@ mp_obj_t logger_obj_make_new(pbio_log_t *log) { // Create new light instance tools_Logger_obj_t *logger = m_new_obj(tools_Logger_obj_t); // Set type and iodev - logger->base.type = (mp_obj_type_t*) &tools_Logger_type; + logger->base.type = (mp_obj_type_t *)&tools_Logger_type; logger->log = log; return logger; } diff --git a/extmod/modmedia_ev3dev.c b/extmod/modmedia_ev3dev.c index e2fc9ec69..fd5002e80 100644 --- a/extmod/modmedia_ev3dev.c +++ b/extmod/modmedia_ev3dev.c @@ -29,7 +29,7 @@ STATIC MP_DEFINE_CONST_DICT(pb_module_media_ev3dev_globals, media_ev3dev_globals const mp_obj_module_t pb_module_media_ev3dev = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_media_ev3dev_globals, + .globals = (mp_obj_dict_t *)&pb_module_media_ev3dev_globals, }; #endif // PYBRICKS_PY_MEDIA_EV3DEV diff --git a/extmod/modmotor.c b/extmod/modmotor.c index da4ab134f..89e7362a3 100644 --- a/extmod/modmotor.c +++ b/extmod/modmotor.c @@ -24,11 +24,10 @@ #include "pbkwarg.h" // pybricks.builtins.DCMotor.__init__ -STATIC mp_obj_t motor_DCMotor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args){ +STATIC mp_obj_t motor_DCMotor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, PB_ARG_REQUIRED(port), - PB_ARG_DEFAULT_OBJ(positive_direction, pb_Direction_CLOCKWISE_obj) - ); + PB_ARG_DEFAULT_OBJ(positive_direction, pb_Direction_CLOCKWISE_obj)); // Configure the motor with the selected arguments at pbio level mp_int_t port_arg = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -44,7 +43,7 @@ STATIC mp_obj_t motor_DCMotor_make_new(const mp_obj_type_t *type, size_t n_args, // On success, create and return the MicroPython object motor_DCMotor_obj_t *self = m_new_obj(motor_DCMotor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; self->dcmotor = dc; return MP_OBJ_FROM_PTR(self); } @@ -55,8 +54,8 @@ void motor_DCMotor_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin // Get the dcmotor from self, which is either Motor or DCMotor pbio_dcmotor_t *dcmotor = mp_obj_is_type(self_in, &motor_Motor_type) ? - ((motor_Motor_obj_t*) MP_OBJ_TO_PTR(self_in))->srv->dcmotor : - ((motor_DCMotor_obj_t*) MP_OBJ_TO_PTR(self_in))->dcmotor; + ((motor_Motor_obj_t *)MP_OBJ_TO_PTR(self_in))->srv->dcmotor : + ((motor_DCMotor_obj_t *)MP_OBJ_TO_PTR(self_in))->dcmotor; mp_printf(print, "Motor properties:\n" @@ -64,8 +63,7 @@ void motor_DCMotor_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin "Port\t\t %c\n" "Positive dir.\t %s", dcmotor->port, - dcmotor->direction == PBIO_DIRECTION_CLOCKWISE ? "clockwise" : "counterclockwise" - ); + dcmotor->direction == PBIO_DIRECTION_CLOCKWISE ? "clockwise" : "counterclockwise"); } // pybricks.builtins.DCMotor.dc @@ -73,8 +71,7 @@ void motor_DCMotor_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin STATIC mp_obj_t motor_DCMotor_duty(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { // Parse all arguments except the first one (self) PB_PARSE_ARGS_METHOD_SKIP_SELF(n_args, pos_args, kw_args, - PB_ARG_REQUIRED(duty) - ); + PB_ARG_REQUIRED(duty)); mp_int_t duty_cycle = pb_obj_get_int(duty); @@ -84,8 +81,7 @@ STATIC mp_obj_t motor_DCMotor_duty(size_t n_args, const mp_obj_t *pos_args, mp_m if (is_servo) { motor_Motor_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); pb_assert(pbio_servo_set_duty_cycle(self->srv, duty_cycle)); - } - else { + } else { motor_DCMotor_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); pb_assert(pbio_dcmotor_set_duty_cycle_usr(self->dcmotor, duty_cycle)); } @@ -104,8 +100,7 @@ STATIC mp_obj_t motor_DCMotor_stop(mp_obj_t self_in) { if (is_servo) { motor_Motor_obj_t *self = MP_OBJ_TO_PTR(self_in); pb_assert(pbio_servo_stop(self->srv, PBIO_ACTUATION_COAST)); - } - else { + } else { motor_DCMotor_obj_t *self = MP_OBJ_TO_PTR(self_in); pb_assert(pbio_dcmotor_coast(self->dcmotor)); } @@ -123,8 +118,7 @@ STATIC mp_obj_t motor_DCMotor_brake(mp_obj_t self_in) { if (is_servo) { motor_Motor_obj_t *self = MP_OBJ_TO_PTR(self_in); pb_assert(pbio_servo_stop(self->srv, PBIO_ACTUATION_BRAKE)); - } - else { + } else { motor_DCMotor_obj_t *self = MP_OBJ_TO_PTR(self_in); #if PYBRICKS_PY_EV3DEVICES // Workaround for ev3dev dc-motor not coasting on first try @@ -151,7 +145,7 @@ const mp_obj_type_t motor_DCMotor_type = { .name = MP_QSTR_DCMotor, .print = motor_DCMotor_print, .make_new = motor_DCMotor_make_new, - .locals_dict = (mp_obj_dict_t*)&motor_DCMotor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&motor_DCMotor_locals_dict, }; /* Wait for servo maneuver to complete */ @@ -167,12 +161,11 @@ STATIC void wait_for_completion(pbio_servo_t *srv) { } // pybricks.builtins.Motor.__init__ -STATIC mp_obj_t motor_Motor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args){ +STATIC mp_obj_t motor_Motor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, PB_ARG_REQUIRED(port), PB_ARG_DEFAULT_OBJ(positive_direction, pb_Direction_CLOCKWISE_obj), - PB_ARG_DEFAULT_NONE(gears) - ); + PB_ARG_DEFAULT_NONE(gears)); // Configure the motor with the selected arguments at pbio level mp_int_t port_arg = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -191,7 +184,7 @@ STATIC mp_obj_t motor_Motor_make_new(const mp_obj_type_t *type, size_t n_args, s mp_obj_get_array(gears, &n_trains, &trains); // If the first and last element is an integer, assume the user gave just one list of gears, i.e. [12, 20, 36] - bool is_one_train = MP_OBJ_IS_SMALL_INT(trains[0]) && MP_OBJ_IS_SMALL_INT(trains[n_trains-1]); + bool is_one_train = MP_OBJ_IS_SMALL_INT(trains[0]) && MP_OBJ_IS_SMALL_INT(trains[n_trains - 1]); // This means we don't have a list of gear trains, but just one gear train with a given number of gears if (is_one_train) { n_gears = n_trains; @@ -207,7 +200,7 @@ STATIC mp_obj_t motor_Motor_make_new(const mp_obj_type_t *type, size_t n_args, s } // For this gear train, compute the ratio from the first and last gear fix16_t first_gear = fix16_from_int(mp_obj_get_int(gear_list[0])); - fix16_t last_gear = fix16_from_int(mp_obj_get_int(gear_list[n_gears-1])); + fix16_t last_gear = fix16_from_int(mp_obj_get_int(gear_list[n_gears - 1])); if (first_gear < 1 || last_gear < 1) { pb_assert(PBIO_ERROR_INVALID_ARG); } @@ -233,7 +226,7 @@ STATIC mp_obj_t motor_Motor_make_new(const mp_obj_type_t *type, size_t n_args, s // On success, proceed to create and return the MicroPython object motor_Motor_obj_t *self = m_new_obj(motor_Motor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; self->srv = srv; // Create an instance of the Logger class @@ -260,8 +253,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(motor_Motor_angle_obj, motor_Motor_angle); STATIC mp_obj_t motor_Motor_reset_angle(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, motor_Motor_obj_t, self, - PB_ARG_DEFAULT_NONE(angle) - ); + PB_ARG_DEFAULT_NONE(angle)); // If no angle argument is given, reset to the absolute value bool reset_to_abs = angle == mp_const_none; @@ -291,8 +283,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(motor_Motor_speed_obj, motor_Motor_speed); STATIC mp_obj_t motor_Motor_run(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, motor_Motor_obj_t, self, - PB_ARG_REQUIRED(speed) - ); + PB_ARG_REQUIRED(speed)); mp_int_t speed_arg = pb_obj_get_int(speed); pb_assert(pbio_servo_run(self->srv, speed_arg)); @@ -316,13 +307,12 @@ STATIC mp_obj_t motor_Motor_run_time(size_t n_args, const mp_obj_t *pos_args, mp PB_ARG_REQUIRED(speed), PB_ARG_REQUIRED(time), PB_ARG_DEFAULT_OBJ(then, pb_Stop_HOLD_obj), - PB_ARG_DEFAULT_TRUE(wait) - ); + PB_ARG_DEFAULT_TRUE(wait)); mp_int_t speed_arg = pb_obj_get_int(speed); mp_int_t time_arg = pb_obj_get_int(time); - if (time_arg < 0 || time_arg > DURATION_MAX_S*MS_PER_SECOND) { + if (time_arg < 0 || time_arg > DURATION_MAX_S * MS_PER_SECOND) { pb_assert(PBIO_ERROR_INVALID_ARG); } @@ -345,8 +335,7 @@ STATIC mp_obj_t motor_Motor_run_until_stalled(size_t n_args, const mp_obj_t *pos motor_Motor_obj_t, self, PB_ARG_REQUIRED(speed), PB_ARG_DEFAULT_OBJ(then, pb_Stop_COAST_obj), - PB_ARG_DEFAULT_NONE(duty_limit) - ); + PB_ARG_DEFAULT_NONE(duty_limit)); mp_int_t speed_arg = pb_obj_get_int(speed); pbio_actuation_t after_stop = pb_type_enum_get_value(then, &pb_enum_type_Stop); @@ -409,8 +398,7 @@ STATIC mp_obj_t motor_Motor_run_angle(size_t n_args, const mp_obj_t *pos_args, m PB_ARG_REQUIRED(speed), PB_ARG_REQUIRED(rotation_angle), PB_ARG_DEFAULT_OBJ(then, pb_Stop_HOLD_obj), - PB_ARG_DEFAULT_TRUE(wait) - ); + PB_ARG_DEFAULT_TRUE(wait)); mp_int_t speed_arg = pb_obj_get_int(speed); mp_int_t angle_arg = pb_obj_get_int(rotation_angle); @@ -434,8 +422,7 @@ STATIC mp_obj_t motor_Motor_run_target(size_t n_args, const mp_obj_t *pos_args, PB_ARG_REQUIRED(speed), PB_ARG_REQUIRED(target_angle), PB_ARG_DEFAULT_OBJ(then, pb_Stop_HOLD_obj), - PB_ARG_DEFAULT_TRUE(wait) - ); + PB_ARG_DEFAULT_TRUE(wait)); mp_int_t speed_arg = pb_obj_get_int(speed); mp_int_t angle_arg = pb_obj_get_int(target_angle); @@ -456,8 +443,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_KW(motor_Motor_run_target_obj, 1, motor_Motor_run STATIC mp_obj_t motor_Motor_track_target(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, motor_Motor_obj_t, self, - PB_ARG_REQUIRED(target_angle) - ); + PB_ARG_REQUIRED(target_angle)); mp_int_t target = pb_obj_get_int(target_angle); pb_assert(pbio_servo_track_target(self->srv, target)); @@ -498,7 +484,7 @@ const mp_obj_type_t motor_Motor_type = { .name = MP_QSTR_Motor, .print = motor_DCMotor_print, .make_new = motor_Motor_make_new, - .locals_dict = (mp_obj_dict_t*)&motor_Motor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&motor_Motor_locals_dict, }; #endif // PBDRV_CONFIG_NUM_MOTOR_CONTROLLER diff --git a/extmod/modnxtdevices.c b/extmod/modnxtdevices.c index db2e90436..b3f3ed9b8 100644 --- a/extmod/modnxtdevices.c +++ b/extmod/modnxtdevices.c @@ -22,7 +22,7 @@ // Generic linear scaling of an analog value between a known min and max to a percentage STATIC int32_t analog_scale(int32_t mvolts, int32_t mvolts_min, int32_t mvolts_max, bool invert) { - int32_t scaled = (100*(mvolts-mvolts_min))/(mvolts_max-mvolts_min); + int32_t scaled = (100 * (mvolts - mvolts_min)) / (mvolts_max - mvolts_min); if (invert) { scaled = 100 - scaled; } @@ -36,13 +36,12 @@ typedef struct _nxtdevices_UltrasonicSensor_obj_t { } nxtdevices_UltrasonicSensor_obj_t; // pybricks.nxtdevices.UltrasonicSensor.__init__ -STATIC mp_obj_t nxtdevices_UltrasonicSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t nxtdevices_UltrasonicSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); nxtdevices_UltrasonicSensor_obj_t *self = m_new_obj(nxtdevices_UltrasonicSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -71,7 +70,7 @@ STATIC const mp_obj_type_t nxtdevices_UltrasonicSensor_type = { { &mp_type_type }, .name = MP_QSTR_UltrasonicSensor, .make_new = nxtdevices_UltrasonicSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&nxtdevices_UltrasonicSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&nxtdevices_UltrasonicSensor_locals_dict, }; // pybricks.nxtdevices.TouchSensor class object @@ -81,13 +80,12 @@ typedef struct _nxtdevices_TouchSensor_obj_t { } nxtdevices_TouchSensor_obj_t; // pybricks.nxtdevices.TouchSensor.__init__ -STATIC mp_obj_t nxtdevices_TouchSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t nxtdevices_TouchSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); nxtdevices_TouchSensor_obj_t *self = m_new_obj(nxtdevices_TouchSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -116,7 +114,7 @@ STATIC const mp_obj_type_t nxtdevices_TouchSensor_type = { { &mp_type_type }, .name = MP_QSTR_TouchSensor, .make_new = nxtdevices_TouchSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&nxtdevices_TouchSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&nxtdevices_TouchSensor_locals_dict, }; // pybricks.nxtdevices.SoundSensor class object @@ -130,8 +128,7 @@ STATIC mp_obj_t nxtdevices_SoundSensor_intensity(size_t n_args, const mp_obj_t * PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, nxtdevices_SoundSensor_obj_t, self, - PB_ARG_DEFAULT_TRUE(audible_only) - ); + PB_ARG_DEFAULT_TRUE(audible_only)); uint8_t mode = mp_obj_is_true(audible_only) ? PBIO_IODEV_MODE_NXT_ANALOG__ACTIVE : PBIO_IODEV_MODE_NXT_ANALOG__PASSIVE; int32_t analog; @@ -142,13 +139,12 @@ STATIC mp_obj_t nxtdevices_SoundSensor_intensity(size_t n_args, const mp_obj_t * STATIC MP_DEFINE_CONST_FUN_OBJ_KW(nxtdevices_SoundSensor_intensity_obj, 1, nxtdevices_SoundSensor_intensity); // pybricks.nxtdevices.SoundSensor.__init__ -STATIC mp_obj_t nxtdevices_SoundSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t nxtdevices_SoundSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); nxtdevices_SoundSensor_obj_t *self = m_new_obj(nxtdevices_SoundSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -165,7 +161,7 @@ STATIC mp_obj_t nxtdevices_SoundSensor_make_new(const mp_obj_type_t *type, size_ // dir(pybricks.ev3devices.SoundSensor) STATIC const mp_rom_map_elem_t nxtdevices_SoundSensor_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_intensity), MP_ROM_PTR(&nxtdevices_SoundSensor_intensity_obj ) }, + { MP_ROM_QSTR(MP_QSTR_intensity), MP_ROM_PTR(&nxtdevices_SoundSensor_intensity_obj) }, }; STATIC MP_DEFINE_CONST_DICT(nxtdevices_SoundSensor_locals_dict, nxtdevices_SoundSensor_locals_dict_table); @@ -174,7 +170,7 @@ STATIC const mp_obj_type_t nxtdevices_SoundSensor_type = { { &mp_type_type }, .name = MP_QSTR_SoundSensor, .make_new = nxtdevices_SoundSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&nxtdevices_SoundSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&nxtdevices_SoundSensor_locals_dict, }; // pybricks.nxtdevices.LightSensor class object @@ -206,13 +202,12 @@ STATIC mp_obj_t nxtdevices_LightSensor_reflection(mp_obj_t self_in) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(nxtdevices_LightSensor_reflection_obj, nxtdevices_LightSensor_reflection); // pybricks.nxtdevices.LightSensor.__init__ -STATIC mp_obj_t nxtdevices_LightSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t nxtdevices_LightSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); nxtdevices_LightSensor_obj_t *self = m_new_obj(nxtdevices_LightSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -226,7 +221,7 @@ STATIC mp_obj_t nxtdevices_LightSensor_make_new(const mp_obj_type_t *type, size_ // dir(pybricks.ev3devices.LightSensor) STATIC const mp_rom_map_elem_t nxtdevices_LightSensor_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_ambient), MP_ROM_PTR(&nxtdevices_LightSensor_ambient_obj ) }, + { MP_ROM_QSTR(MP_QSTR_ambient), MP_ROM_PTR(&nxtdevices_LightSensor_ambient_obj) }, { MP_ROM_QSTR(MP_QSTR_reflection), MP_ROM_PTR(&nxtdevices_LightSensor_reflection_obj) }, }; STATIC MP_DEFINE_CONST_DICT(nxtdevices_LightSensor_locals_dict, nxtdevices_LightSensor_locals_dict_table); @@ -236,7 +231,7 @@ STATIC const mp_obj_type_t nxtdevices_LightSensor_type = { { &mp_type_type }, .name = MP_QSTR_LightSensor, .make_new = nxtdevices_LightSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&nxtdevices_LightSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&nxtdevices_LightSensor_locals_dict, }; // pybricks.nxtdevices.ColorSensor class object @@ -247,13 +242,12 @@ typedef struct _nxtdevices_ColorSensor_obj_t { } nxtdevices_ColorSensor_obj_t; // pybricks.nxtdevices.ColorSensor.__init__ -STATIC mp_obj_t nxtdevices_ColorSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t nxtdevices_ColorSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); nxtdevices_ColorSensor_obj_t *self = m_new_obj(nxtdevices_ColorSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -269,7 +263,7 @@ STATIC mp_obj_t nxtdevices_ColorSensor_make_new(const mp_obj_type_t *type, size_ } static mp_obj_t color_obj(pbio_light_color_t color) { - switch(color) { + switch (color) { case PBIO_LIGHT_COLOR_RED: return pb_const_color_red; case PBIO_LIGHT_COLOR_GREEN: @@ -321,7 +315,7 @@ STATIC mp_obj_t nxtdevices_ColorSensor_reflection(mp_obj_t self_in) { int32_t all[5]; pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_NXT_COLOR_SENSOR__MEASURE, all); // Return the average of red, green, and blue reflection - return mp_obj_new_int((all[0]+all[1]+all[2])/3); + return mp_obj_new_int((all[0] + all[1] + all[2]) / 3); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(nxtdevices_ColorSensor_reflection_obj, nxtdevices_ColorSensor_reflection); @@ -361,7 +355,7 @@ STATIC const mp_obj_type_t nxtdevices_ColorSensor_type = { { &mp_type_type }, .name = MP_QSTR_ColorSensor, .make_new = nxtdevices_ColorSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&nxtdevices_ColorSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&nxtdevices_ColorSensor_locals_dict, }; // pybricks.nxtdevices.TemperatureSensor class object @@ -371,13 +365,12 @@ typedef struct _nxtdevices_TemperatureSensor_obj_t { } nxtdevices_TemperatureSensor_obj_t; // pybricks.nxtdevices.TemperatureSensor.__init__ -STATIC mp_obj_t nxtdevices_TemperatureSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t nxtdevices_TemperatureSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); nxtdevices_TemperatureSensor_obj_t *self = m_new_obj(nxtdevices_TemperatureSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -391,7 +384,7 @@ STATIC mp_obj_t nxtdevices_TemperatureSensor_temperature(mp_obj_t self_in) { nxtdevices_TemperatureSensor_obj_t *self = MP_OBJ_TO_PTR(self_in); int32_t temperature_scaled; pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_NXT_TEMPERATURE_SENSOR_CELCIUS, &temperature_scaled); - return mp_obj_new_float((temperature_scaled >> 4)/16.0); + return mp_obj_new_float((temperature_scaled >> 4) / 16.0); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(nxtdevices_TemperatureSensor_temperature_obj, nxtdevices_TemperatureSensor_temperature); @@ -406,7 +399,7 @@ STATIC const mp_obj_type_t nxtdevices_TemperatureSensor_type = { { &mp_type_type }, .name = MP_QSTR_TemperatureSensor, .make_new = nxtdevices_TemperatureSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&nxtdevices_TemperatureSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&nxtdevices_TemperatureSensor_locals_dict, }; // pybricks.nxtdevices.EnergyMeter class object @@ -416,13 +409,12 @@ typedef struct _nxtdevices_EnergyMeter_obj_t { } nxtdevices_EnergyMeter_obj_t; // pybricks.nxtdevices.EnergyMeter.__init__ -STATIC mp_obj_t nxtdevices_EnergyMeter_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t nxtdevices_EnergyMeter_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); nxtdevices_EnergyMeter_obj_t *self = m_new_obj(nxtdevices_EnergyMeter_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -472,7 +464,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(nxtdevices_EnergyMeter_output_obj, nxtdevices_E // dir(pybricks.ev3devices.EnergyMeter) STATIC const mp_rom_map_elem_t nxtdevices_EnergyMeter_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_input), MP_ROM_PTR(&nxtdevices_EnergyMeter_input_obj ) }, + { MP_ROM_QSTR(MP_QSTR_input), MP_ROM_PTR(&nxtdevices_EnergyMeter_input_obj) }, { MP_ROM_QSTR(MP_QSTR_output), MP_ROM_PTR(&nxtdevices_EnergyMeter_output_obj) }, { MP_ROM_QSTR(MP_QSTR_storage), MP_ROM_PTR(&nxtdevices_EnergyMeter_storage_obj) }, }; @@ -483,7 +475,7 @@ STATIC const mp_obj_type_t nxtdevices_EnergyMeter_type = { { &mp_type_type }, .name = MP_QSTR_EnergyMeter, .make_new = nxtdevices_EnergyMeter_make_new, - .locals_dict = (mp_obj_dict_t*)&nxtdevices_EnergyMeter_locals_dict, + .locals_dict = (mp_obj_dict_t *)&nxtdevices_EnergyMeter_locals_dict, }; #endif // PYBRICKS_HUB_EV3 @@ -491,9 +483,9 @@ STATIC const mp_obj_type_t nxtdevices_EnergyMeter_type = { // dir(pybricks.nxtdevices) STATIC const mp_rom_map_elem_t nxtdevices_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_nxtdevices) }, -#if PYBRICKS_HUB_NXT + #if PYBRICKS_HUB_NXT { MP_ROM_QSTR(MP_QSTR_Motor), MP_ROM_PTR(&motor_Motor_type) }, -#else + #else { MP_ROM_QSTR(MP_QSTR_TouchSensor), MP_ROM_PTR(&nxtdevices_TouchSensor_type) }, { MP_ROM_QSTR(MP_QSTR_SoundSensor), MP_ROM_PTR(&nxtdevices_SoundSensor_type) }, { MP_ROM_QSTR(MP_QSTR_LightSensor), MP_ROM_PTR(&nxtdevices_LightSensor_type) }, @@ -501,13 +493,13 @@ STATIC const mp_rom_map_elem_t nxtdevices_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_ColorSensor), MP_ROM_PTR(&nxtdevices_ColorSensor_type) }, { MP_ROM_QSTR(MP_QSTR_TemperatureSensor),MP_ROM_PTR(&nxtdevices_TemperatureSensor_type)}, { MP_ROM_QSTR(MP_QSTR_EnergyMeter), MP_ROM_PTR(&nxtdevices_EnergyMeter_type) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(pb_module_nxtdevices_globals, nxtdevices_globals_table); const mp_obj_module_t pb_module_nxtdevices = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_nxtdevices_globals, + .globals = (mp_obj_dict_t *)&pb_module_nxtdevices_globals, }; diff --git a/extmod/modparameters.c b/extmod/modparameters.c index 85e9c6b7f..bab1f121c 100644 --- a/extmod/modparameters.c +++ b/extmod/modparameters.c @@ -22,36 +22,36 @@ /* Port enum */ STATIC const mp_rom_map_elem_t pb_enum_Port_table[] = { -#if PBDRV_CONFIG_HAS_PORT_A + #if PBDRV_CONFIG_HAS_PORT_A PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_A, PBIO_PORT_A), -#endif -#if PBDRV_CONFIG_HAS_PORT_B + #endif + #if PBDRV_CONFIG_HAS_PORT_B PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_B, PBIO_PORT_B), -#endif -#if PBDRV_CONFIG_HAS_PORT_C + #endif + #if PBDRV_CONFIG_HAS_PORT_C PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_C, PBIO_PORT_C), -#endif -#if PBDRV_CONFIG_HAS_PORT_D + #endif + #if PBDRV_CONFIG_HAS_PORT_D PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_D, PBIO_PORT_D), -#endif -#if PBDRV_CONFIG_HAS_PORT_E + #endif + #if PBDRV_CONFIG_HAS_PORT_E PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_E, PBIO_PORT_E), -#endif -#if PBDRV_CONFIG_HAS_PORT_F + #endif + #if PBDRV_CONFIG_HAS_PORT_F PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_F, PBIO_PORT_F), -#endif -#if PBDRV_CONFIG_HAS_PORT_1 + #endif + #if PBDRV_CONFIG_HAS_PORT_1 PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_S1, PBIO_PORT_1), -#endif -#if PBDRV_CONFIG_HAS_PORT_2 + #endif + #if PBDRV_CONFIG_HAS_PORT_2 PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_S2, PBIO_PORT_2), -#endif -#if PBDRV_CONFIG_HAS_PORT_3 + #endif + #if PBDRV_CONFIG_HAS_PORT_3 PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_S3, PBIO_PORT_3), -#endif -#if PBDRV_CONFIG_HAS_PORT_4 + #endif + #if PBDRV_CONFIG_HAS_PORT_4 PB_ROM_ENUM_MEMBER(pb_enum_type_Port, MP_QSTR_S4, PBIO_PORT_4), -#endif + #endif }; PB_DEFINE_ENUM(pb_enum_type_Port, MP_QSTR_Port, pb_enum_Port_table); @@ -263,7 +263,7 @@ STATIC MP_DEFINE_CONST_DICT(pb_module_parameters_globals, parameters_globals_tab const mp_obj_module_t pb_module_parameters = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_parameters_globals, + .globals = (mp_obj_dict_t *)&pb_module_parameters_globals, }; #endif // PYBRICKS_PY_PARAMETERS diff --git a/extmod/modpupdevices.c b/extmod/modpupdevices.c index fde81adc5..b9d19064c 100644 --- a/extmod/modpupdevices.c +++ b/extmod/modpupdevices.c @@ -29,13 +29,12 @@ typedef struct _pupdevices_ColorDistanceSensor_obj_t { } pupdevices_ColorDistanceSensor_obj_t; // pybricks.pupdevices.ColorDistanceSensor.__init__ -STATIC mp_obj_t pupdevices_ColorDistanceSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t pupdevices_ColorDistanceSensor_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, - PB_ARG_REQUIRED(port) - ); + PB_ARG_REQUIRED(port)); pupdevices_ColorDistanceSensor_obj_t *self = m_new_obj(pupdevices_ColorDistanceSensor_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; mp_int_t port_num = pb_type_enum_get_value(port, &pb_enum_type_Port); @@ -54,7 +53,7 @@ STATIC mp_obj_t pupdevices_ColorDistanceSensor_color(mp_obj_t self_in) { int32_t data[4]; pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__SPEC1, data); - switch(data[0]) { + switch (data[0]) { case 1: return pb_const_color_black; case 3: @@ -80,7 +79,7 @@ STATIC mp_obj_t pupdevices_ColorDistanceSensor_distance(mp_obj_t self_in) { pupdevices_ColorDistanceSensor_obj_t *self = MP_OBJ_TO_PTR(self_in); int32_t data[4]; pbdevice_get_values(self->pbdev, PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__SPEC1, data); - return mp_obj_new_int(data[1]*10); + return mp_obj_new_int(data[1] * 10); } MP_DEFINE_CONST_FUN_OBJ_1(pupdevices_ColorDistanceSensor_distance_obj, pupdevices_ColorDistanceSensor_distance); @@ -108,8 +107,7 @@ STATIC mp_obj_t pupdevices_ColorDistanceSensor_remote(size_t n_args, const mp_ob pupdevices_ColorDistanceSensor_obj_t, self, PB_ARG_REQUIRED(channel), PB_ARG_DEFAULT_NONE(button_1), - PB_ARG_DEFAULT_NONE(button_2) - ); + PB_ARG_DEFAULT_NONE(button_2)); // Get channel mp_int_t ch = mp_obj_get_int(channel); @@ -126,12 +124,12 @@ STATIC mp_obj_t pupdevices_ColorDistanceSensor_remote(size_t n_args, const mp_ob btn = b1 | b2; // Power Functions 1.0 "Combo Direct Mode" without checksum - int32_t message = ((btn & PBIO_BUTTON_LEFT_UP) != 0) << 0 | - ((btn & PBIO_BUTTON_LEFT_DOWN) != 0) << 1 | - ((btn & PBIO_BUTTON_RIGHT_UP) != 0) << 2 | - ((btn & PBIO_BUTTON_RIGHT_DOWN) != 0) << 3 | - (1) << 4 | - (ch - 1) << 8; + int32_t message = ((btn & PBIO_BUTTON_LEFT_UP) != 0) << 0 | + ((btn & PBIO_BUTTON_LEFT_DOWN) != 0) << 1 | + ((btn & PBIO_BUTTON_RIGHT_UP) != 0) << 2 | + ((btn & PBIO_BUTTON_RIGHT_DOWN) != 0) << 3 | + (1) << 4 | + (ch - 1) << 8; // Send the data to the device pbdevice_set_values(self->pbdev, PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__IR_TX, &message, 1); @@ -148,7 +146,7 @@ STATIC mp_obj_t pupdevices_ColorDistanceSensor_rgb(mp_obj_t self_in) { mp_obj_t rgb[3]; for (uint8_t col = 0; col < 3; col++) { - int16_t intensity = (data[col]*10)/44; + int16_t intensity = (data[col] * 10) / 44; rgb[col] = mp_obj_new_int(intensity < 100 ? intensity : 100); } return mp_obj_new_tuple(3, rgb); @@ -172,7 +170,7 @@ STATIC const mp_obj_type_t pupdevices_ColorDistanceSensor_type = { { &mp_type_type }, .name = MP_QSTR_ColorDistanceSensor, .make_new = pupdevices_ColorDistanceSensor_make_new, - .locals_dict = (mp_obj_dict_t*)&pupdevices_ColorDistanceSensor_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pupdevices_ColorDistanceSensor_locals_dict, }; // dir(pybricks.pupdevices) @@ -183,14 +181,13 @@ STATIC const mp_rom_map_elem_t pupdevices_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_ColorDistanceSensor), MP_ROM_PTR(&pupdevices_ColorDistanceSensor_type) }, }; -STATIC MP_DEFINE_CONST_DICT ( +STATIC MP_DEFINE_CONST_DICT( pb_module_pupdevices_globals, - pupdevices_globals_table -); + pupdevices_globals_table); const mp_obj_module_t pb_module_pupdevices = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_pupdevices_globals, + .globals = (mp_obj_dict_t *)&pb_module_pupdevices_globals, }; #endif // PYBRICKS_PY_PUPDEVICES diff --git a/extmod/modrobotics.c b/extmod/modrobotics.c index c5678c9f5..dc8b7835a 100644 --- a/extmod/modrobotics.c +++ b/extmod/modrobotics.c @@ -39,25 +39,24 @@ typedef struct _robotics_DriveBase_obj_t { } robotics_DriveBase_obj_t; // pybricks.robotics.DriveBase.__init__ -STATIC mp_obj_t robotics_DriveBase_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t robotics_DriveBase_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { PB_PARSE_ARGS_CLASS(n_args, n_kw, args, PB_ARG_REQUIRED(left_motor), PB_ARG_REQUIRED(right_motor), PB_ARG_REQUIRED(wheel_diameter), - PB_ARG_REQUIRED(axle_track) - ); + PB_ARG_REQUIRED(axle_track)); robotics_DriveBase_obj_t *self = m_new_obj(robotics_DriveBase_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; // Pointer to the Python (not pbio) Motor objects self->left = left_motor; self->right = right_motor; // Pointers to servos - pbio_servo_t *srv_left = ((motor_Motor_obj_t*) pb_obj_get_base_class_obj(self->left, &motor_Motor_type))->srv; - pbio_servo_t *srv_right = ((motor_Motor_obj_t*) pb_obj_get_base_class_obj(self->right, &motor_Motor_type))->srv; + pbio_servo_t *srv_left = ((motor_Motor_obj_t *)pb_obj_get_base_class_obj(self->left, &motor_Motor_type))->srv; + pbio_servo_t *srv_right = ((motor_Motor_obj_t *)pb_obj_get_base_class_obj(self->right, &motor_Motor_type))->srv; // A DriveBase must have two distinct motors if (srv_left == srv_right) { @@ -81,10 +80,10 @@ STATIC mp_obj_t robotics_DriveBase_make_new(const mp_obj_type_t *type, size_t n_ pbio_control_settings_get_limits(&self->db->control_distance.settings, &straight_speed_limit, &straight_acceleration_limit, &_); pbio_control_settings_get_limits(&self->db->control_heading.settings, &turn_rate_limit, &turn_acceleration_limit, &_); - self->straight_speed = straight_speed_limit/3; - self->straight_acceleration = straight_acceleration_limit/3; - self->turn_rate = turn_rate_limit/3; - self->turn_acceleration = turn_acceleration_limit/3; + self->straight_speed = straight_speed_limit / 3; + self->straight_acceleration = straight_acceleration_limit / 3; + self->turn_rate = turn_rate_limit / 3; + self->turn_acceleration = turn_acceleration_limit / 3; return MP_OBJ_FROM_PTR(self); } @@ -103,8 +102,7 @@ STATIC void wait_for_completion_drivebase(pbio_drivebase_t *db) { STATIC mp_obj_t robotics_DriveBase_straight(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, robotics_DriveBase_obj_t, self, - PB_ARG_REQUIRED(distance) - ); + PB_ARG_REQUIRED(distance)); int32_t distance_val = pb_obj_get_int(distance); pb_assert(pbio_drivebase_straight(self->db, distance_val, self->straight_speed, self->straight_acceleration)); @@ -119,8 +117,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_KW(robotics_DriveBase_straight_obj, 1, robotics_D STATIC mp_obj_t robotics_DriveBase_turn(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, robotics_DriveBase_obj_t, self, - PB_ARG_REQUIRED(angle) - ); + PB_ARG_REQUIRED(angle)); int32_t angle_val = pb_obj_get_int(angle); pb_assert(pbio_drivebase_turn(self->db, angle_val, self->turn_rate, self->turn_acceleration)); @@ -136,8 +133,7 @@ STATIC mp_obj_t robotics_DriveBase_drive(size_t n_args, const mp_obj_t *pos_args PB_PARSE_ARGS_METHOD(n_args, pos_args, kw_args, robotics_DriveBase_obj_t, self, PB_ARG_REQUIRED(speed), - PB_ARG_REQUIRED(turn_rate) - ); + PB_ARG_REQUIRED(turn_rate)); // Get wheel diameter and axle track dimensions int32_t speed_val = pb_obj_get_int(speed); @@ -215,15 +211,14 @@ STATIC mp_obj_t robotics_DriveBase_settings(size_t n_args, const mp_obj_t *pos_a PB_ARG_DEFAULT_NONE(straight_speed), PB_ARG_DEFAULT_NONE(straight_acceleration), PB_ARG_DEFAULT_NONE(turn_rate), - PB_ARG_DEFAULT_NONE(turn_acceleration) - ); + PB_ARG_DEFAULT_NONE(turn_acceleration)); // If all given values are none, return current values if (straight_speed == mp_const_none && straight_acceleration == mp_const_none && turn_rate == mp_const_none && turn_acceleration == mp_const_none - ) { + ) { mp_obj_t ret[4]; ret[0] = mp_obj_new_int(self->straight_speed); ret[1] = mp_obj_new_int(self->straight_acceleration); @@ -274,7 +269,7 @@ STATIC const mp_obj_type_t robotics_DriveBase_type = { { &mp_type_type }, .name = MP_QSTR_DriveBase, .make_new = robotics_DriveBase_make_new, - .locals_dict = (mp_obj_dict_t*)&robotics_DriveBase_locals_dict, + .locals_dict = (mp_obj_dict_t *)&robotics_DriveBase_locals_dict, }; // dir(pybricks.robotics) @@ -286,7 +281,7 @@ STATIC MP_DEFINE_CONST_DICT(pb_module_robotics_globals, robotics_globals_table); const mp_obj_module_t pb_module_robotics = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_robotics_globals, + .globals = (mp_obj_dict_t *)&pb_module_robotics_globals, }; #endif // PYBRICKS_PY_ROBOTICS diff --git a/extmod/modsys.c b/extmod/modsys.c index 556598ae8..70fad3a2f 100644 --- a/extmod/modsys.c +++ b/extmod/modsys.c @@ -34,8 +34,7 @@ STATIC MP_DEFINE_ATTRTUPLE( MP_ROM_INT(PYBRICKS_VERSION_MINOR), MP_ROM_INT(PYBRICKS_VERSION_MICRO), MP_ROM_PTR(&pybricks_version_level_obj), - MP_ROM_INT(PYBRICKS_VERSION_SERIAL) -); + MP_ROM_INT(PYBRICKS_VERSION_SERIAL)); // Standard sys.implementation fields + custom fields (with leading underscore). @@ -59,8 +58,7 @@ MP_DEFINE_ATTRTUPLE( MP_ROM_PTR(&git_tag_obj), MP_ROM_PTR(&build_date_obj), MP_ROM_INT(MPY_VERSION), - MP_ROM_PTR(&hub_name_obj) -); + MP_ROM_PTR(&hub_name_obj)); #else // MICROPY_PY_ATTRTUPLE diff --git a/extmod/modtools.c b/extmod/modtools.c index a74e062a8..0ecb48c41 100644 --- a/extmod/modtools.c +++ b/extmod/modtools.c @@ -9,8 +9,8 @@ STATIC mp_obj_t tools_wait(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { PB_PARSE_ARGS_FUNCTION(n_args, pos_args, kw_args, - PB_ARG_REQUIRED(time) - ); + PB_ARG_REQUIRED(time)); + mp_int_t duration = pb_obj_get_int(time); if (duration > 0) { mp_hal_delay_ms(duration); @@ -41,9 +41,8 @@ STATIC mp_obj_t tools_StopWatch_time(mp_obj_t self_in) { tools_StopWatch_obj_t *self = MP_OBJ_TO_PTR(self_in); return mp_obj_new_int_from_uint( self->running ? - mp_hal_ticks_ms()- self->time_start - self->time_spent_pausing : - self->time_stop - self->time_start - self->time_spent_pausing - ); + mp_hal_ticks_ms() - self->time_start - self->time_spent_pausing : + self->time_stop - self->time_start - self->time_spent_pausing); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(tools_StopWatch_time_obj, tools_StopWatch_time); @@ -67,10 +66,10 @@ STATIC mp_obj_t tools_StopWatch_resume(mp_obj_t self_in) { } STATIC MP_DEFINE_CONST_FUN_OBJ_1(tools_StopWatch_resume_obj, tools_StopWatch_resume); -STATIC mp_obj_t tools_StopWatch_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args ) { +STATIC mp_obj_t tools_StopWatch_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { // Initialize self tools_StopWatch_obj_t *self = m_new_obj(tools_StopWatch_obj_t); - self->base.type = (mp_obj_type_t*) type; + self->base.type = (mp_obj_type_t *)type; tools_StopWatch_reset(self); tools_StopWatch_resume(self); return MP_OBJ_FROM_PTR(self); @@ -91,7 +90,7 @@ STATIC const mp_obj_type_t tools_StopWatch_type = { { &mp_type_type }, .name = MP_QSTR_StopWatch, .make_new = tools_StopWatch_make_new, - .locals_dict = (mp_obj_dict_t*)&tools_StopWatch_locals_dict, + .locals_dict = (mp_obj_dict_t *)&tools_StopWatch_locals_dict, }; /* @@ -107,5 +106,5 @@ STATIC MP_DEFINE_CONST_DICT(pb_module_tools_globals, tools_globals_table); const mp_obj_module_t pb_module_tools = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pb_module_tools_globals, + .globals = (mp_obj_dict_t *)&pb_module_tools_globals, }; diff --git a/extmod/pbdevice.h b/extmod/pbdevice.h index 172acf8f5..209fe0d0c 100644 --- a/extmod/pbdevice.h +++ b/extmod/pbdevice.h @@ -127,7 +127,7 @@ enum { PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__AMBI = 4, // read 1x int8_t PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__COL_O = 5, // writ 1x int8_t PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__RGB_I = 6, // read 3x int16_t - PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__IR_TX = 7, // writ 1x int16_t + PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__IR_TX = 7, // writ 1x int16_t PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__SPEC1 = 8, // rrwr 4x int8_t PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__DEBUG = 9, // ?? 2x int16_t PBIO_IODEV_MODE_PUP_COLOR_DISTANCE_SENSOR__CALIB = 10, // ?? 8x int16_t diff --git a/lib/pbio/drv/adc/adc_stm32_hal.c b/lib/pbio/drv/adc/adc_stm32_hal.c index 6431fa46a..a374e1b6c 100644 --- a/lib/pbio/drv/adc/adc_stm32_hal.c +++ b/lib/pbio/drv/adc/adc_stm32_hal.c @@ -59,7 +59,7 @@ void pbdrv_adc_stm32_hal_handle_irq() { HAL_DMA_IRQHandler(&pbdrv_adc_hdma); } -void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) { +void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc) { process_poll(&pbdrv_adc_process); } @@ -105,11 +105,11 @@ PROCESS_THREAD(pbdrv_adc_process, ev, data) { // using DMA pbdrv_adc_hdma.Instance = PBDRV_CONFIG_ADC_STM32_HAL_DMA_INSTANCE; -#ifdef STM32L4 + #ifdef STM32L4 pbdrv_adc_hdma.Init.Request = PBDRV_CONFIG_ADC_STM32_HAL_DMA_REQUEST; -#else + #else pbdrv_adc_hdma.Init.Channel = PBDRV_CONFIG_ADC_STM32_HAL_DMA_CHANNEL; -#endif + #endif pbdrv_adc_hdma.Init.Direction = DMA_PERIPH_TO_MEMORY; pbdrv_adc_hdma.Init.PeriphInc = DMA_PINC_DISABLE; pbdrv_adc_hdma.Init.MemInc = DMA_MINC_ENABLE; @@ -136,9 +136,9 @@ PROCESS_THREAD(pbdrv_adc_process, ev, data) { HAL_ADC_Init(&pbdrv_adc_hadc); -#ifdef STM32L4 + #ifdef STM32L4 HAL_ADCEx_Calibration_Start(&pbdrv_adc_hadc, ADC_SINGLE_ENDED); -#endif + #endif __HAL_LINKDMA(&pbdrv_adc_hadc, DMA_Handle, pbdrv_adc_hdma); HAL_NVIC_SetPriority(PBDRV_CONFIG_ADC_STM32_HAL_DMA_IRQ, 1, 0); diff --git a/lib/pbio/drv/adc/adc_stm32f0.c b/lib/pbio/drv/adc/adc_stm32f0.c index bb0654116..7badb32a3 100644 --- a/lib/pbio/drv/adc/adc_stm32f0.c +++ b/lib/pbio/drv/adc/adc_stm32f0.c @@ -27,7 +27,8 @@ static void pbdrv_adc_calibrate() { ADC1->CR |= ADC_CR_ADCAL; - while (ADC1->CR & ADC_CR_ADCAL) { } + while (ADC1->CR & ADC_CR_ADCAL) { + } } static void pbdrv_adc_init() { @@ -47,7 +48,7 @@ static void pbdrv_adc_init() { do { ADC1->CR |= ADC_CR_ADEN; - } while (!(ADC1->ISR & ADC_ISR_ADRDY)); + } while (!(ADC1->ISR & ADC_ISR_ADRDY)); // set sampling time to 239.5 ADC clock cycles (longest possible) ADC1->SMPR = (ADC1->SMPR & ADC_SMPR_SMP_Msk) | (7 << ADC_SMPR_SMP_Pos); @@ -68,7 +69,8 @@ pbio_error_t pbdrv_adc_get_ch(uint8_t ch, uint16_t *value) { ADC1->CHSELR = 1 << ch; ADC1->CR |= ADC_CR_ADSTART; - while (!(ADC1->ISR & ADC_ISR_EOC)) { } + while (!(ADC1->ISR & ADC_ISR_EOC)) { + } *value = ADC1->DR; @@ -79,19 +81,21 @@ pbio_error_t pbdrv_adc_get_ch(uint8_t ch, uint16_t *value) { static void pbdrv_adc_exit() { // REVISIT: do we need timeouts here? ADC1->CR |= ADC_CR_ADSTP; - while (ADC1->CR & ADC_CR_ADSTP) { } + while (ADC1->CR & ADC_CR_ADSTP) { + } ADC1->CR |= ADC_CR_ADDIS; - while (ADC1->CR & ADC_CR_ADEN) { } + while (ADC1->CR & ADC_CR_ADEN) { + } } #endif PROCESS_THREAD(pbdrv_adc_process, ev, data) { // TODO: use DMA for background updates and add filtering // PROCESS_POLLHANDLER(pbdrv_adc_poll()); -#if PBIO_CONFIG_ENABLE_DEINIT + #if PBIO_CONFIG_ENABLE_DEINIT PROCESS_EXITHANDLER(pbdrv_adc_exit()); -#endif + #endif PROCESS_BEGIN(); diff --git a/lib/pbio/drv/battery/battery_adc.c b/lib/pbio/drv/battery/battery_adc.c index 0d8c8e434..e1098cbf8 100644 --- a/lib/pbio/drv/battery/battery_adc.c +++ b/lib/pbio/drv/battery/battery_adc.c @@ -28,7 +28,7 @@ pbio_error_t pbdrv_battery_get_voltage_now(uint16_t *value) { // REVISIT: do we want to take into account shunt resistor voltage drop // like on EV3? Probably only makes a difference of ~10mV at the most. *value = raw * PBDRV_CONFIG_BATTERY_ADC_VOLTAGE_SCALED_MAX / - PBDRV_CONFIG_BATTERY_ADC_VOLTAGE_RAW_MAX; + PBDRV_CONFIG_BATTERY_ADC_VOLTAGE_RAW_MAX; return PBIO_SUCCESS; } @@ -45,7 +45,7 @@ pbio_error_t pbdrv_battery_get_current_now(uint16_t *value) { } *value = raw * PBDRV_CONFIG_BATTERY_ADC_CURRENT_SCALED_MAX / - PBDRV_CONFIG_BATTERY_ADC_CURRENT_RAW_MAX; + PBDRV_CONFIG_BATTERY_ADC_CURRENT_RAW_MAX; return PBIO_SUCCESS; } diff --git a/lib/pbio/drv/button/button_adc.c b/lib/pbio/drv/button/button_adc.c index d53801bcc..94d101097 100644 --- a/lib/pbio/drv/button/button_adc.c +++ b/lib/pbio/drv/button/button_adc.c @@ -63,17 +63,13 @@ pbio_error_t pbdrv_button_is_pressed(pbio_button_flags_t *pressed) { if (value > 3394) { // not a button - } - else if (value > 3009) { + } else if (value > 3009) { *pressed |= PBIO_BUTTON_CENTER; - } - else if (value > 2538) { + } else if (value > 2538) { // not a button - } - else if (value > 2141) { + } else if (value > 2141) { *pressed |= PBIO_BUTTON_CENTER; - } - else { + } else { // hardware failure? return PBIO_ERROR_IO; } @@ -85,34 +81,26 @@ pbio_error_t pbdrv_button_is_pressed(pbio_button_flags_t *pressed) { if (value > 3872) { // no buttons pressed - } - else if (value > 3394) { + } else if (value > 3394) { *pressed |= PBIO_BUTTON_RIGHT_UP; // Bluetooth - } - else if (value > 3009) { + } else if (value > 3009) { *pressed |= PBIO_BUTTON_RIGHT; - } - else if (value > 2755) { + } else if (value > 2755) { *pressed |= PBIO_BUTTON_RIGHT_UP; // Bluetooth *pressed |= PBIO_BUTTON_RIGHT; - } - else if (value > 2538) { + } else if (value > 2538) { *pressed |= PBIO_BUTTON_LEFT; - } - else if (value > 2327) { + } else if (value > 2327) { *pressed |= PBIO_BUTTON_RIGHT_UP; // Bluetooth *pressed |= PBIO_BUTTON_LEFT; - } - else if (value > 2141) { + } else if (value > 2141) { *pressed |= PBIO_BUTTON_RIGHT; *pressed |= PBIO_BUTTON_LEFT; - } - else if (value > 1969) { + } else if (value > 1969) { *pressed |= PBIO_BUTTON_RIGHT_UP; // Bluetooth *pressed |= PBIO_BUTTON_RIGHT; *pressed |= PBIO_BUTTON_LEFT; - } - else { + } else { // hardware failure? return PBIO_ERROR_IO; } diff --git a/lib/pbio/drv/button/button_gpio.c b/lib/pbio/drv/button/button_gpio.c index 86fac77ae..7b676c23c 100644 --- a/lib/pbio/drv/button/button_gpio.c +++ b/lib/pbio/drv/button/button_gpio.c @@ -23,7 +23,8 @@ void _pbdrv_button_init(void) { } #if PBIO_CONFIG_ENABLE_DEINIT -void _pbdrv_button_deinit(void) { } +void _pbdrv_button_deinit(void) { +} #endif pbio_error_t pbdrv_button_is_pressed(pbio_button_flags_t *pressed) { diff --git a/lib/pbio/drv/button/button_linux_ev3.c b/lib/pbio/drv/button/button_linux_ev3.c index c5a38807f..052afd22c 100644 --- a/lib/pbio/drv/button/button_linux_ev3.c +++ b/lib/pbio/drv/button/button_linux_ev3.c @@ -28,11 +28,11 @@ void _pbdrv_button_init(void) { void _pbdrv_button_deinit(void) { close(f_btn); f_btn = -1; - } +} #endif static bool check(uint8_t *buffer, uint8_t key) { - return buffer[key>>3] & (1 << (key % 8)); + return buffer[key >> 3] & (1 << (key % 8)); } pbio_error_t pbdrv_button_is_pressed(pbio_button_flags_t *pressed) { diff --git a/lib/pbio/drv/city_hub/light.c b/lib/pbio/drv/city_hub/light.c index 3da08bd8b..187eac336 100644 --- a/lib/pbio/drv/city_hub/light.c +++ b/lib/pbio/drv/city_hub/light.c @@ -86,7 +86,7 @@ pbio_error_t pbdrv_light_set_rgb(pbio_port_t port, uint8_t r, uint8_t g, uint8_t } pbio_error_t pbdrv_light_get_rgb_for_color(pbio_port_t port, pbio_light_color_t color, - uint8_t *r, uint8_t *g, uint8_t *b) { + uint8_t *r, uint8_t *g, uint8_t *b) { if (port == PBIO_PORT_B || port == PBIO_PORT_A) { // TODO: check for Powered UP Lights connected to ports C/D return PBIO_ERROR_NO_DEV; @@ -97,46 +97,46 @@ pbio_error_t pbdrv_light_get_rgb_for_color(pbio_port_t port, pbio_light_color_t } switch (color) { - case PBIO_LIGHT_COLOR_WHITE: - *r = 255; - *g = 140; - *b = 60; - break; - case PBIO_LIGHT_COLOR_RED: - *r = 255; - *g = 0; - *b = 0; - break; - case PBIO_LIGHT_COLOR_ORANGE: - *r = 255; - *g = 25; - *b = 0; - break; - case PBIO_LIGHT_COLOR_YELLOW: - *r = 255; - *g = 70; - *b = 0; - break; - case PBIO_LIGHT_COLOR_GREEN: - *r = 0; - *g = 200; - *b = 0; - break; - case PBIO_LIGHT_COLOR_BLUE: - *r = 0; - *g = 0; - *b = 255; - break; - case PBIO_LIGHT_COLOR_PURPLE: - *r = 220; - *g = 0; - *b = 120; - break; - default: - *r = 0; - *g = 0; - *b = 0; - break; + case PBIO_LIGHT_COLOR_WHITE: + *r = 255; + *g = 140; + *b = 60; + break; + case PBIO_LIGHT_COLOR_RED: + *r = 255; + *g = 0; + *b = 0; + break; + case PBIO_LIGHT_COLOR_ORANGE: + *r = 255; + *g = 25; + *b = 0; + break; + case PBIO_LIGHT_COLOR_YELLOW: + *r = 255; + *g = 70; + *b = 0; + break; + case PBIO_LIGHT_COLOR_GREEN: + *r = 0; + *g = 200; + *b = 0; + break; + case PBIO_LIGHT_COLOR_BLUE: + *r = 0; + *g = 0; + *b = 255; + break; + case PBIO_LIGHT_COLOR_PURPLE: + *r = 220; + *g = 0; + *b = 120; + break; + default: + *r = 0; + *g = 0; + *b = 0; + break; } return PBIO_SUCCESS; diff --git a/lib/pbio/drv/city_hub/motor.c b/lib/pbio/drv/city_hub/motor.c index b90de6856..9f034b2ad 100644 --- a/lib/pbio/drv/city_hub/motor.c +++ b/lib/pbio/drv/city_hub/motor.c @@ -88,20 +88,20 @@ pbio_error_t pbdrv_motor_coast(pbio_port_t port) { // set both port pins 1 and 2 to output low switch (port) { - case PBIO_PORT_B: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); - GPIOC->BRR = GPIO_BRR_BR_6; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOC->BRR = GPIO_BRR_BR_8; - break; - case PBIO_PORT_A: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); - GPIOC->BRR = GPIO_BRR_BR_7; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOC->BRR = GPIO_BRR_BR_9; - break; - default: - return PBIO_ERROR_INVALID_PORT; + case PBIO_PORT_B: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); + GPIOC->BRR = GPIO_BRR_BR_6; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOC->BRR = GPIO_BRR_BR_8; + break; + case PBIO_PORT_A: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); + GPIOC->BRR = GPIO_BRR_BR_7; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOC->BRR = GPIO_BRR_BR_9; + break; + default: + return PBIO_ERROR_INVALID_PORT; } return PBIO_SUCCESS; @@ -110,60 +110,60 @@ pbio_error_t pbdrv_motor_coast(pbio_port_t port) { static void pbdrv_motor_brake(pbio_port_t port) { // set both port pins 1 and 2 to output high switch (port) { - case PBIO_PORT_B: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_6; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_8; - break; - case PBIO_PORT_A: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_7; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_9; - break; - default: - break; + case PBIO_PORT_B: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_6; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_8; + break; + case PBIO_PORT_A: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_7; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_9; + break; + default: + break; } } static void pbdrv_motor_run_fwd(pbio_port_t port, int16_t duty_cycle) { // one pin as out, high and the other as PWM switch (port) { - case PBIO_PORT_B: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_6; - TIM3->CCR3 = 10000 - duty_cycle; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (2 << GPIO_MODER_MODER8_Pos); - break; - case PBIO_PORT_A: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_9; - TIM3->CCR2 = 10000 - duty_cycle; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (2 << GPIO_MODER_MODER7_Pos); - break; - default: - break; + case PBIO_PORT_B: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_6; + TIM3->CCR3 = 10000 - duty_cycle; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (2 << GPIO_MODER_MODER8_Pos); + break; + case PBIO_PORT_A: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_9; + TIM3->CCR2 = 10000 - duty_cycle; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (2 << GPIO_MODER_MODER7_Pos); + break; + default: + break; } } static void pbdrv_motor_run_rev(pbio_port_t port, int16_t duty_cycle) { // one pin as out, high and the other as PWM switch (port) { - case PBIO_PORT_B: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_8; - TIM3->CCR1 = 10000 + duty_cycle; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (2 << GPIO_MODER_MODER6_Pos); - break; - case PBIO_PORT_A: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_7; - TIM3->CCR4 = 10000 + duty_cycle; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (2 << GPIO_MODER_MODER9_Pos); - break; - default: - break; + case PBIO_PORT_B: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_8; + TIM3->CCR1 = 10000 + duty_cycle; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (2 << GPIO_MODER_MODER6_Pos); + break; + case PBIO_PORT_A: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_7; + TIM3->CCR4 = 10000 + duty_cycle; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (2 << GPIO_MODER_MODER9_Pos); + break; + default: + break; } } diff --git a/lib/pbio/drv/counter/counter.h b/lib/pbio/drv/counter/counter.h index feb7706f7..ef19ab98b 100644 --- a/lib/pbio/drv/counter/counter.h +++ b/lib/pbio/drv/counter/counter.h @@ -27,8 +27,12 @@ typedef struct { pbio_error_t pbdrv_counter_register(uint8_t id, pbdrv_counter_dev_t *dev); pbio_error_t pbdrv_counter_unregister(pbdrv_counter_dev_t *dev); #else // PBDRV_CONFIG_COUNTER -static inline pbio_error_t pbdrv_counter_register(uint8_t id, pbdrv_counter_dev_t *dev) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbdrv_counter_unregister(pbdrv_counter_dev_t *dev) { return PBIO_ERROR_NOT_SUPPORTED; } +static inline pbio_error_t pbdrv_counter_register(uint8_t id, pbdrv_counter_dev_t *dev) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbdrv_counter_unregister(pbdrv_counter_dev_t *dev) { + return PBIO_ERROR_NOT_SUPPORTED; +} #endif // PBDRV_CONFIG_COUNTER #endif // _PBDRV_COUNTER_COUNTER_H_ diff --git a/lib/pbio/drv/counter/counter_core.c b/lib/pbio/drv/counter/counter_core.c index 3b7c27517..f1eab831e 100644 --- a/lib/pbio/drv/counter/counter_core.c +++ b/lib/pbio/drv/counter/counter_core.c @@ -96,15 +96,15 @@ pbio_error_t pbdrv_counter_get_rate(pbdrv_counter_dev_t *dev, int32_t *rate) { } static void pbdrv_counter_process_exit() { -#if PBDRV_CONFIG_COUNTER_NXT + #if PBDRV_CONFIG_COUNTER_NXT pbdrv_counter_nxt_drv.exit(); -#endif -#if PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO + #endif + #if PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO pbdrv_counter_ev3dev_stretch_iio_drv.exit(); -#endif -#if PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC + #endif + #if PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC pbdrv_counter_stm32f0_gpio_quad_enc_drv.exit(); -#endif + #endif } PROCESS_THREAD(pbdrv_counter_process, ev, data) { @@ -112,15 +112,15 @@ PROCESS_THREAD(pbdrv_counter_process, ev, data) { PROCESS_BEGIN(); -#if PBDRV_CONFIG_COUNTER_NXT + #if PBDRV_CONFIG_COUNTER_NXT pbdrv_counter_nxt_drv.init(); -#endif -#if PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO + #endif + #if PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO pbdrv_counter_ev3dev_stretch_iio_drv.init(); -#endif -#if PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC + #endif + #if PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC pbdrv_counter_stm32f0_gpio_quad_enc_drv.init(); -#endif + #endif while (true) { PROCESS_WAIT_EVENT(); diff --git a/lib/pbio/drv/counter/counter_ev3dev_stretch_iio.c b/lib/pbio/drv/counter/counter_ev3dev_stretch_iio.c index d40cb22a3..621ce4c6a 100644 --- a/lib/pbio/drv/counter/counter_ev3dev_stretch_iio.c +++ b/lib/pbio/drv/counter/counter_ev3dev_stretch_iio.c @@ -167,8 +167,8 @@ static pbio_error_t counter_ev3dev_stretch_iio_exit() { } const pbdrv_counter_drv_t pbdrv_counter_ev3dev_stretch_iio_drv = { - .init = counter_ev3dev_stretch_iio_init, - .exit = counter_ev3dev_stretch_iio_exit, + .init = counter_ev3dev_stretch_iio_init, + .exit = counter_ev3dev_stretch_iio_exit, }; #endif // PBDRV_CONFIG_COUNTER_EV3DEV_STRETCH_IIO diff --git a/lib/pbio/drv/counter/counter_nxt.c b/lib/pbio/drv/counter/counter_nxt.c index cbd954b0a..9137d0e8b 100644 --- a/lib/pbio/drv/counter/counter_nxt.c +++ b/lib/pbio/drv/counter/counter_nxt.c @@ -64,8 +64,8 @@ static pbio_error_t counter_nxt_exit() { } const pbdrv_counter_drv_t pbdrv_counter_nxt_drv = { - .init = counter_nxt_init, - .exit = counter_nxt_exit, + .init = counter_nxt_init, + .exit = counter_nxt_exit, }; #endif // PBDRV_CONFIG_COUNTER_NXT diff --git a/lib/pbio/drv/counter/counter_stm32f0_gpio_quad_enc.c b/lib/pbio/drv/counter/counter_stm32f0_gpio_quad_enc.c index b1a4e1add..c929c654b 100644 --- a/lib/pbio/drv/counter/counter_stm32f0_gpio_quad_enc.c +++ b/lib/pbio/drv/counter/counter_stm32f0_gpio_quad_enc.c @@ -64,7 +64,7 @@ static pbio_error_t pbdrv_counter_stm32f0_gpio_quad_enc_get_rate(pbdrv_counter_d return PBIO_SUCCESS; } - while (x++ < RING_BUF_SIZE) { + while (x++ < RING_BUF_SIZE) { tail = (head - x) & (RING_BUF_SIZE - 1); tail_count = data->counts[tail]; @@ -97,11 +97,10 @@ static pbio_error_t pbdrv_counter_stm32f0_gpio_quad_enc_get_rate(pbdrv_counter_d } static void pbdrv_motor_tacho_update_count(private_data_t *data, - bool int_pin_state, bool dir_pin_state, uint16_t timestamp) { + bool int_pin_state, bool dir_pin_state, uint16_t timestamp) { if (int_pin_state ^ dir_pin_state) { data->count--; - } - else { + } else { data->count++; } @@ -211,8 +210,8 @@ static pbio_error_t counter_stm32f0_gpio_quad_enc_exit() { } const pbdrv_counter_drv_t pbdrv_counter_stm32f0_gpio_quad_enc_drv = { - .init = counter_stm32f0_gpio_quad_enc_init, - .exit = counter_stm32f0_gpio_quad_enc_exit, + .init = counter_stm32f0_gpio_quad_enc_init, + .exit = counter_stm32f0_gpio_quad_enc_exit, }; #endif // PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC diff --git a/lib/pbio/drv/counter/counter_stm32f0_gpio_quad_enc.h b/lib/pbio/drv/counter/counter_stm32f0_gpio_quad_enc.h index 93f373b3a..9984de970 100644 --- a/lib/pbio/drv/counter/counter_stm32f0_gpio_quad_enc.h +++ b/lib/pbio/drv/counter/counter_stm32f0_gpio_quad_enc.h @@ -23,7 +23,7 @@ typedef struct { // defined in platform/*/platform.c extern const pbdrv_counter_stm32f0_gpio_quad_enc_platform_data_t -pbdrv_counter_stm32f0_gpio_quad_enc_platform_data[PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC_NUM_DEV]; + pbdrv_counter_stm32f0_gpio_quad_enc_platform_data[PBDRV_CONFIG_COUNTER_STM32F0_GPIO_QUAD_ENC_NUM_DEV]; // defined in counter_stm32f0_gpio_quad_enc.c extern const pbdrv_counter_drv_t pbdrv_counter_stm32f0_gpio_quad_enc_drv; diff --git a/lib/pbio/drv/cplus_hub/bluetooth.c b/lib/pbio/drv/cplus_hub/bluetooth.c index cd89c36b1..109c104bb 100644 --- a/lib/pbio/drv/cplus_hub/bluetooth.c +++ b/lib/pbio/drv/cplus_hub/bluetooth.c @@ -38,12 +38,12 @@ #if DEBUG #include #define DBG(fmt, ...) { \ - char dbg[64]; \ - snprintf(dbg, 64, fmt "\r\n", ##__VA_ARGS__); \ - for (char *d = dbg; *d; d++) { \ - while (!(LPUART1->ISR & USART_ISR_TXE)) { } \ - LPUART1->TDR = *d; \ - } \ + char dbg[64]; \ + snprintf(dbg, 64, fmt "\r\n",##__VA_ARGS__); \ + for (char *d = dbg; *d; d++) { \ + while (!(LPUART1->ISR & USART_ISR_TXE)) { } \ + LPUART1->TDR = *d; \ + } \ } #else #define DBG(...) @@ -321,12 +321,11 @@ static void handle_event(uint8_t *packet) { UNUSED(size); switch (event) { - case HCI_COMMAND_COMPLETE_EVENT: - hci_command_complete = true; - break; + case HCI_COMMAND_COMPLETE_EVENT: + hci_command_complete = true; + break; - case HCI_LE_EXT_EVENT: - { + case HCI_LE_EXT_EVENT: { uint16_t event_code = (data[1] << 8) | data[0]; HCI_StatusCodes_t status = data[2]; uint16_t connection_handle = (data[4] << 8) | data[3]; @@ -336,16 +335,14 @@ static void handle_event(uint8_t *packet) { UNUSED(pdu_len); switch (event_code) { - case ATT_EVENT_EXCHANGE_MTU_REQ: - { + case ATT_EVENT_EXCHANGE_MTU_REQ: { attExchangeMTURsp_t rsp; rsp.serverRxMTU = 158; ATT_ExchangeMTURsp(connection_handle, &rsp); } break; - case ATT_EVENT_READ_BY_TYPE_REQ: - { + case ATT_EVENT_READ_BY_TYPE_REQ: { uint16_t start_handle = (data[7] << 8) | data[6]; uint16_t end_handle = (data[9] << 8) | data[8]; uint16_t type = (data[11] << 8) | data[10]; @@ -354,132 +351,124 @@ static void handle_event(uint8_t *packet) { DBG("s %04X t %04X", start_handle, type); switch (type) { - case GATT_CHARACTER_UUID: - if (start_handle <= gatt_service_handle) { - uint16_t handle = gatt_service_handle + 1; - attReadByTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = handle & 0xFF; - buf[1] = (handle >> 8) & 0xFF; - buf[2] = GATT_PROP_INDICATE; - buf[3] = ++handle & 0xFF; - buf[4] = (handle >> 8) & 0xFF; - buf[5] = SERVICE_CHANGED_UUID & 0xFF; - buf[6] = (SERVICE_CHANGED_UUID >> 8) & 0xFF; - - rsp.pDataList = buf; - rsp.dataLen = 7; - ATT_ReadByTypeRsp(connection_handle, &rsp); - } - else if (start_handle <= gap_service_handle) { - uint16_t handle = gap_service_handle + 1; - attReadByTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = handle & 0xFF; - buf[1] = (handle >> 8) & 0xFF; - buf[2] = GATT_PROP_READ; - buf[3] = ++handle & 0xFF; - buf[4] = (handle >> 8) & 0xFF; - buf[5] = DEVICE_NAME_UUID & 0xFF; - buf[6] = (DEVICE_NAME_UUID >> 8) & 0xFF; - - rsp.pDataList = buf; - rsp.dataLen = 7; - ATT_ReadByTypeRsp(connection_handle, &rsp); - } - else if (start_handle <= pybricks_service_handle) { - uint16_t handle = pybricks_service_handle + 1; - attReadByTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = handle & 0xFF; - buf[1] = (handle >> 8) & 0xFF; - buf[2] = GATT_PROP_READ | GATT_PROP_WRITE | - GATT_PROP_WRITE_NO_RSP | GATT_PROP_NOTIFY; - buf[3] = ++handle & 0xFF; - buf[4] = (handle >> 8) & 0xFF; - memcpy(&buf[5], pybricks_char_uuid, 16); - - rsp.pDataList = buf; - rsp.dataLen = 21; - ATT_ReadByTypeRsp(connection_handle, &rsp); - } - else if (start_handle <= uart_service_handle) { - uint16_t handle = uart_service_handle + 1; - attReadByTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = handle & 0xFF; - buf[1] = (handle >> 8) & 0xFF; - buf[2] = GATT_PROP_WRITE | GATT_PROP_WRITE_NO_RSP; - buf[3] = ++handle & 0xFF; - buf[4] = (handle >> 8) & 0xFF; - memcpy(&buf[5], nrf_uart_rx_char_uuid, 16); - - rsp.pDataList = buf; - rsp.dataLen = 21; - ATT_ReadByTypeRsp(connection_handle, &rsp); - } - else if (start_handle <= uart_service_handle + 2) { - uint16_t handle = uart_service_handle + 3; - attReadByTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = handle & 0xFF; - buf[1] = (handle >> 8) & 0xFF; - buf[2] = GATT_PROP_NOTIFY; - buf[3] = ++handle & 0xFF; - buf[4] = (handle >> 8) & 0xFF; - memcpy(&buf[5], nrf_uart_tx_char_uuid, 16); - - rsp.pDataList = buf; - rsp.dataLen = 21; - ATT_ReadByTypeRsp(connection_handle, &rsp); - } - else { - attErrorRsp_t rsp; - - rsp.reqOpcode = ATT_READ_BY_TYPE_REQ; - rsp.handle = start_handle; - rsp.errCode = ATT_ERR_INVALID_VALUE; - ATT_ErrorRsp(connection_handle, &rsp); - } - break; - default: - DBG("unhandled read by type req: %04X", type); - break; + case GATT_CHARACTER_UUID: + if (start_handle <= gatt_service_handle) { + uint16_t handle = gatt_service_handle + 1; + attReadByTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = handle & 0xFF; + buf[1] = (handle >> 8) & 0xFF; + buf[2] = GATT_PROP_INDICATE; + buf[3] = ++handle & 0xFF; + buf[4] = (handle >> 8) & 0xFF; + buf[5] = SERVICE_CHANGED_UUID & 0xFF; + buf[6] = (SERVICE_CHANGED_UUID >> 8) & 0xFF; + + rsp.pDataList = buf; + rsp.dataLen = 7; + ATT_ReadByTypeRsp(connection_handle, &rsp); + } else if (start_handle <= gap_service_handle) { + uint16_t handle = gap_service_handle + 1; + attReadByTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = handle & 0xFF; + buf[1] = (handle >> 8) & 0xFF; + buf[2] = GATT_PROP_READ; + buf[3] = ++handle & 0xFF; + buf[4] = (handle >> 8) & 0xFF; + buf[5] = DEVICE_NAME_UUID & 0xFF; + buf[6] = (DEVICE_NAME_UUID >> 8) & 0xFF; + + rsp.pDataList = buf; + rsp.dataLen = 7; + ATT_ReadByTypeRsp(connection_handle, &rsp); + } else if (start_handle <= pybricks_service_handle) { + uint16_t handle = pybricks_service_handle + 1; + attReadByTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = handle & 0xFF; + buf[1] = (handle >> 8) & 0xFF; + buf[2] = GATT_PROP_READ | GATT_PROP_WRITE | + GATT_PROP_WRITE_NO_RSP | GATT_PROP_NOTIFY; + buf[3] = ++handle & 0xFF; + buf[4] = (handle >> 8) & 0xFF; + memcpy(&buf[5], pybricks_char_uuid, 16); + + rsp.pDataList = buf; + rsp.dataLen = 21; + ATT_ReadByTypeRsp(connection_handle, &rsp); + } else if (start_handle <= uart_service_handle) { + uint16_t handle = uart_service_handle + 1; + attReadByTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = handle & 0xFF; + buf[1] = (handle >> 8) & 0xFF; + buf[2] = GATT_PROP_WRITE | GATT_PROP_WRITE_NO_RSP; + buf[3] = ++handle & 0xFF; + buf[4] = (handle >> 8) & 0xFF; + memcpy(&buf[5], nrf_uart_rx_char_uuid, 16); + + rsp.pDataList = buf; + rsp.dataLen = 21; + ATT_ReadByTypeRsp(connection_handle, &rsp); + } else if (start_handle <= uart_service_handle + 2) { + uint16_t handle = uart_service_handle + 3; + attReadByTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = handle & 0xFF; + buf[1] = (handle >> 8) & 0xFF; + buf[2] = GATT_PROP_NOTIFY; + buf[3] = ++handle & 0xFF; + buf[4] = (handle >> 8) & 0xFF; + memcpy(&buf[5], nrf_uart_tx_char_uuid, 16); + + rsp.pDataList = buf; + rsp.dataLen = 21; + ATT_ReadByTypeRsp(connection_handle, &rsp); + } else { + attErrorRsp_t rsp; + + rsp.reqOpcode = ATT_READ_BY_TYPE_REQ; + rsp.handle = start_handle; + rsp.errCode = ATT_ERR_INVALID_VALUE; + ATT_ErrorRsp(connection_handle, &rsp); + } + break; + default: + DBG("unhandled read by type req: %04X", type); + break; } } break; - case ATT_EVENT_READ_REQ: - { + case ATT_EVENT_READ_REQ: { uint16_t handle = (data[7] << 8) | data[6]; if (handle == gap_service_handle + 2) { attReadRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-1]; + uint8_t buf[ATT_MTU_SIZE - 1]; memcpy(&buf[0], DEV_NAME, sizeof(DEV_NAME)); rsp.len = sizeof(DEV_NAME) - 1; rsp.pValue = buf; ATT_ReadRsp(connection_handle, &rsp); - } - else if (handle == gap_service_handle + 4) { + } else if (handle == gap_service_handle + 4) { attReadRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-1]; + uint8_t buf[ATT_MTU_SIZE - 1]; buf[0] = GAP_APPEARE_UNKNOWN & 0xFF; buf[1] = (GAP_APPEARE_UNKNOWN >> 8) & 0xFF; rsp.len = 2; rsp.pValue = buf; ATT_ReadRsp(connection_handle, &rsp); - } - else if (handle == gap_service_handle + 6) { + } else if (handle == gap_service_handle + 6) { attReadRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-1]; + uint8_t buf[ATT_MTU_SIZE - 1]; // FIXME: what should these values be? buf[0] = 0xFFFF & 0xFF; // intervalMin @@ -493,25 +482,22 @@ static void handle_event(uint8_t *packet) { rsp.len = 8; rsp.pValue = buf; ATT_ReadRsp(connection_handle, &rsp); - } - else if (handle == uart_tx_char_handle + 1) { + } else if (handle == uart_tx_char_handle + 1) { attReadRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-1]; + uint8_t buf[ATT_MTU_SIZE - 1]; buf[0] = uart_tx_notify_en; buf[1] = 0; rsp.len = 2; rsp.pValue = buf; ATT_ReadRsp(connection_handle, &rsp); - } - else { + } else { DBG("unhandled read req: %04X", handle); } } break; - case ATT_EVENT_READ_BY_GRP_TYPE_REQ: - { + case ATT_EVENT_READ_BY_GRP_TYPE_REQ: { uint16_t start_handle = (data[7] << 8) | data[6]; uint16_t end_handle = (data[9] << 8) | data[8]; uint16_t group_type = (data[11] << 8) | data[10]; @@ -520,107 +506,99 @@ static void handle_event(uint8_t *packet) { DBG("s %04X g %04X", start_handle, group_type); switch (group_type) { - case GATT_PRIMARY_SERVICE_UUID: - if (start_handle == gatt_service_handle) { - attReadByGrpTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = gatt_service_handle & 0xFF; - buf[1] = (gatt_service_handle >> 8) & 0xFF; - buf[2] = gatt_service_end_handle & 0xFF; - buf[3] = (gatt_service_end_handle >> 8) & 0xFF; - buf[4] = GATT_SERVICE_UUID & 0xFF; - buf[5] = (GATT_SERVICE_UUID >> 8) & 0xFF; - - rsp.pDataList = buf; - rsp.dataLen = 6; - ATT_ReadByGrpTypeRsp(connection_handle, &rsp); - } - else if (start_handle == gap_service_handle) { - attReadByGrpTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = gap_service_handle & 0xFF; - buf[1] = (gap_service_handle >> 8) & 0xFF; - buf[2] = gap_service_end_handle & 0xFF; - buf[3] = (gap_service_end_handle >> 8) & 0xFF; - buf[4] = GAP_SERVICE_UUID & 0xFF; - buf[5] = (GAP_SERVICE_UUID >> 8) & 0xFF; - - rsp.pDataList = buf; - rsp.dataLen = 6; - ATT_ReadByGrpTypeRsp(connection_handle, &rsp); - } - else if (start_handle == pybricks_service_handle) { - attReadByGrpTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = pybricks_service_handle & 0xFF; - buf[1] = (pybricks_service_handle >> 8) & 0xFF; - buf[2] = pybricks_service_end_handle & 0xFF; - buf[3] = (pybricks_service_end_handle >> 8) & 0xFF; - memcpy(&buf[4], pybricks_service_uuid, 16); - - rsp.pDataList = buf; - rsp.dataLen = 20; - ATT_ReadByGrpTypeRsp(connection_handle, &rsp); - } - else if (start_handle == uart_service_handle) { - attReadByGrpTypeRsp_t rsp; - uint8_t buf[ATT_MTU_SIZE-2]; - - buf[0] = uart_service_handle & 0xFF; - buf[1] = (uart_service_handle >> 8) & 0xFF; - buf[2] = uart_service_end_handle & 0xFF; - buf[3] = (uart_service_end_handle >> 8) & 0xFF; - memcpy(&buf[4], nrf_uart_service_uuid, 16); - - rsp.pDataList = buf; - rsp.dataLen = 20; - ATT_ReadByGrpTypeRsp(connection_handle, &rsp); - } - else { - attErrorRsp_t rsp; - - rsp.reqOpcode = ATT_READ_BY_GRP_TYPE_REQ; - rsp.handle = start_handle; - rsp.errCode = ATT_ERR_INVALID_VALUE; - ATT_ErrorRsp(connection_handle, &rsp); - } - break; - default: - DBG("unhandled read by grp type req: %05X", group_type); - break; + case GATT_PRIMARY_SERVICE_UUID: + if (start_handle == gatt_service_handle) { + attReadByGrpTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = gatt_service_handle & 0xFF; + buf[1] = (gatt_service_handle >> 8) & 0xFF; + buf[2] = gatt_service_end_handle & 0xFF; + buf[3] = (gatt_service_end_handle >> 8) & 0xFF; + buf[4] = GATT_SERVICE_UUID & 0xFF; + buf[5] = (GATT_SERVICE_UUID >> 8) & 0xFF; + + rsp.pDataList = buf; + rsp.dataLen = 6; + ATT_ReadByGrpTypeRsp(connection_handle, &rsp); + } else if (start_handle == gap_service_handle) { + attReadByGrpTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = gap_service_handle & 0xFF; + buf[1] = (gap_service_handle >> 8) & 0xFF; + buf[2] = gap_service_end_handle & 0xFF; + buf[3] = (gap_service_end_handle >> 8) & 0xFF; + buf[4] = GAP_SERVICE_UUID & 0xFF; + buf[5] = (GAP_SERVICE_UUID >> 8) & 0xFF; + + rsp.pDataList = buf; + rsp.dataLen = 6; + ATT_ReadByGrpTypeRsp(connection_handle, &rsp); + } else if (start_handle == pybricks_service_handle) { + attReadByGrpTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = pybricks_service_handle & 0xFF; + buf[1] = (pybricks_service_handle >> 8) & 0xFF; + buf[2] = pybricks_service_end_handle & 0xFF; + buf[3] = (pybricks_service_end_handle >> 8) & 0xFF; + memcpy(&buf[4], pybricks_service_uuid, 16); + + rsp.pDataList = buf; + rsp.dataLen = 20; + ATT_ReadByGrpTypeRsp(connection_handle, &rsp); + } else if (start_handle == uart_service_handle) { + attReadByGrpTypeRsp_t rsp; + uint8_t buf[ATT_MTU_SIZE - 2]; + + buf[0] = uart_service_handle & 0xFF; + buf[1] = (uart_service_handle >> 8) & 0xFF; + buf[2] = uart_service_end_handle & 0xFF; + buf[3] = (uart_service_end_handle >> 8) & 0xFF; + memcpy(&buf[4], nrf_uart_service_uuid, 16); + + rsp.pDataList = buf; + rsp.dataLen = 20; + ATT_ReadByGrpTypeRsp(connection_handle, &rsp); + } else { + attErrorRsp_t rsp; + + rsp.reqOpcode = ATT_READ_BY_GRP_TYPE_REQ; + rsp.handle = start_handle; + rsp.errCode = ATT_ERR_INVALID_VALUE; + ATT_ErrorRsp(connection_handle, &rsp); + } + break; + default: + DBG("unhandled read by grp type req: %05X", group_type); + break; } } break; - case ATT_EVENT_WRITE_REQ: - { + case ATT_EVENT_WRITE_REQ: { uint16_t char_handle = (data[9] << 8) | data[8]; DBG("w: %04X %04X %d", char_handle, uart_tx_char_handle, pdu_len - 4); if (char_handle == uart_rx_char_handle) { uart_rx_char_modified(&data[10], pdu_len - 4); - } - else if (char_handle == uart_tx_char_handle + 1) { + } else if (char_handle == uart_tx_char_handle + 1) { uart_tx_notify_en = data[10]; DBG("noti: %d", uart_tx_notify_en); - } - else { + } else { DBG("unhandled write req: %04X", char_handle); } ATT_WriteRsp(connection_handle); } break; - case GAP_LINK_ESTABLISHED: - conn_handle = (data[11] << 8) | data[10]; - DBG("link: %04x", conn_handle); - break; + case GAP_LINK_ESTABLISHED: + conn_handle = (data[11] << 8) | data[10]; + DBG("link: %04x", conn_handle); + break; - case GAP_LINK_TERMINATED: - { + case GAP_LINK_TERMINATED: { DBG("bye: %04x", connection_handle); if (conn_handle == connection_handle) { conn_handle = NO_CONNECTION; @@ -629,22 +607,21 @@ static void handle_event(uint8_t *packet) { } break; - case GAP_LINK_PARAM_UPDATE: - // we get this event, but don't need to do anything about it - break; - - case HCI_EXT_SET_TX_POWER_EVENT: - case HCI_EXT_SET_LOCAL_SUPPORTED_FEATURES_EVENT: - case HCI_EXT_SET_BDADDR_EVENT: - case GAP_DEVICE_INIT_DONE: - case GAP_ADVERT_DATA_UPDATE_DONE: - case GAP_MAKE_DISCOVERABLE_DONE: - case GAP_END_DISCOVERABLE_DONE: - hci_command_complete = true; - break; - - case HCI_COMMAND_STATUS: - { + case GAP_LINK_PARAM_UPDATE: + // we get this event, but don't need to do anything about it + break; + + case HCI_EXT_SET_TX_POWER_EVENT: + case HCI_EXT_SET_LOCAL_SUPPORTED_FEATURES_EVENT: + case HCI_EXT_SET_BDADDR_EVENT: + case GAP_DEVICE_INIT_DONE: + case GAP_ADVERT_DATA_UPDATE_DONE: + case GAP_MAKE_DISCOVERABLE_DONE: + case GAP_END_DISCOVERABLE_DONE: + hci_command_complete = true; + break; + + case HCI_COMMAND_STATUS: { uint16_t opcode = (data[4] << 8) | data[3]; // This filters out responses that were sent from commands // initiated from here in the event handler. @@ -657,9 +634,9 @@ static void handle_event(uint8_t *packet) { } break; - default: - DBG("unhandled: %04X", event_code); - break; + default: + DBG("unhandled: %04X", event_code); + break; } } break; @@ -698,8 +675,7 @@ PROCESS_THREAD(pbdrv_bluetooth_spi_process, ev, data) { if (write_xfer_size) { // if we are writing only, we have to wait until SRDY is asserted PROCESS_WAIT_UNTIL(spi_srdy); - } - else { + } else { // if we are reading only, the write buffer has to be all 0s memset(write_buf, 0, PBIO_ARRAY_SIZE(write_buf)); } @@ -713,15 +689,14 @@ PROCESS_THREAD(pbdrv_bluetooth_spi_process, ev, data) { read_xfer_size = 0; if (get_npi_rx_size(&read_xfer_size) && read_xfer_size > write_xfer_size - 4) { xfer_size = read_xfer_size + 4; - } - else { + } else { xfer_size = write_xfer_size; } // read the remaining message spi_xfer_complete = false; HAL_SPI_TransmitReceive_DMA(&bt_spi, &write_buf[NPI_SPI_HEADER_LEN], - &read_buf[NPI_SPI_HEADER_LEN], xfer_size); + &read_buf[NPI_SPI_HEADER_LEN], xfer_size); PROCESS_WAIT_UNTIL(spi_xfer_complete); spi_set_mrdy(false); @@ -812,7 +787,7 @@ static PT_THREAD(gatt_init(struct pt *pt)) { PT_WAIT_WHILE(pt, write_xfer_size); GATT_AddAttribute(GATT_CHARACTER_UUID, GATT_PERMIT_WRITE | GATT_PERMIT_AUTHEN_READ | - GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_ENCRYPT_READ); + GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_ENCRYPT_READ); PT_WAIT_UNTIL(pt, hci_command_status); // ignoring response data @@ -823,7 +798,7 @@ static PT_THREAD(gatt_init(struct pt *pt)) { PT_WAIT_WHILE(pt, write_xfer_size); GATT_AddAttribute(GATT_CHARACTER_UUID, GATT_PERMIT_WRITE | GATT_PERMIT_AUTHEN_READ | - GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_ENCRYPT_READ); + GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_ENCRYPT_READ); PT_WAIT_UNTIL(pt, hci_command_status); // ignoring response data @@ -1040,7 +1015,7 @@ static PT_THREAD(init_pybricks_service(struct pt *pt)) { PT_WAIT_WHILE(pt, write_xfer_size); GATT_AddAttribute(GATT_CHARACTER_UUID, GATT_PERMIT_WRITE | GATT_PERMIT_AUTHEN_READ | - GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_AUTHOR_READ); + GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_AUTHOR_READ); PT_WAIT_UNTIL(pt, hci_command_status); // ignoring response data @@ -1085,7 +1060,7 @@ static PT_THREAD(init_uart_service(struct pt *pt)) { PT_WAIT_WHILE(pt, write_xfer_size); GATT_AddAttribute(GATT_CHARACTER_UUID, GATT_PERMIT_WRITE | GATT_PERMIT_AUTHEN_READ | - GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_AUTHOR_READ); + GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_AUTHOR_READ); PT_WAIT_UNTIL(pt, hci_command_status); // ignoring response data @@ -1096,7 +1071,7 @@ static PT_THREAD(init_uart_service(struct pt *pt)) { PT_WAIT_WHILE(pt, write_xfer_size); GATT_AddAttribute(GATT_CHARACTER_UUID, GATT_PERMIT_WRITE | GATT_PERMIT_AUTHEN_READ | - GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_AUTHOR_READ); + GATT_PERMIT_AUTHEN_WRITE | GATT_PERMIT_AUTHOR_READ); PT_WAIT_UNTIL(pt, hci_command_status); // ignoring response data diff --git a/lib/pbio/drv/cplus_hub/light.c b/lib/pbio/drv/cplus_hub/light.c index c65b340a3..d25a0bf8e 100644 --- a/lib/pbio/drv/cplus_hub/light.c +++ b/lib/pbio/drv/cplus_hub/light.c @@ -69,52 +69,52 @@ pbio_error_t pbdrv_light_set_rgb(pbio_port_t port, uint8_t r, uint8_t g, uint8_t } pbio_error_t pbdrv_light_get_rgb_for_color(pbio_port_t port, pbio_light_color_t color, - uint8_t *r, uint8_t *g, uint8_t *b) { + uint8_t *r, uint8_t *g, uint8_t *b) { if (port != PBIO_PORT_SELF) { return PBIO_ERROR_INVALID_PORT; } switch (color) { - case PBIO_LIGHT_COLOR_WHITE: - *r = 185; - *g = 161; - *b = 22; - break; - case PBIO_LIGHT_COLOR_RED: - *r = 255; - *g = 0; - *b = 0; - break; - case PBIO_LIGHT_COLOR_ORANGE: - *r = 255; - *g = 37; - *b = 0; - break; - case PBIO_LIGHT_COLOR_YELLOW: - *r = 255; - *g = 140; - *b = 0; - break; - case PBIO_LIGHT_COLOR_GREEN: - *r = 0; - *g = 255; - *b = 0; - break; - case PBIO_LIGHT_COLOR_BLUE: - *r = 0; - *g = 0; - *b = 180; - break; - case PBIO_LIGHT_COLOR_PURPLE: - *r = 220; - *g = 0; - *b = 110; - break; - default: - *r = 0; - *g = 0; - *b = 0; - break; + case PBIO_LIGHT_COLOR_WHITE: + *r = 185; + *g = 161; + *b = 22; + break; + case PBIO_LIGHT_COLOR_RED: + *r = 255; + *g = 0; + *b = 0; + break; + case PBIO_LIGHT_COLOR_ORANGE: + *r = 255; + *g = 37; + *b = 0; + break; + case PBIO_LIGHT_COLOR_YELLOW: + *r = 255; + *g = 140; + *b = 0; + break; + case PBIO_LIGHT_COLOR_GREEN: + *r = 0; + *g = 255; + *b = 0; + break; + case PBIO_LIGHT_COLOR_BLUE: + *r = 0; + *g = 0; + *b = 180; + break; + case PBIO_LIGHT_COLOR_PURPLE: + *r = 220; + *g = 0; + *b = 110; + break; + default: + *r = 0; + *g = 0; + *b = 0; + break; } return PBIO_SUCCESS; diff --git a/lib/pbio/drv/cplus_hub/motor.c b/lib/pbio/drv/cplus_hub/motor.c index 759e71e1e..7e7425a04 100644 --- a/lib/pbio/drv/cplus_hub/motor.c +++ b/lib/pbio/drv/cplus_hub/motor.c @@ -27,7 +27,7 @@ typedef struct { } pbdrv_motor_data_t; static pbdrv_motor_data_t -platform_data[PBDRV_CONFIG_NUM_MOTOR_CONTROLLER] = { + platform_data[PBDRV_CONFIG_NUM_MOTOR_CONTROLLER] = { { .pin1_gpio.bank = GPIOA, .pin1_gpio.pin = 1, diff --git a/lib/pbio/drv/debug/light.c b/lib/pbio/drv/debug/light.c index a9dc93c02..5a5e544d8 100644 --- a/lib/pbio/drv/debug/light.c +++ b/lib/pbio/drv/debug/light.c @@ -85,52 +85,52 @@ pbio_error_t pbdrv_light_set_rgb(pbio_port_t port, uint8_t r, uint8_t g, uint8_t } pbio_error_t pbdrv_light_get_rgb_for_color(pbio_port_t port, pbio_light_color_t color, - uint8_t *r, uint8_t *g, uint8_t *b) { + uint8_t *r, uint8_t *g, uint8_t *b) { if (port != PBIO_PORT_SELF) { return PBIO_ERROR_INVALID_PORT; } switch (color) { - case PBIO_LIGHT_COLOR_WHITE: - *r = 255; - *g = 140; - *b = 60; - break; - case PBIO_LIGHT_COLOR_RED: - *r = 255; - *g = 0; - *b = 0; - break; - case PBIO_LIGHT_COLOR_ORANGE: - *r = 255; - *g = 25; - *b = 0; - break; - case PBIO_LIGHT_COLOR_YELLOW: - *r = 255; - *g = 70; - *b = 0; - break; - case PBIO_LIGHT_COLOR_GREEN: - *r = 0; - *g = 200; - *b = 0; - break; - case PBIO_LIGHT_COLOR_BLUE: - *r = 0; - *g = 0; - *b = 255; - break; - case PBIO_LIGHT_COLOR_PURPLE: - *r = 220; - *g = 0; - *b = 120; - break; - default: - *r = 0; - *g = 0; - *b = 0; - break; + case PBIO_LIGHT_COLOR_WHITE: + *r = 255; + *g = 140; + *b = 60; + break; + case PBIO_LIGHT_COLOR_RED: + *r = 255; + *g = 0; + *b = 0; + break; + case PBIO_LIGHT_COLOR_ORANGE: + *r = 255; + *g = 25; + *b = 0; + break; + case PBIO_LIGHT_COLOR_YELLOW: + *r = 255; + *g = 70; + *b = 0; + break; + case PBIO_LIGHT_COLOR_GREEN: + *r = 0; + *g = 200; + *b = 0; + break; + case PBIO_LIGHT_COLOR_BLUE: + *r = 0; + *g = 0; + *b = 255; + break; + case PBIO_LIGHT_COLOR_PURPLE: + *r = 220; + *g = 0; + *b = 120; + break; + default: + *r = 0; + *g = 0; + *b = 0; + break; } return PBIO_SUCCESS; diff --git a/lib/pbio/drv/ev3dev_stretch/light.c b/lib/pbio/drv/ev3dev_stretch/light.c index 00f07aac7..3fa9a5ba0 100644 --- a/lib/pbio/drv/ev3dev_stretch/light.c +++ b/lib/pbio/drv/ev3dev_stretch/light.c @@ -18,14 +18,14 @@ static FILE *f_brightness[NLEDS]; void _pbdrv_light_init(void) { - const char * const trigger_paths[NLEDS] = { + const char *const trigger_paths[NLEDS] = { "/sys/class/leds/led0:red:brick-status/trigger", "/sys/class/leds/led1:red:brick-status/trigger", "/sys/class/leds/led0:green:brick-status/trigger", "/sys/class/leds/led1:green:brick-status/trigger" }; - const char * const brightness_paths[NLEDS] = { + const char *const brightness_paths[NLEDS] = { "/sys/class/leds/led0:red:brick-status/brightness", "/sys/class/leds/led1:red:brick-status/brightness", "/sys/class/leds/led0:green:brick-status/brightness", @@ -33,7 +33,7 @@ void _pbdrv_light_init(void) { }; for (int led = 0; led < NLEDS; led++) { - FILE* f_trigger = fopen(trigger_paths[led], "w"); + FILE *f_trigger = fopen(trigger_paths[led], "w"); if (!f_trigger) { continue; } @@ -78,38 +78,38 @@ pbio_error_t pbdrv_light_set_rgb(pbio_port_t port, uint8_t r, uint8_t g, uint8_t } pbio_error_t pbdrv_light_get_rgb_for_color(pbio_port_t port, pbio_light_color_t color, - uint8_t *r, uint8_t *g, uint8_t *b) { + uint8_t *r, uint8_t *g, uint8_t *b) { if (port != PBIO_PORT_SELF) { return PBIO_ERROR_INVALID_PORT; } switch (color) { - case PBIO_LIGHT_COLOR_RED: - *r = 255; - *g = 0; - *b = 0; - break; - case PBIO_LIGHT_COLOR_ORANGE: - *r = 255; - *g = 255; - *b = 0; - break; - case PBIO_LIGHT_COLOR_YELLOW: - *r = 30; - *g = 255; - *b = 0; - break; - case PBIO_LIGHT_COLOR_GREEN: - *r = 0; - *g = 255; - *b = 0; - break; - default: - *r = 0; - *g = 0; - *b = 0; - break; + case PBIO_LIGHT_COLOR_RED: + *r = 255; + *g = 0; + *b = 0; + break; + case PBIO_LIGHT_COLOR_ORANGE: + *r = 255; + *g = 255; + *b = 0; + break; + case PBIO_LIGHT_COLOR_YELLOW: + *r = 30; + *g = 255; + *b = 0; + break; + case PBIO_LIGHT_COLOR_GREEN: + *r = 0; + *g = 255; + *b = 0; + break; + default: + *r = 0; + *g = 0; + *b = 0; + break; } return PBIO_SUCCESS; diff --git a/lib/pbio/drv/ev3dev_stretch/motor.c b/lib/pbio/drv/ev3dev_stretch/motor.c index 72a9655f1..d3ef51eb2 100644 --- a/lib/pbio/drv/ev3dev_stretch/motor.c +++ b/lib/pbio/drv/ev3dev_stretch/motor.c @@ -21,10 +21,12 @@ #define PORT_TO_IDX(p) ((p) - PBDRV_CONFIG_FIRST_MOTOR_PORT) -inline void _pbdrv_motor_init(void) { } +inline void _pbdrv_motor_init(void) { +} #if PBIO_CONFIG_ENABLE_DEINIT -void _pbdrv_motor_deinit(void) { } +void _pbdrv_motor_deinit(void) { +} #endif typedef struct _motor_t { @@ -63,13 +65,12 @@ static pbio_error_t ev3dev_motor_init(motor_t *mtr, pbio_port_t port) { // Determine motor type ID if (!strcmp(driver_name, "lego-ev3-l-motor")) { mtr->id = PBIO_IODEV_TYPE_ID_EV3_LARGE_MOTOR; - } - else { + } else { mtr->id = PBIO_IODEV_TYPE_ID_EV3_MEDIUM_MOTOR; } // Close driver name file if (fclose(f_driver_name) != 0) { - return PBIO_ERROR_IO; + return PBIO_ERROR_IO; } // Open command file err = sysfs_open_tacho_motor_attr(&mtr->f_command, mtr->n_motor, "command", "w"); @@ -80,7 +81,7 @@ static pbio_error_t ev3dev_motor_init(motor_t *mtr, pbio_port_t port) { err = sysfs_open_tacho_motor_attr(&mtr->f_duty, mtr->n_motor, "duty_cycle_sp", "w"); if (err != PBIO_SUCCESS) { return err; - + } } // If tacho-motor was not found, look for dc-motor instead @@ -102,8 +103,7 @@ static pbio_error_t ev3dev_motor_init(motor_t *mtr, pbio_port_t port) { if (err != PBIO_SUCCESS) { return err; } - } - else { + } else { // Could not find either type of motor, so return the error return err; } @@ -175,7 +175,7 @@ pbio_error_t pbdrv_motor_set_duty_cycle(pbio_port_t port, int16_t duty_cycle) { mtr->coasting = false; } // Set the duty cycle value - err = sysfs_write_int(mtr->f_duty, duty_cycle/100); + err = sysfs_write_int(mtr->f_duty, duty_cycle / 100); return ev3dev_motor_connect_status(mtr, err); } diff --git a/lib/pbio/drv/ev3dev_stretch/pcm.c b/lib/pbio/drv/ev3dev_stretch/pcm.c index 52596a07b..f145990e4 100644 --- a/lib/pbio/drv/ev3dev_stretch/pcm.c +++ b/lib/pbio/drv/ev3dev_stretch/pcm.c @@ -63,9 +63,9 @@ static pbio_error_t configure_volume_control(pbdrv_pcm_dev_t *pcm_dev) { return PBIO_ERROR_FAILED; } if (snd_mixer_selem_get_playback_volume_range( - pcm_dev->pcm_elem, - &pcm_dev->pcm_vol_min, - &pcm_dev->pcm_vol_max) != 0) { + pcm_dev->pcm_elem, + &pcm_dev->pcm_vol_min, + &pcm_dev->pcm_vol_max) != 0) { return PBIO_ERROR_IO; } @@ -77,9 +77,9 @@ static pbio_error_t configure_volume_control(pbdrv_pcm_dev_t *pcm_dev) { return PBIO_ERROR_FAILED; } if (snd_mixer_selem_get_playback_volume_range( - pcm_dev->beep_elem, - &pcm_dev->beep_vol_min, - &pcm_dev->beep_vol_max) != 0) { + pcm_dev->beep_elem, + &pcm_dev->beep_vol_min, + &pcm_dev->beep_vol_max) != 0) { return PBIO_ERROR_IO; } @@ -96,10 +96,10 @@ static pbio_error_t configure_pcm(pbdrv_pcm_dev_t *pcm_dev) { // Open pcm if (snd_pcm_open( - &pcm_dev->pcm, - "default", - SND_PCM_STREAM_PLAYBACK, - SND_PCM_NONBLOCK) != 0) { + &pcm_dev->pcm, + "default", + SND_PCM_STREAM_PLAYBACK, + SND_PCM_NONBLOCK) != 0) { return PBIO_ERROR_IO; } @@ -112,8 +112,8 @@ pbio_error_t pbdrv_pcm_set_volume(pbdrv_pcm_dev_t *pcm_dev, uint32_t volume) { return PBIO_ERROR_INVALID_ARG; } - long pcm_vol = (volume*(pcm_dev->pcm_vol_max - pcm_dev->pcm_vol_min))/100 + pcm_dev->pcm_vol_min; - long beep_vol = (volume*(pcm_dev->beep_vol_max - pcm_dev->beep_vol_min))/100 + pcm_dev->beep_vol_min; + long pcm_vol = (volume * (pcm_dev->pcm_vol_max - pcm_dev->pcm_vol_min)) / 100 + pcm_dev->pcm_vol_min; + long beep_vol = (volume * (pcm_dev->beep_vol_max - pcm_dev->beep_vol_min)) / 100 + pcm_dev->beep_vol_min; if (snd_mixer_selem_set_playback_volume_all(pcm_dev->pcm_elem, pcm_vol) != 0) { return PBIO_ERROR_IO; @@ -162,7 +162,7 @@ pbio_error_t pbdrv_pcm_play_file_start(pbdrv_pcm_dev_t *pcm_dev, const char *pat if (snd_pcm_hw_params_set_channels(pcm_dev->pcm, hp, pcm_dev->sf_info.channels) != 0) { return PBIO_ERROR_IO; } - + // Set rate if (snd_pcm_hw_params_set_rate(pcm_dev->pcm, hp, pcm_dev->sf_info.samplerate, 0) != 0) { return PBIO_ERROR_IO; @@ -215,7 +215,7 @@ pbio_error_t pbdrv_pcm_play_file_update(pbdrv_pcm_dev_t *pcm_dev) { if (count < 0) { return PBIO_ERROR_IO; } - + // If there are no frames, we are done if (count == 0) { return PBIO_SUCCESS; diff --git a/lib/pbio/drv/ev3dev_stretch/serial.c b/lib/pbio/drv/ev3dev_stretch/serial.c index 59569bff0..edffe5e95 100644 --- a/lib/pbio/drv/ev3dev_stretch/serial.c +++ b/lib/pbio/drv/ev3dev_stretch/serial.c @@ -15,7 +15,7 @@ #include -static const char* const TTY_PATH[] = { +static const char *const TTY_PATH[] = { "/dev/tty_ev3-ports:in1", "/dev/tty_ev3-ports:in2", "/dev/tty_ev3-ports:in3", @@ -44,27 +44,69 @@ static pbio_error_t pbdrv_serial_config(pbdrv_serial_t *ser, int baudrate) { // Convert to termios baudrate speed_t speed; switch (baudrate) { - case 50: speed = B50; break; - case 75: speed = B75; break; - case 110: speed = B110; break; - case 134: speed = B134; break; - case 150: speed = B150; break; - case 200: speed = B200; break; - case 300: speed = B300; break; - case 600: speed = B600; break; - case 1200: speed = B1200; break; - case 1800: speed = B1800; break; - case 2400: speed = B2400; break; - case 4800: speed = B4800; break; - case 9600: speed = B9600; break; - case 19200: speed = B19200; break; - case 38400: speed = B38400; break; - case 57600: speed = B57600; break; - case 115200: speed = B115200; break; - case 230400: speed = B230400; break; - case 460800: speed = B460800; break; - case 500000: speed = B500000; break; - case 576000: speed = B576000; break; + case 50: + speed = B50; + break; + case 75: + speed = B75; + break; + case 110: + speed = B110; + break; + case 134: + speed = B134; + break; + case 150: + speed = B150; + break; + case 200: + speed = B200; + break; + case 300: + speed = B300; + break; + case 600: + speed = B600; + break; + case 1200: + speed = B1200; + break; + case 1800: + speed = B1800; + break; + case 2400: + speed = B2400; + break; + case 4800: + speed = B4800; + break; + case 9600: + speed = B9600; + break; + case 19200: + speed = B19200; + break; + case 38400: + speed = B38400; + break; + case 57600: + speed = B57600; + break; + case 115200: + speed = B115200; + break; + case 230400: + speed = B230400; + break; + case 460800: + speed = B460800; + break; + case 500000: + speed = B500000; + break; + case 576000: + speed = B576000; + break; default: return PBIO_ERROR_INVALID_ARG; } @@ -104,10 +146,10 @@ pbio_error_t pbdrv_serial_get(pbdrv_serial_t **_ser, pbio_port_t port, int baudr // Get device pointer pbio_error_t err; - pbdrv_serial_t *ser = &pbdrv_serials[port-PBIO_PORT_1]; + pbdrv_serial_t *ser = &pbdrv_serials[port - PBIO_PORT_1]; // Open pbdrv_serial port - err = pbdrv_serial_open(ser, TTY_PATH[port-PBIO_PORT_1]); + err = pbdrv_serial_open(ser, TTY_PATH[port - PBIO_PORT_1]); if (err != PBIO_SUCCESS) { return err; } @@ -144,8 +186,7 @@ pbio_error_t pbdrv_serial_read(pbdrv_serial_t *ser, uint8_t *buf, size_t count, if (errno == EAGAIN) { *received = 0; return PBIO_SUCCESS; - } - else { + } else { return PBIO_ERROR_IO; } } diff --git a/lib/pbio/drv/ioport/ioport_ev3dev_stretch.c b/lib/pbio/drv/ioport/ioport_ev3dev_stretch.c index a38d48239..9d2f8067d 100644 --- a/lib/pbio/drv/ioport/ioport_ev3dev_stretch.c +++ b/lib/pbio/drv/ioport/ioport_ev3dev_stretch.c @@ -70,32 +70,32 @@ pbio_error_t pbdrv_ioport_ev3dev_get_syspath(pbio_port_t port, const char **sysp ev3dev_port_t *p; switch (port) { - case PBIO_PORT_1: - name = "ev3-ports:in1"; - break; - case PBIO_PORT_2: - name = "ev3-ports:in2"; - break; - case PBIO_PORT_3: - name = "ev3-ports:in3"; - break; - case PBIO_PORT_4: - name = "ev3-ports:in4"; - break; - case PBIO_PORT_A: - name = "ev3-ports:outA"; - break; - case PBIO_PORT_B: - name = "ev3-ports:outB"; - break; - case PBIO_PORT_C: - name = "ev3-ports:outC"; - break; - case PBIO_PORT_D: - name = "ev3-ports:outD"; - break; - default: - return PBIO_ERROR_INVALID_PORT; + case PBIO_PORT_1: + name = "ev3-ports:in1"; + break; + case PBIO_PORT_2: + name = "ev3-ports:in2"; + break; + case PBIO_PORT_3: + name = "ev3-ports:in3"; + break; + case PBIO_PORT_4: + name = "ev3-ports:in4"; + break; + case PBIO_PORT_A: + name = "ev3-ports:outA"; + break; + case PBIO_PORT_B: + name = "ev3-ports:outB"; + break; + case PBIO_PORT_C: + name = "ev3-ports:outC"; + break; + case PBIO_PORT_D: + name = "ev3-ports:outD"; + break; + default: + return PBIO_ERROR_INVALID_PORT; } p = find_port(name); diff --git a/lib/pbio/drv/ioport/ioport_lpf2.c b/lib/pbio/drv/ioport/ioport_lpf2.c index f96416a01..aee874ad8 100644 --- a/lib/pbio/drv/ioport/ioport_lpf2.c +++ b/lib/pbio/drv/ioport/ioport_lpf2.c @@ -210,36 +210,36 @@ static const pbio_iodev_type_id_t ioport_type_id_lookup[3][3] = { PROCESS(pbdrv_ioport_lpf2_process, "I/O port"); static ioport_dev_t ioport_devs[PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS] = { -#if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 0 + #if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 0 [0] = { .pins = &pbdrv_ioport_lpf2_platform_port_0, }, -#endif -#if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 1 + #endif + #if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 1 [1] = { .pins = &pbdrv_ioport_lpf2_platform_port_1, }, -#endif -#if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 2 + #endif + #if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 2 [2] = { .pins = &pbdrv_ioport_lpf2_platform_port_2, }, -#endif -#if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 3 + #endif + #if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 3 [3] = { .pins = &pbdrv_ioport_lpf2_platform_port_3, }, -#endif -#if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 4 + #endif + #if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 4 [4] = { .pins = &pbdrv_ioport_lpf2_platform_port_4, }, -#endif -#if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 5 + #endif + #if PBDRV_CONFIG_IOPORT_LPF2_NUM_PORTS > 5 [5] = { .pins = &pbdrv_ioport_lpf2_platform_port_5, }, -#endif + #endif }; static void ioport_enable_uart(ioport_dev_t *ioport) { @@ -285,7 +285,7 @@ pbio_error_t pbdrv_ioport_get_iodev(pbio_port_t port, pbio_iodev_t **iodev) { // This is the device connection manager (dcm). It monitors the ID1 and ID2 pins // on the port to see when devices are connected or disconnected. // It is expected for there to be a 2ms delay between calls to this function. -static PT_THREAD(poll_dcm(ioport_dev_t *ioport)) { +static PT_THREAD(poll_dcm(ioport_dev_t * ioport)) { struct pt *pt = &ioport->pt; dcm_data_t *data = &ioport->dcm; const pbdrv_ioport_lpf2_platform_port_t pins = *ioport->pins; @@ -328,13 +328,12 @@ static PT_THREAD(poll_dcm(ioport_dev_t *ioport)) { // ID1 is inverse of touch sensor value // TODO: save this value to sensor data - //sensor_data = !pbdrv_gpio_input(&pins.id1); + // sensor_data = !pbdrv_gpio_input(&pins.id1); } // if ID2 changed from low to high else if (data->prev_gpio_value == 0 && data->gpio_value == 1) { data->type_id = PBIO_IODEV_TYPE_ID_LPF2_TPOINT; - } - else { + } else { // read ID1 data->prev_gpio_value = pbdrv_gpio_input(&pins.id1); @@ -355,8 +354,7 @@ static PT_THREAD(poll_dcm(ioport_dev_t *ioport)) { else if (data->prev_gpio_value == 0 && data->gpio_value == 0) { // we have ID1 == GND data->dev_id1_group = DEV_ID1_GROUP_GND; - } - else { + } else { // set ID1 as input pbdrv_gpio_out_high(&pins.uart_buf); pbdrv_gpio_input(&pins.uart_tx); @@ -367,8 +365,7 @@ static PT_THREAD(poll_dcm(ioport_dev_t *ioport)) { if (pbdrv_gpio_input(&pins.id1) == 1) { // we have ID1 == open data->dev_id1_group = DEV_ID1_GROUP_OPEN; - } - else { + } else { // we have ID1 == pull down data->dev_id1_group = DEV_ID1_GROUP_PULL_DOWN; } @@ -408,8 +405,7 @@ static PT_THREAD(poll_dcm(ioport_dev_t *ioport)) { else if (data->prev_gpio_value == 0 && data->gpio_value == 1) { // something might explode data->type_id = PBIO_IODEV_TYPE_ID_LPF2_EXPLOD; - } - else { + } else { // set ID1 high pbdrv_gpio_out_high(&pins.uart_tx); pbdrv_gpio_out_low(&pins.uart_buf); @@ -431,19 +427,16 @@ static PT_THREAD(poll_dcm(ioport_dev_t *ioport)) { if (data->dev_id1_group < 3) { data->type_id = ioport_type_id_lookup[data->dev_id1_group][2]; } - } - else { + } else { if (data->dev_id1_group < 3) { data->type_id = ioport_type_id_lookup[data->dev_id1_group][1]; } } - } - else { + } else { // we know the device now if (data->dev_id1_group < 3) { data->type_id = ioport_type_id_lookup[data->dev_id1_group][0]; - } - else { + } else { data->type_id = PBIO_IODEV_TYPE_ID_LPF2_UNKNOWN_UART; } } diff --git a/lib/pbio/drv/move_hub/bluetooth.c b/lib/pbio/drv/move_hub/bluetooth.c index 6eddf3381..6dff58e76 100644 --- a/lib/pbio/drv/move_hub/bluetooth.c +++ b/lib/pbio/drv/move_hub/bluetooth.c @@ -213,7 +213,8 @@ static void spi_start_xfer(const uint8_t *tx_buf, uint8_t *rx_buf, uint8_t xfer_ // hopefully this shouldn't actually block, but we can't disable SPI while // it is busy, so just in case... - while (SPI2->SR & SPI_SR_BSY) { } + while (SPI2->SR & SPI_SR_BSY) { + } // disable the SPI so we can configure it SPI2->CR1 &= ~SPI_CR1_SPE; @@ -255,9 +256,9 @@ static void pybricks_char_modified(uint8_t *data, uint8_t size) { } switch (data[0]) { - case PBIO_COM_MSG_TYPE_CMD: - process_post(&pbsys_process, PBIO_EVENT_COM_CMD, (process_data_t)(uint32_t)data[1]); - break; + case PBIO_COM_MSG_TYPE_CMD: + process_post(&pbsys_process, PBIO_EVENT_COM_CMD, (process_data_t)(uint32_t)data[1]); + break; } } @@ -296,23 +297,20 @@ static void uart_rx_char_modified(uint8_t *data, uint8_t size); // processes an event received from the Bluetooth chip static void handle_event(hci_event_pckt *event) { switch (event->evt) { - case EVT_DISCONN_COMPLETE: - { + case EVT_DISCONN_COMPLETE: { evt_disconn_complete *evt = (evt_disconn_complete *)event->data; if (conn_handle == evt->handle) { conn_handle = 0; } } break; - case EVT_CMD_COMPLETE: - hci_command_complete = true; - break; - case EVT_LE_META_EVENT: - { + case EVT_CMD_COMPLETE: + hci_command_complete = true; + break; + case EVT_LE_META_EVENT: { evt_le_meta_event *evt = (evt_le_meta_event *)event->data; switch (evt->subevent) { - case EVT_LE_CONN_COMPLETE: - { + case EVT_LE_CONN_COMPLETE: { evt_le_connection_complete *subevt = (evt_le_connection_complete *)evt->data; conn_handle = subevt->handle; } @@ -320,23 +318,19 @@ static void handle_event(hci_event_pckt *event) { } } break; - case EVT_VENDOR: - { + case EVT_VENDOR: { evt_blue_aci *evt = (evt_blue_aci *)event->data; switch (evt->ecode) { - case EVT_BLUE_HAL_INITIALIZED: - { + case EVT_BLUE_HAL_INITIALIZED: { evt_hal_initialized *subevt = (evt_hal_initialized *)evt->data; reset_reason = subevt->reason_code; } break; - case EVT_BLUE_GATT_ATTRIBUTE_MODIFIED: - { + case EVT_BLUE_GATT_ATTRIBUTE_MODIFIED: { evt_gatt_attr_modified *subevt = (evt_gatt_attr_modified *)evt->data; if (subevt->attr_handle == pybricks_char_handle + 1) { pybricks_char_modified(subevt->att_data, subevt->data_length); - } - else if (subevt->attr_handle == uart_rx_char_handle + 1) { + } else if (subevt->attr_handle == uart_rx_char_handle + 1) { uart_rx_char_modified(subevt->att_data, subevt->data_length); } } @@ -388,7 +382,7 @@ static PT_THREAD(spi_read(struct pt *pt)) { } // TODO: do we need to handle ACL packets (HCI_ACLDATA_PKT)? -end: ; +end:; PT_END(pt); } diff --git a/lib/pbio/drv/move_hub/light.c b/lib/pbio/drv/move_hub/light.c index 05a6b136f..ee056149f 100644 --- a/lib/pbio/drv/move_hub/light.c +++ b/lib/pbio/drv/move_hub/light.c @@ -86,7 +86,7 @@ pbio_error_t pbdrv_light_set_rgb(pbio_port_t port, uint8_t r, uint8_t g, uint8_t } pbio_error_t pbdrv_light_get_rgb_for_color(pbio_port_t port, pbio_light_color_t color, - uint8_t *r, uint8_t *g, uint8_t *b) { + uint8_t *r, uint8_t *g, uint8_t *b) { if (port == PBIO_PORT_C || port == PBIO_PORT_D) { // TODO: check for Powered UP Lights connected to ports C/D return PBIO_ERROR_NO_DEV; @@ -97,46 +97,46 @@ pbio_error_t pbdrv_light_get_rgb_for_color(pbio_port_t port, pbio_light_color_t } switch (color) { - case PBIO_LIGHT_COLOR_WHITE: - *r = 255; - *g = 140; - *b = 60; - break; - case PBIO_LIGHT_COLOR_RED: - *r = 255; - *g = 0; - *b = 0; - break; - case PBIO_LIGHT_COLOR_ORANGE: - *r = 255; - *g = 25; - *b = 0; - break; - case PBIO_LIGHT_COLOR_YELLOW: - *r = 255; - *g = 70; - *b = 0; - break; - case PBIO_LIGHT_COLOR_GREEN: - *r = 0; - *g = 200; - *b = 0; - break; - case PBIO_LIGHT_COLOR_BLUE: - *r = 0; - *g = 0; - *b = 255; - break; - case PBIO_LIGHT_COLOR_PURPLE: - *r = 220; - *g = 0; - *b = 120; - break; - default: - *r = 0; - *g = 0; - *b = 0; - break; + case PBIO_LIGHT_COLOR_WHITE: + *r = 255; + *g = 140; + *b = 60; + break; + case PBIO_LIGHT_COLOR_RED: + *r = 255; + *g = 0; + *b = 0; + break; + case PBIO_LIGHT_COLOR_ORANGE: + *r = 255; + *g = 25; + *b = 0; + break; + case PBIO_LIGHT_COLOR_YELLOW: + *r = 255; + *g = 70; + *b = 0; + break; + case PBIO_LIGHT_COLOR_GREEN: + *r = 0; + *g = 200; + *b = 0; + break; + case PBIO_LIGHT_COLOR_BLUE: + *r = 0; + *g = 0; + *b = 255; + break; + case PBIO_LIGHT_COLOR_PURPLE: + *r = 220; + *g = 0; + *b = 120; + break; + default: + *r = 0; + *g = 0; + *b = 0; + break; } return PBIO_SUCCESS; diff --git a/lib/pbio/drv/move_hub/motor.c b/lib/pbio/drv/move_hub/motor.c index f84f386b1..75e1cf6b5 100644 --- a/lib/pbio/drv/move_hub/motor.c +++ b/lib/pbio/drv/move_hub/motor.c @@ -126,32 +126,32 @@ pbio_error_t pbdrv_motor_coast(pbio_port_t port) { // set both port pins 1 and 2 to output low switch (port) { - case PBIO_PORT_A: - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOA->BRR = GPIO_BRR_BR_8; - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER10_Msk) | (1 << GPIO_MODER_MODER10_Pos); - GPIOA->BRR = GPIO_BRR_BR_10; - break; - case PBIO_PORT_B: - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOA->BRR = GPIO_BRR_BR_9; - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER11_Msk) | (1 << GPIO_MODER_MODER11_Pos); - GPIOA->BRR = GPIO_BRR_BR_11; - break; - case PBIO_PORT_C: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); - GPIOC->BRR = GPIO_BRR_BR_6; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOC->BRR = GPIO_BRR_BR_8; - break; - case PBIO_PORT_D: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); - GPIOC->BRR = GPIO_BRR_BR_7; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOC->BRR = GPIO_BRR_BR_9; - break; - default: - return PBIO_ERROR_INVALID_PORT; + case PBIO_PORT_A: + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOA->BRR = GPIO_BRR_BR_8; + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER10_Msk) | (1 << GPIO_MODER_MODER10_Pos); + GPIOA->BRR = GPIO_BRR_BR_10; + break; + case PBIO_PORT_B: + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOA->BRR = GPIO_BRR_BR_9; + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER11_Msk) | (1 << GPIO_MODER_MODER11_Pos); + GPIOA->BRR = GPIO_BRR_BR_11; + break; + case PBIO_PORT_C: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); + GPIOC->BRR = GPIO_BRR_BR_6; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOC->BRR = GPIO_BRR_BR_8; + break; + case PBIO_PORT_D: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); + GPIOC->BRR = GPIO_BRR_BR_7; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOC->BRR = GPIO_BRR_BR_9; + break; + default: + return PBIO_ERROR_INVALID_PORT; } return PBIO_SUCCESS; @@ -160,96 +160,96 @@ pbio_error_t pbdrv_motor_coast(pbio_port_t port) { static void pbdrv_motor_brake(pbio_port_t port) { // set both port pins 1 and 2 to output high switch (port) { - case PBIO_PORT_A: - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOA->BSRR = GPIO_BSRR_BS_8; - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER10_Msk) | (1 << GPIO_MODER_MODER10_Pos); - GPIOA->BSRR = GPIO_BSRR_BS_10; - break; - case PBIO_PORT_B: - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOA->BSRR = GPIO_BSRR_BS_9; - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER11_Msk) | (1 << GPIO_MODER_MODER11_Pos); - GPIOA->BSRR = GPIO_BSRR_BS_11; - break; - case PBIO_PORT_C: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_6; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_8; - break; - case PBIO_PORT_D: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_7; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_9; - break; - default: - break; + case PBIO_PORT_A: + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOA->BSRR = GPIO_BSRR_BS_8; + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER10_Msk) | (1 << GPIO_MODER_MODER10_Pos); + GPIOA->BSRR = GPIO_BSRR_BS_10; + break; + case PBIO_PORT_B: + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOA->BSRR = GPIO_BSRR_BS_9; + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER11_Msk) | (1 << GPIO_MODER_MODER11_Pos); + GPIOA->BSRR = GPIO_BSRR_BS_11; + break; + case PBIO_PORT_C: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_6; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_8; + break; + case PBIO_PORT_D: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_7; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_9; + break; + default: + break; } } static void pbdrv_motor_run_fwd(pbio_port_t port, int16_t duty_cycle) { // one pin as out, high and the other as PWM switch (port) { - case PBIO_PORT_A: - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOA->BSRR = GPIO_BSRR_BS_8; - TIM1->CCR3 = 10000 - duty_cycle; - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER10_Msk) | (2 << GPIO_MODER_MODER10_Pos); - break; - case PBIO_PORT_B: - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER11_Msk) | (1 << GPIO_MODER_MODER11_Pos); - GPIOA->BSRR = GPIO_BSRR_BS_11; - TIM1->CCR2 = 10000 - duty_cycle; - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER9_Msk) | (2 << GPIO_MODER_MODER9_Pos); - break; - case PBIO_PORT_C: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_6; - TIM3->CCR3 = 10000 - duty_cycle; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (2 << GPIO_MODER_MODER8_Pos); - break; - case PBIO_PORT_D: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_9; - TIM3->CCR2 = 10000 - duty_cycle; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (2 << GPIO_MODER_MODER7_Pos); - break; - default: - break; + case PBIO_PORT_A: + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOA->BSRR = GPIO_BSRR_BS_8; + TIM1->CCR3 = 10000 - duty_cycle; + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER10_Msk) | (2 << GPIO_MODER_MODER10_Pos); + break; + case PBIO_PORT_B: + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER11_Msk) | (1 << GPIO_MODER_MODER11_Pos); + GPIOA->BSRR = GPIO_BSRR_BS_11; + TIM1->CCR2 = 10000 - duty_cycle; + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER9_Msk) | (2 << GPIO_MODER_MODER9_Pos); + break; + case PBIO_PORT_C: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (1 << GPIO_MODER_MODER6_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_6; + TIM3->CCR3 = 10000 - duty_cycle; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (2 << GPIO_MODER_MODER8_Pos); + break; + case PBIO_PORT_D: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_9; + TIM3->CCR2 = 10000 - duty_cycle; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (2 << GPIO_MODER_MODER7_Pos); + break; + default: + break; } } static void pbdrv_motor_run_rev(pbio_port_t port, int16_t duty_cycle) { // one pin as out, high and the other as PWM switch (port) { - case PBIO_PORT_A: - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER10_Msk) | (1 << GPIO_MODER_MODER10_Pos); - GPIOA->BSRR = GPIO_BSRR_BS_10; - TIM1->CCR1 = 10000 + duty_cycle; - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER8_Msk) | (2 << GPIO_MODER_MODER8_Pos); - break; - case PBIO_PORT_B: - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); - GPIOA->BSRR = GPIO_BSRR_BS_9; - TIM1->CCR4 = 10000 + duty_cycle; - GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER11_Msk) | (2 << GPIO_MODER_MODER11_Pos); - break; - case PBIO_PORT_C: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_8; - TIM3->CCR1 = 10000 + duty_cycle; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (2 << GPIO_MODER_MODER6_Pos); - break; - case PBIO_PORT_D: - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); - GPIOC->BSRR = GPIO_BSRR_BS_7; - TIM3->CCR4 = 10000 + duty_cycle; - GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (2 << GPIO_MODER_MODER9_Pos); - break; - default: - break; + case PBIO_PORT_A: + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER10_Msk) | (1 << GPIO_MODER_MODER10_Pos); + GPIOA->BSRR = GPIO_BSRR_BS_10; + TIM1->CCR1 = 10000 + duty_cycle; + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER8_Msk) | (2 << GPIO_MODER_MODER8_Pos); + break; + case PBIO_PORT_B: + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER9_Msk) | (1 << GPIO_MODER_MODER9_Pos); + GPIOA->BSRR = GPIO_BSRR_BS_9; + TIM1->CCR4 = 10000 + duty_cycle; + GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER11_Msk) | (2 << GPIO_MODER_MODER11_Pos); + break; + case PBIO_PORT_C: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER8_Msk) | (1 << GPIO_MODER_MODER8_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_8; + TIM3->CCR1 = 10000 + duty_cycle; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER6_Msk) | (2 << GPIO_MODER_MODER6_Pos); + break; + case PBIO_PORT_D: + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER7_Msk) | (1 << GPIO_MODER_MODER7_Pos); + GPIOC->BSRR = GPIO_BSRR_BS_7; + TIM3->CCR4 = 10000 + duty_cycle; + GPIOC->MODER = (GPIOC->MODER & ~GPIO_MODER_MODER9_Msk) | (2 << GPIO_MODER_MODER9_Pos); + break; + default: + break; } } @@ -287,8 +287,7 @@ pbio_error_t pbdrv_motor_get_id(pbio_port_t port, pbio_iodev_type_id_t *id) { if (port == PBIO_PORT_A || port == PBIO_PORT_B) { *id = PBIO_IODEV_TYPE_ID_MOVE_HUB_MOTOR; return PBIO_SUCCESS; - } - else if (port == PBIO_PORT_C || port == PBIO_PORT_D) { + } else if (port == PBIO_PORT_C || port == PBIO_PORT_D) { pbio_iodev_t *iodev; iodev = get_iodev(port); diff --git a/lib/pbio/drv/nxt/motor.c b/lib/pbio/drv/nxt/motor.c index d67e6a0ad..f5f05ca7a 100644 --- a/lib/pbio/drv/nxt/motor.c +++ b/lib/pbio/drv/nxt/motor.c @@ -12,7 +12,8 @@ #include -inline void _pbdrv_motor_init(void) { } +inline void _pbdrv_motor_init(void) { +} #if PBIO_CONFIG_ENABLE_DEINIT void _pbdrv_motor_deinit(void) { @@ -31,7 +32,7 @@ pbio_error_t pbdrv_motor_set_duty_cycle(pbio_port_t port, int16_t duty_cycle) { if (port < PBDRV_CONFIG_FIRST_MOTOR_PORT || port > PBDRV_CONFIG_LAST_MOTOR_PORT) { return PBIO_ERROR_INVALID_PORT; } - nxt_motor_set_speed(port - PBDRV_CONFIG_FIRST_MOTOR_PORT, duty_cycle/100, 1); + nxt_motor_set_speed(port - PBDRV_CONFIG_FIRST_MOTOR_PORT, duty_cycle / 100, 1); return PBIO_SUCCESS; } diff --git a/lib/pbio/drv/prime_hub/motor.c b/lib/pbio/drv/prime_hub/motor.c index 361b146c8..0c999c6ae 100644 --- a/lib/pbio/drv/prime_hub/motor.c +++ b/lib/pbio/drv/prime_hub/motor.c @@ -25,7 +25,7 @@ typedef struct { } pbdrv_motor_data_t; static pbdrv_motor_data_t -platform_data[PBDRV_CONFIG_NUM_MOTOR_CONTROLLER] = { + platform_data[PBDRV_CONFIG_NUM_MOTOR_CONTROLLER] = { { .pin1_gpio.bank = GPIOE, .pin1_gpio.pin = 9, @@ -97,17 +97,17 @@ void _pbdrv_motor_init(void) { htim1.Instance = TIM1; htim1.Init.Prescaler = 8 - 1; - htim1.Init.Period = 10000 -1; + htim1.Init.Period = 10000 - 1; HAL_TIM_Base_Init(&htim1); htim3.Instance = TIM3; htim3.Init.Prescaler = 8 - 1; - htim3.Init.Period = 10000 -1; + htim3.Init.Period = 10000 - 1; HAL_TIM_Base_Init(&htim3); htim4.Instance = TIM4; htim4.Init.Prescaler = 8 - 1; - htim4.Init.Period = 10000 -1; + htim4.Init.Period = 10000 - 1; HAL_TIM_Base_Init(&htim4); tim_oc_init.OCMode = TIM_OCMODE_PWM1; diff --git a/lib/pbio/drv/uart/uart_stm32_hal.c b/lib/pbio/drv/uart/uart_stm32_hal.c index bc031836d..80df4a1b3 100644 --- a/lib/pbio/drv/uart/uart_stm32_hal.c +++ b/lib/pbio/drv/uart/uart_stm32_hal.c @@ -79,8 +79,7 @@ pbio_error_t pbdrv_uart_read_end(pbdrv_uart_dev_t *uart_dev) { if (err != PBIO_ERROR_AGAIN) { etimer_stop(&uart->rx_timer); - } - else if (etimer_expired(&uart->rx_timer)) { + } else if (etimer_expired(&uart->rx_timer)) { // NB: This function can be blocking when using DMA - if we switch to // DMA, the timout will need to be reworked. HAL_UART_AbortReceive(&uart->huart); @@ -120,8 +119,7 @@ pbio_error_t pbdrv_uart_write_end(pbdrv_uart_dev_t *uart_dev) { if (err != PBIO_ERROR_AGAIN) { etimer_stop(&uart->tx_timer); - } - else if (etimer_expired(&uart->tx_timer)) { + } else if (etimer_expired(&uart->tx_timer)) { // NB: This function can be blocking when using DMA - if we switch to // DMA, the timout will need to be reworked. HAL_UART_AbortTransmit(&uart->huart); diff --git a/lib/pbio/drv/uart/uart_stm32_hal.h b/lib/pbio/drv/uart/uart_stm32_hal.h index 33e41f185..e30e5e99a 100644 --- a/lib/pbio/drv/uart/uart_stm32_hal.h +++ b/lib/pbio/drv/uart/uart_stm32_hal.h @@ -14,7 +14,7 @@ typedef struct { } pbdrv_uart_stm32_hal_platform_data_t; extern const pbdrv_uart_stm32_hal_platform_data_t -pbdrv_uart_stm32_hal_platform_data[PBDRV_CONFIG_UART_STM32_HAL_NUM_UART]; + pbdrv_uart_stm32_hal_platform_data[PBDRV_CONFIG_UART_STM32_HAL_NUM_UART]; void pbdrv_uart_stm32_hal_handle_irq(uint8_t id); diff --git a/lib/pbio/drv/uart/uart_stm32f0.c b/lib/pbio/drv/uart/uart_stm32f0.c index 1bea28e47..82f305a9e 100644 --- a/lib/pbio/drv/uart/uart_stm32f0.c +++ b/lib/pbio/drv/uart/uart_stm32f0.c @@ -70,7 +70,7 @@ pbio_error_t pbdrv_uart_read_begin(pbdrv_uart_dev_t *uart_dev, uint8_t *msg, uin pbdrv_uart_t *uart = PBIO_CONTAINER_OF(uart_dev, pbdrv_uart_t, uart_dev); if (!msg || !length) { - return PBIO_ERROR_INVALID_ARG; + return PBIO_ERROR_INVALID_ARG; } if (uart->rx_buf) { @@ -101,8 +101,7 @@ pbio_error_t pbdrv_uart_read_end(pbdrv_uart_dev_t *uart_dev) { if (err != PBIO_ERROR_AGAIN) { etimer_stop(&uart->rx_timer); uart->rx_buf = NULL; - } - else if (etimer_expired(&uart->rx_timer)) { + } else if (etimer_expired(&uart->rx_timer)) { err = PBIO_ERROR_TIMEDOUT; uart->rx_buf = NULL; } @@ -120,7 +119,7 @@ pbio_error_t pbdrv_uart_write_begin(pbdrv_uart_dev_t *uart_dev, uint8_t *msg, ui pbdrv_uart_t *uart = PBIO_CONTAINER_OF(uart_dev, pbdrv_uart_t, uart_dev); if (!msg || !length) { - return PBIO_ERROR_INVALID_ARG; + return PBIO_ERROR_INVALID_ARG; } if (uart->tx_buf) { @@ -151,8 +150,7 @@ pbio_error_t pbdrv_uart_write_end(pbdrv_uart_dev_t *uart_dev) { if (err != PBIO_ERROR_AGAIN) { etimer_stop(&uart->tx_timer); uart->tx_buf = NULL; - } - else if (etimer_expired(&uart->tx_timer)) { + } else if (etimer_expired(&uart->tx_timer)) { uart->USART->CR1 &= ~(USART_CR1_TXEIE | USART_CR1_TCIE); err = PBIO_ERROR_TIMEDOUT; uart->tx_buf = NULL; diff --git a/lib/pbio/include/pbdrv/battery.h b/lib/pbio/include/pbdrv/battery.h index 63f1ca8fe..63dd8f089 100644 --- a/lib/pbio/include/pbdrv/battery.h +++ b/lib/pbio/include/pbdrv/battery.h @@ -36,8 +36,10 @@ pbio_error_t pbdrv_battery_get_current_now(uint16_t *value); #else // PBDRV_CONFIG_BATTERY -static inline void _pbdrv_battery_poll(uint32_t now) { } -static inline void _pbdrv_battery_deinit(void) { } +static inline void _pbdrv_battery_poll(uint32_t now) { +} +static inline void _pbdrv_battery_deinit(void) { +} static inline pbio_error_t pbdrv_battery_get_voltage_now(uint16_t *value) { *value = 0; return PBIO_ERROR_NOT_SUPPORTED; diff --git a/lib/pbio/include/pbdrv/bluetooth.h b/lib/pbio/include/pbdrv/bluetooth.h index 3c380dcdc..4a7c168c1 100644 --- a/lib/pbio/include/pbdrv/bluetooth.h +++ b/lib/pbio/include/pbdrv/bluetooth.h @@ -29,7 +29,9 @@ pbio_error_t pbdrv_bluetooth_tx(uint8_t c); #else // PBDRV_CONFIG_BLUETOOTH -static inline pbio_error_t pbdrv_bluetooth_tx(uint8_t c) { return PBIO_ERROR_NOT_SUPPORTED; } +static inline pbio_error_t pbdrv_bluetooth_tx(uint8_t c) { + return PBIO_ERROR_NOT_SUPPORTED; +} #endif // PBDRV_CONFIG_BLUETOOTH diff --git a/lib/pbio/include/pbdrv/button.h b/lib/pbio/include/pbdrv/button.h index c39fe1751..63b89a47f 100644 --- a/lib/pbio/include/pbdrv/button.h +++ b/lib/pbio/include/pbdrv/button.h @@ -36,7 +36,8 @@ void _pbdrv_button_init(void); #if PBIO_CONFIG_ENABLE_DEINIT void _pbdrv_button_deinit(void); #else -static inline void _pbdrv_button_deinit(void) { } +static inline void _pbdrv_button_deinit(void) { +} #endif /** @endcond */ @@ -53,8 +54,10 @@ pbio_error_t pbdrv_button_is_pressed(pbio_button_flags_t *pressed); #else -static inline void _pbdrv_button_init(void) { } -static inline void _pbdrv_button_deinit(void) { } +static inline void _pbdrv_button_init(void) { +} +static inline void _pbdrv_button_deinit(void) { +} static inline pbio_error_t pbdrv_button_is_pressed(pbio_button_flags_t *pressed) { *pressed = 0; return PBIO_ERROR_NOT_SUPPORTED; diff --git a/lib/pbio/include/pbdrv/config.h b/lib/pbio/include/pbdrv/config.h index c91944ad1..4e0c21ca6 100644 --- a/lib/pbio/include/pbdrv/config.h +++ b/lib/pbio/include/pbdrv/config.h @@ -84,7 +84,7 @@ #endif // The maximum number of motor pairs -#define PBDRV_CONFIG_NUM_MOTOR_PAIRS (PBDRV_CONFIG_NUM_MOTOR_CONTROLLER/2) +#define PBDRV_CONFIG_NUM_MOTOR_PAIRS (PBDRV_CONFIG_NUM_MOTOR_CONTROLLER / 2) // the pbio_port_t enum value of the first motor port #ifndef PBDRV_CONFIG_FIRST_MOTOR_PORT diff --git a/lib/pbio/include/pbdrv/gpio.h b/lib/pbio/include/pbdrv/gpio.h index edf71d9e6..607039253 100644 --- a/lib/pbio/include/pbdrv/gpio.h +++ b/lib/pbio/include/pbdrv/gpio.h @@ -36,11 +36,17 @@ void pbdrv_gpio_set_pull(const pbdrv_gpio_t *gpio, pbdrv_gpio_pull_t pull); #else // -static inline void pbdrv_gpio_out_low(const pbdrv_gpio_t *gpio) { } -static inline void pbdrv_gpio_out_high(const pbdrv_gpio_t *gpio) { } -static inline uint8_t pbdrv_gpio_input(const pbdrv_gpio_t *gpio) { return 0; } -static inline void pbdrv_gpio_alt(const pbdrv_gpio_t *gpio, uint8_t alt) { } -static inline void pbdrv_gpio_set_pull(const pbdrv_gpio_t *gpio, pbdrv_gpio_pull_t pull) { } +static inline void pbdrv_gpio_out_low(const pbdrv_gpio_t *gpio) { +} +static inline void pbdrv_gpio_out_high(const pbdrv_gpio_t *gpio) { +} +static inline uint8_t pbdrv_gpio_input(const pbdrv_gpio_t *gpio) { + return 0; +} +static inline void pbdrv_gpio_alt(const pbdrv_gpio_t *gpio, uint8_t alt) { +} +static inline void pbdrv_gpio_set_pull(const pbdrv_gpio_t *gpio, pbdrv_gpio_pull_t pull) { +} #endif // PBDRV_CONFIG_GPIO diff --git a/lib/pbio/include/pbdrv/light.h b/lib/pbio/include/pbdrv/light.h index 55b74b969..93a2df819 100644 --- a/lib/pbio/include/pbdrv/light.h +++ b/lib/pbio/include/pbdrv/light.h @@ -35,7 +35,8 @@ void _pbdrv_light_init(void); #if PBIO_CONFIG_ENABLE_DEINIT void _pbdrv_light_deinit(void); #else -static inline void _pbdrv_light_deinit(void) { } +static inline void _pbdrv_light_deinit(void) { +} #endif /** @endcond */ @@ -78,12 +79,14 @@ pbio_error_t pbdrv_light_set_rgb(pbio_port_t port, uint8_t r, uint8_t g, uint8_t * ::PBIO_ERROR_NO_DEV if port is valid but light is not connected */ pbio_error_t pbdrv_light_get_rgb_for_color(pbio_port_t port, pbio_light_color_t color, - uint8_t *r, uint8_t *g, uint8_t *b); + uint8_t *r, uint8_t *g, uint8_t *b); #else -static inline void _pbdrv_light_init(void) { } -static inline void _pbdrv_light_deinit(void) { } +static inline void _pbdrv_light_init(void) { +} +static inline void _pbdrv_light_deinit(void) { +} static inline pbio_error_t pbdrv_light_set_rgb(pbio_port_t port, uint8_t r, uint8_t g, uint8_t b) { return PBIO_ERROR_NOT_SUPPORTED; } diff --git a/lib/pbio/include/pbdrv/motor.h b/lib/pbio/include/pbdrv/motor.h index 93c010512..0cff5bccf 100644 --- a/lib/pbio/include/pbdrv/motor.h +++ b/lib/pbio/include/pbdrv/motor.h @@ -39,7 +39,8 @@ void _pbdrv_motor_init(void); #if PBIO_CONFIG_ENABLE_DEINIT void _pbdrv_motor_deinit(void); #else -static inline void _pbdrv_motor_deinit(void) { } +static inline void _pbdrv_motor_deinit(void) { +} #endif /** @endcond */ @@ -91,8 +92,10 @@ pbio_error_t pbdrv_motor_setup(pbio_port_t port, bool is_servo); #else -static inline void _pbdrv_motor_init(void) { } -static inline void _pbdrv_motor_deinit(void) { } +static inline void _pbdrv_motor_init(void) { +} +static inline void _pbdrv_motor_deinit(void) { +} static inline pbio_error_t pbdrv_motor_coast(pbio_port_t port) { return PBIO_ERROR_NOT_SUPPORTED; } diff --git a/lib/pbio/include/pbdrv/uart.h b/lib/pbio/include/pbdrv/uart.h index 1c5ef01c6..f06b04e99 100644 --- a/lib/pbio/include/pbdrv/uart.h +++ b/lib/pbio/include/pbdrv/uart.h @@ -46,13 +46,25 @@ static inline pbio_error_t pbdrv_uart_get(uint8_t id, pbdrv_uart_dev_t **uart_de *uart_dev = NULL; return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbdrv_uart_set_baud_rate(pbdrv_uart_dev_t *uart, uint32_t baud) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbdrv_uart_read_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbdrv_uart_read_end(pbdrv_uart_dev_t *uart) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline void pbdrv_uart_read_cancel(pbdrv_uart_dev_t *uart) { } -static inline pbio_error_t pbdrv_uart_write_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbdrv_uart_write_end(pbdrv_uart_dev_t *uart) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline void pbdrv_uart_write_cancel(pbdrv_uart_dev_t *uart) { } +static inline pbio_error_t pbdrv_uart_set_baud_rate(pbdrv_uart_dev_t *uart, uint32_t baud) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbdrv_uart_read_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbdrv_uart_read_end(pbdrv_uart_dev_t *uart) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline void pbdrv_uart_read_cancel(pbdrv_uart_dev_t *uart) { +} +static inline pbio_error_t pbdrv_uart_write_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbdrv_uart_write_end(pbdrv_uart_dev_t *uart) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline void pbdrv_uart_write_cancel(pbdrv_uart_dev_t *uart) { +} #endif // PBDRV_CONFIG_UART diff --git a/lib/pbio/include/pbio/control.h b/lib/pbio/include/pbio/control.h index 521cb6b03..ad2e4405a 100644 --- a/lib/pbio/include/pbio/control.h +++ b/lib/pbio/include/pbio/control.h @@ -46,11 +46,11 @@ typedef enum { // Maneuver-specific function that returns true if maneuver is done, based on current state typedef bool (*pbio_control_on_target_t)(pbio_trajectory_t *trajectory, - pbio_control_settings_t *settings, - int32_t time, - int32_t count, - int32_t rate, - bool stalled); + pbio_control_settings_t *settings, + int32_t time, + int32_t count, + int32_t rate, + bool stalled); // Functions to check whether motion is done pbio_control_on_target_t pbio_control_on_target_always; diff --git a/lib/pbio/include/pbio/dcmotor.h b/lib/pbio/include/pbio/dcmotor.h index 12b600e3a..f4af1ed30 100644 --- a/lib/pbio/include/pbio/dcmotor.h +++ b/lib/pbio/include/pbio/dcmotor.h @@ -44,14 +44,26 @@ pbio_error_t pbio_dcmotor_set_duty_cycle_usr(pbio_dcmotor_t *dcmotor, int32_t du #else -static inline pbio_error_t pbio_dcmotor_get(pbio_port_t port, pbio_dcmotor_t **dcmotor, pbio_direction_t direction, bool is_servo) { return PBIO_ERROR_NOT_SUPPORTED; } - -static inline pbio_error_t pbio_dcmotor_get_state(pbio_dcmotor_t *dcmotor, pbio_passivity_t *state, int32_t *duty_now) { return PBIO_ERROR_NOT_SUPPORTED; } - -static inline pbio_error_t pbio_dcmotor_coast(pbio_dcmotor_t *dcmotor) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_dcmotor_brake(pbio_dcmotor_t *dcmotor) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_dcmotor_set_duty_cycle_sys(pbio_dcmotor_t *dcmotor, int32_t duty_steps) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_dcmotor_set_duty_cycle_usr(pbio_dcmotor_t *dcmotor, int32_t duty_steps) { return PBIO_ERROR_NOT_SUPPORTED; } +static inline pbio_error_t pbio_dcmotor_get(pbio_port_t port, pbio_dcmotor_t **dcmotor, pbio_direction_t direction, bool is_servo) { + return PBIO_ERROR_NOT_SUPPORTED; +} + +static inline pbio_error_t pbio_dcmotor_get_state(pbio_dcmotor_t *dcmotor, pbio_passivity_t *state, int32_t *duty_now) { + return PBIO_ERROR_NOT_SUPPORTED; +} + +static inline pbio_error_t pbio_dcmotor_coast(pbio_dcmotor_t *dcmotor) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_dcmotor_brake(pbio_dcmotor_t *dcmotor) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_dcmotor_set_duty_cycle_sys(pbio_dcmotor_t *dcmotor, int32_t duty_steps) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_dcmotor_set_duty_cycle_usr(pbio_dcmotor_t *dcmotor, int32_t duty_steps) { + return PBIO_ERROR_NOT_SUPPORTED; +} #endif // PBIO_CONFIG_DCMOTOR diff --git a/lib/pbio/include/pbio/integrator.h b/lib/pbio/include/pbio/integrator.h index f46cff90c..3c97f9668 100644 --- a/lib/pbio/include/pbio/integrator.h +++ b/lib/pbio/include/pbio/integrator.h @@ -22,12 +22,12 @@ void pbio_rate_integrator_resume(pbio_rate_integrator_t *itg, int32_t time_now, void pbio_rate_integrator_reset(pbio_rate_integrator_t *itg, int32_t time_now, int32_t count, int32_t count_ref); void pbio_rate_integrator_get_errors(pbio_rate_integrator_t *itg, - int32_t rate, - int32_t rate_ref, - int32_t count, - int32_t count_ref, - int32_t *rate_err, - int32_t *rate_err_integral); + int32_t rate, + int32_t rate_ref, + int32_t count, + int32_t count_ref, + int32_t *rate_err, + int32_t *rate_err_integral); bool pbio_rate_integrator_stalled(pbio_rate_integrator_t *itg, int32_t time_now, int32_t rate, int32_t time_stall, int32_t rate_stall); diff --git a/lib/pbio/include/pbio/iodev.h b/lib/pbio/include/pbio/iodev.h index 477994216..fc3f1e4fa 100644 --- a/lib/pbio/include/pbio/iodev.h +++ b/lib/pbio/include/pbio/iodev.h @@ -130,29 +130,29 @@ typedef enum { // NXT Devices - PBIO_IODEV_TYPE_ID_NXT_TOUCH_SENSOR , /**< MINDSTORMS NXT Touch Sensor */ - PBIO_IODEV_TYPE_ID_NXT_LIGHT_SENSOR , /**< MINDSTORMS NXT Light Sensor */ - PBIO_IODEV_TYPE_ID_NXT_SOUND_SENSOR , /**< MINDSTORMS NXT Sound Sensor */ - PBIO_IODEV_TYPE_ID_NXT_COLOR_SENSOR , /**< MINDSTORMS NXT Color Sensor */ - PBIO_IODEV_TYPE_ID_NXT_ULTRASONIC_SENSOR , /**< MINDSTORMS NXT Ultrasonic Sensor */ - PBIO_IODEV_TYPE_ID_NXT_TEMPERATURE_SENSOR , /**< MINDSTORMS NXT Ultrasonic Sensor */ - PBIO_IODEV_TYPE_ID_NXT_ENERGY_METER , /**< MINDSTORMS NXT Energy Meter */ + PBIO_IODEV_TYPE_ID_NXT_TOUCH_SENSOR, /**< MINDSTORMS NXT Touch Sensor */ + PBIO_IODEV_TYPE_ID_NXT_LIGHT_SENSOR, /**< MINDSTORMS NXT Light Sensor */ + PBIO_IODEV_TYPE_ID_NXT_SOUND_SENSOR, /**< MINDSTORMS NXT Sound Sensor */ + PBIO_IODEV_TYPE_ID_NXT_COLOR_SENSOR, /**< MINDSTORMS NXT Color Sensor */ + PBIO_IODEV_TYPE_ID_NXT_ULTRASONIC_SENSOR, /**< MINDSTORMS NXT Ultrasonic Sensor */ + PBIO_IODEV_TYPE_ID_NXT_TEMPERATURE_SENSOR, /**< MINDSTORMS NXT Ultrasonic Sensor */ + PBIO_IODEV_TYPE_ID_NXT_ENERGY_METER, /**< MINDSTORMS NXT Energy Meter */ // EV3 Devices - PBIO_IODEV_TYPE_ID_EV3_TOUCH_SENSOR , /**< MINDSTORMS EV3 Touch Sensor */ - PBIO_IODEV_TYPE_ID_EV3_LARGE_MOTOR , /**< MINDSTORMS EV3 Large Motor */ - PBIO_IODEV_TYPE_ID_EV3_MEDIUM_MOTOR , /**< MINDSTORMS EV3 Medium Motor */ + PBIO_IODEV_TYPE_ID_EV3_TOUCH_SENSOR, /**< MINDSTORMS EV3 Touch Sensor */ + PBIO_IODEV_TYPE_ID_EV3_LARGE_MOTOR, /**< MINDSTORMS EV3 Large Motor */ + PBIO_IODEV_TYPE_ID_EV3_MEDIUM_MOTOR, /**< MINDSTORMS EV3 Medium Motor */ // ev3dev devices - PBIO_IODEV_TYPE_ID_EV3DEV_DC_MOTOR , /**< generic ev3dev rcx-motor */ - PBIO_IODEV_TYPE_ID_EV3DEV_LEGO_SENSOR , /**< generic ev3dev-supported sensor */ + PBIO_IODEV_TYPE_ID_EV3DEV_DC_MOTOR, /**< generic ev3dev rcx-motor */ + PBIO_IODEV_TYPE_ID_EV3DEV_LEGO_SENSOR, /**< generic ev3dev-supported sensor */ // Generic & Custom devices - PBIO_IODEV_TYPE_ID_NXT_ANALOG , /**< MINDSTORMS NXT-style Analog Sensor */ - PBIO_IODEV_TYPE_ID_NXT_I2C , /**< MINDSTORMS NXT-style I2C Sensor */ - PBIO_IODEV_TYPE_ID_CUSTOM_I2C , /**< Custom I2C Sensor */ - PBIO_IODEV_TYPE_ID_LUMP_UART , /**< Device with LEGO UART Messaging Protocol */ - PBIO_IODEV_TYPE_ID_CUSTOM_UART , /**< Custom UART Sensor */ + PBIO_IODEV_TYPE_ID_NXT_ANALOG, /**< MINDSTORMS NXT-style Analog Sensor */ + PBIO_IODEV_TYPE_ID_NXT_I2C, /**< MINDSTORMS NXT-style I2C Sensor */ + PBIO_IODEV_TYPE_ID_CUSTOM_I2C, /**< Custom I2C Sensor */ + PBIO_IODEV_TYPE_ID_LUMP_UART, /**< Device with LEGO UART Messaging Protocol */ + PBIO_IODEV_TYPE_ID_CUSTOM_UART, /**< Custom UART Sensor */ } pbio_iodev_type_id_t; diff --git a/lib/pbio/include/pbio/light.h b/lib/pbio/include/pbio/light.h index 2774cb706..cc77e29eb 100644 --- a/lib/pbio/include/pbio/light.h +++ b/lib/pbio/include/pbio/light.h @@ -82,9 +82,13 @@ void _pbio_light_set_user_mode(bool user_mode); /** @endcond */ #else -static inline void _pbio_light_poll(uint32_t now) { } -static inline void _pbio_light_set_user_mode(bool user_mode) { } -static inline pbio_error_t _pbio_light_on(pbio_port_t port, pbio_light_color_t color, pbio_light_pattern_t pattern) { return PBIO_SUCCESS; } +static inline void _pbio_light_poll(uint32_t now) { +} +static inline void _pbio_light_set_user_mode(bool user_mode) { +} +static inline pbio_error_t _pbio_light_on(pbio_port_t port, pbio_light_color_t color, pbio_light_pattern_t pattern) { + return PBIO_SUCCESS; +} #endif // PBDRV_CONFIG_LIGHT /** @cond */ diff --git a/lib/pbio/include/pbio/main.h b/lib/pbio/include/pbio/main.h index 1d6dc6579..7f3f785b8 100644 --- a/lib/pbio/include/pbio/main.h +++ b/lib/pbio/include/pbio/main.h @@ -12,7 +12,8 @@ int pbio_do_one_event(void); #if PBIO_CONFIG_ENABLE_DEINIT void pbio_deinit(void); #else -static inline void pbio_deinit(void) { } +static inline void pbio_deinit(void) { +} #endif #endif // _PBIO_MAIN_H_ diff --git a/lib/pbio/include/pbio/motorpoll.h b/lib/pbio/include/pbio/motorpoll.h index aeea4786d..34944bdde 100644 --- a/lib/pbio/include/pbio/motorpoll.h +++ b/lib/pbio/include/pbio/motorpoll.h @@ -23,8 +23,10 @@ void _pbio_motorpoll_poll(void); #else -static inline void _pbio_motorpoll_reset_all(void) { } -static inline void _pbio_motorpoll_poll(void) { } +static inline void _pbio_motorpoll_reset_all(void) { +} +static inline void _pbio_motorpoll_poll(void) { +} #endif // PBDRV_CONFIG_NUM_MOTOR_CONTROLLER diff --git a/lib/pbio/include/pbio/port.h b/lib/pbio/include/pbio/port.h index 1db12b447..3bf39a1af 100644 --- a/lib/pbio/include/pbio/port.h +++ b/lib/pbio/include/pbio/port.h @@ -23,36 +23,36 @@ typedef enum { PBIO_PORT_SELF = '@', /**< Virtual port for the programmable brick itself */ -#if PBDRV_CONFIG_HAS_PORT_A + #if PBDRV_CONFIG_HAS_PORT_A PBIO_PORT_A = 'A', /**< I/O port labeled as "A" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_B + #endif + #if PBDRV_CONFIG_HAS_PORT_B PBIO_PORT_B = 'B', /**< I/O port labeled as "B" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_C + #endif + #if PBDRV_CONFIG_HAS_PORT_C PBIO_PORT_C = 'C', /**< I/O port labeled as "C" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_D + #endif + #if PBDRV_CONFIG_HAS_PORT_D PBIO_PORT_D = 'D', /**< I/O port labeled as "D" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_E + #endif + #if PBDRV_CONFIG_HAS_PORT_E PBIO_PORT_E = 'E', /**< I/O port labeled as "C" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_F + #endif + #if PBDRV_CONFIG_HAS_PORT_F PBIO_PORT_F = 'F', /**< I/O port labeled as "F" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_1 + #endif + #if PBDRV_CONFIG_HAS_PORT_1 PBIO_PORT_1 = '1', /**< I/O port labeled as "1" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_2 + #endif + #if PBDRV_CONFIG_HAS_PORT_2 PBIO_PORT_2 = '2', /**< I/O port labeled as "2" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_3 + #endif + #if PBDRV_CONFIG_HAS_PORT_3 PBIO_PORT_3 = '3', /**< I/O port labeled as "3" */ -#endif -#if PBDRV_CONFIG_HAS_PORT_4 + #endif + #if PBDRV_CONFIG_HAS_PORT_4 PBIO_PORT_4 = '4', /**< I/O port labeled as "4" */ -#endif + #endif } pbio_port_t; /** @}*/ diff --git a/lib/pbio/include/pbio/serial.h b/lib/pbio/include/pbio/serial.h index e8854eb23..381de4b9d 100644 --- a/lib/pbio/include/pbio/serial.h +++ b/lib/pbio/include/pbio/serial.h @@ -24,10 +24,20 @@ pbio_error_t pbio_serial_clear(pbio_serial_t *ser); #else // PBIO_CONFIG_SERIAL -static inline pbio_error_t pbio_serial_get(pbio_serial_t **_ser, pbio_port_t port, int baudrate, int timeout) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_serial_write(pbio_serial_t *ser, const void *buf, size_t count) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_serial_in_waiting(pbio_serial_t *ser, size_t *waiting) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_serial_read(pbio_serial_t *ser, uint8_t *buf, size_t count) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_serial_clear(pbio_serial_t *ser) { return PBIO_ERROR_NOT_SUPPORTED; } +static inline pbio_error_t pbio_serial_get(pbio_serial_t **_ser, pbio_port_t port, int baudrate, int timeout) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_serial_write(pbio_serial_t *ser, const void *buf, size_t count) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_serial_in_waiting(pbio_serial_t *ser, size_t *waiting) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_serial_read(pbio_serial_t *ser, uint8_t *buf, size_t count) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_serial_clear(pbio_serial_t *ser) { + return PBIO_ERROR_NOT_SUPPORTED; +} #endif // PBIO_CONFIG_SERIAL diff --git a/lib/pbio/include/pbio/sound.h b/lib/pbio/include/pbio/sound.h index 10253ba76..878674cfc 100644 --- a/lib/pbio/include/pbio/sound.h +++ b/lib/pbio/include/pbio/sound.h @@ -20,9 +20,17 @@ pbio_error_t pbio_sound_set_volume(pbio_sound_t *sound, uint32_t volume); #else -static inline pbio_error_t pbio_sound_get(pbio_sound_t **_sound) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_sound_beep(pbio_sound_t *sound, uint32_t freq, int32_t duration) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_sound_play_file(pbio_sound_t *sound, const char *path) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_sound_set_volume(pbio_sound_t *sound, uint32_t volume) { return PBIO_ERROR_NOT_SUPPORTED; } +static inline pbio_error_t pbio_sound_get(pbio_sound_t **_sound) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_sound_beep(pbio_sound_t *sound, uint32_t freq, int32_t duration) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_sound_play_file(pbio_sound_t *sound, const char *path) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_sound_set_volume(pbio_sound_t *sound, uint32_t volume) { + return PBIO_ERROR_NOT_SUPPORTED; +} #endif diff --git a/lib/pbio/include/pbio/tacho.h b/lib/pbio/include/pbio/tacho.h index cc7f3a0ab..0eca34616 100644 --- a/lib/pbio/include/pbio/tacho.h +++ b/lib/pbio/include/pbio/tacho.h @@ -26,13 +26,25 @@ pbio_error_t pbio_tacho_get_angular_rate(pbio_tacho_t *tacho, int32_t *angular_r #else -static inline pbio_error_t pbio_tacho_get(pbio_port_t port, pbio_tacho_t **tacho, pbio_direction_t direction, fix16_t gear_ratio) { return PBIO_ERROR_NOT_SUPPORTED; } - -static inline pbio_error_t pbio_tacho_get_count(pbio_tacho_t *tacho, int32_t *count) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_tacho_get_angle(pbio_tacho_t *tacho, int32_t *angle) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_tacho_reset_angle(pbio_tacho_t *tacho, int32_t reset_angle, bool reset_to_abs) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_tacho_get_rate(pbio_tacho_t *tacho, int32_t *encoder_rate) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbio_tacho_get_angular_rate(pbio_tacho_t *tacho, int32_t *angular_rate) { return PBIO_ERROR_NOT_SUPPORTED; } +static inline pbio_error_t pbio_tacho_get(pbio_port_t port, pbio_tacho_t **tacho, pbio_direction_t direction, fix16_t gear_ratio) { + return PBIO_ERROR_NOT_SUPPORTED; +} + +static inline pbio_error_t pbio_tacho_get_count(pbio_tacho_t *tacho, int32_t *count) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_tacho_get_angle(pbio_tacho_t *tacho, int32_t *angle) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_tacho_reset_angle(pbio_tacho_t *tacho, int32_t reset_angle, bool reset_to_abs) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_tacho_get_rate(pbio_tacho_t *tacho, int32_t *encoder_rate) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline pbio_error_t pbio_tacho_get_angular_rate(pbio_tacho_t *tacho, int32_t *angular_rate) { + return PBIO_ERROR_NOT_SUPPORTED; +} #endif // PBIO_CONFIG_TACHO diff --git a/lib/pbio/include/pbio/trajectory.h b/lib/pbio/include/pbio/trajectory.h index e6b503905..562f6cc00 100644 --- a/lib/pbio/include/pbio/trajectory.h +++ b/lib/pbio/include/pbio/trajectory.h @@ -17,17 +17,17 @@ #define US_PER_SECOND (1000000) #define DURATION_FOREVER (-1) -#define DURATION_MAX_S (30*60) +#define DURATION_MAX_S (30 * 60) #define min(a, b) ((a) < (b) ? (a) : (b)) #define max(a, b) ((a) > (b) ? (a) : (b)) // Macro to evaluate b*t/US_PER_SECOND in two steps to avoid excessive round-off errors and overflows. -#define timest(b, t) ((b * ((t)/US_PER_MS))/MS_PER_SECOND) +#define timest(b, t) ((b * ((t) / US_PER_MS)) / MS_PER_SECOND) // Same trick to evaluate formulas of the form 1/2*b*t^2/US_PER_SECOND^2 -#define timest2(b, t) ((timest(timest(b, (t)),(t)))/2) +#define timest2(b, t) ((timest(timest(b, (t)),(t))) / 2) // Macro to evaluate division of speed by acceleration (w/a), yielding time, in the appropriate units -#define wdiva(w, a) ((((w)*US_PER_MS)/a)*MS_PER_SECOND) +#define wdiva(w, a) ((((w) * US_PER_MS) / a) * MS_PER_SECOND) /** * Motor trajectory parameters for an ideal maneuver without disturbances diff --git a/lib/pbio/include/pbsys/sys.h b/lib/pbio/include/pbsys/sys.h index acb87eba5..a27c4ab4a 100644 --- a/lib/pbio/include/pbsys/sys.h +++ b/lib/pbio/include/pbsys/sys.h @@ -102,16 +102,23 @@ void pbsys_power_off(void) __attribute__((noreturn)); #else // PBIO_CONFIG_ENABLE_SYS -static inline void pbsys_prepare_user_program(const pbsys_user_program_callbacks_t *callbacks) { } -static inline void pbsys_unprepare_user_program(void) { } +static inline void pbsys_prepare_user_program(const pbsys_user_program_callbacks_t *callbacks) { +} +static inline void pbsys_unprepare_user_program(void) { +} static inline pbio_error_t pbsys_stdin_get_char(uint8_t *c) { *c = 0; return PBIO_ERROR_NOT_SUPPORTED; } -static inline pbio_error_t pbsys_stdout_put_char(uint8_t c) { return PBIO_ERROR_NOT_SUPPORTED; } -static inline void pbsys_reset(void) { } -static inline void pbsys_reboot(bool fw_update) { } -static inline void pbsys_power_off(void) { } +static inline pbio_error_t pbsys_stdout_put_char(uint8_t c) { + return PBIO_ERROR_NOT_SUPPORTED; +} +static inline void pbsys_reset(void) { +} +static inline void pbsys_reboot(bool fw_update) { +} +static inline void pbsys_power_off(void) { +} #endif // PBIO_CONFIG_ENABLE_SYS diff --git a/lib/pbio/platform/city_hub/platform.c b/lib/pbio/platform/city_hub/platform.c index 8bf543040..beb26987d 100644 --- a/lib/pbio/platform/city_hub/platform.c +++ b/lib/pbio/platform/city_hub/platform.c @@ -15,8 +15,8 @@ const pbdrv_button_gpio_platform_t pbdrv_button_gpio_platform[PBDRV_CONFIG_BUTTON_GPIO_NUM_BUTTON] = { [0] = { - .gpio = { .bank = GPIOC, .pin = 13 }, - .pull = PBDRV_GPIO_PULL_UP, + .gpio = { .bank = GPIOC, .pin = 13 }, + .pull = PBDRV_GPIO_PULL_UP, .button = PBIO_BUTTON_CENTER, .active_low = true, } @@ -24,22 +24,22 @@ const pbdrv_button_gpio_platform_t pbdrv_button_gpio_platform[PBDRV_CONFIG_BUTTO // Port A - USART3 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_0 = { - .id1 = { .bank = GPIOB, .pin = 1 }, - .id2 = { .bank = GPIOC, .pin = 3 }, - .uart_buf = { .bank = GPIOB, .pin = 5 }, - .uart_tx = { .bank = GPIOC, .pin = 4 }, - .uart_rx = { .bank = GPIOC, .pin = 5 }, - .alt = 1, + .id1 = { .bank = GPIOB, .pin = 1 }, + .id2 = { .bank = GPIOC, .pin = 3 }, + .uart_buf = { .bank = GPIOB, .pin = 5 }, + .uart_tx = { .bank = GPIOC, .pin = 4 }, + .uart_rx = { .bank = GPIOC, .pin = 5 }, + .alt = 1, }; // Port B - USART4 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_1 = { - .id1 = { .bank = GPIOB, .pin = 0 }, - .id2 = { .bank = GPIOA, .pin = 2 }, - .uart_buf = { .bank = GPIOB, .pin = 4 }, - .uart_tx = { .bank = GPIOC, .pin = 10 }, - .uart_rx = { .bank = GPIOC, .pin = 11 }, - .alt = 0, + .id1 = { .bank = GPIOB, .pin = 0 }, + .id2 = { .bank = GPIOA, .pin = 2 }, + .uart_buf = { .bank = GPIOB, .pin = 4 }, + .uart_tx = { .bank = GPIOC, .pin = 10 }, + .uart_rx = { .bank = GPIOC, .pin = 11 }, + .alt = 0, }; // UART @@ -51,12 +51,12 @@ enum { const pbdrv_uart_stm32f0_platform_data_t pbdrv_uart_stm32f0_platform_data[PBDRV_CONFIG_UART_STM32F0_NUM_UART] = { [UART_ID_0] = { - .uart = USART3, - .irq = USART3_6_IRQn, + .uart = USART3, + .irq = USART3_6_IRQn, }, [UART_ID_1] = { - .uart = USART4, - .irq = USART3_6_IRQn, + .uart = USART4, + .irq = USART3_6_IRQn, }, }; @@ -73,11 +73,11 @@ enum { const pbio_uartdev_platform_data_t pbio_uartdev_platform_data[PBIO_CONFIG_UARTDEV_NUM_DEV] = { [0] = { - .uart_id = UART_ID_0, + .uart_id = UART_ID_0, .counter_id = COUNTER_PORT_A, }, [1] = { - .uart_id = UART_ID_1, + .uart_id = UART_ID_1, .counter_id = COUNTER_PORT_B, }, }; @@ -99,7 +99,7 @@ void SystemInit(void) { // Enable all of the shared hardware modules we are using RCC->AHBENR |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN | RCC_AHBENR_GPIOCEN - | RCC_AHBENR_GPIODEN | RCC_AHBENR_GPIOFEN; + | RCC_AHBENR_GPIODEN | RCC_AHBENR_GPIOFEN; RCC->APB1ENR |= RCC_APB1ENR_USART3EN | RCC_APB1ENR_USART4EN; RCC->APB2ENR |= RCC_APB2ENR_SYSCFGCOMPEN; diff --git a/lib/pbio/platform/city_hub/sys.c b/lib/pbio/platform/city_hub/sys.c index 37b25be97..c58a0eff6 100644 --- a/lib/pbio/platform/city_hub/sys.c +++ b/lib/pbio/platform/city_hub/sys.c @@ -67,8 +67,7 @@ void pbsys_prepare_user_program(const pbsys_user_program_callbacks_t *callbacks) if (callbacks) { user_stop_func = callbacks->stop; user_stdin_event_func = callbacks->stdin_event; - } - else { + } else { user_stop_func = NULL; user_stdin_event_func = NULL; } @@ -169,8 +168,7 @@ static void update_button(clock_time_t now) { pbsys_power_off(); } - } - else { + } else { button_press_start_time = now; button_pressed = true; led_status_flags |= LED_STATUS_BUTTON_PRESSED; @@ -178,8 +176,7 @@ static void update_button(clock_time_t now) { user_stop_func(); } } - } - else { + } else { button_pressed = false; led_status_flags &= ~LED_STATUS_BUTTON_PRESSED; } @@ -204,8 +201,7 @@ static void update_battery(clock_time_t now) { if (avg_battery_voltage <= BATTERY_LOW_MV) { led_status_flags |= LED_STATUS_BATTERY_LOW; - } - else if (avg_battery_voltage >= BATTERY_OK_MV) { + } else if (avg_battery_voltage >= BATTERY_OK_MV) { led_status_flags &= ~LED_STATUS_BATTERY_LOW; } } @@ -243,22 +239,20 @@ PROCESS_THREAD(pbsys_process, ev, data) { etimer_reset(&timer); update_button(now); update_battery(now); - } - else if (ev == PBIO_EVENT_UART_RX) { + } else if (ev == PBIO_EVENT_UART_RX) { pbio_event_uart_rx_data_t *rx = data; handle_stdin_char(rx->byte); - } - else if (ev == PBIO_EVENT_COM_CMD) { + } else if (ev == PBIO_EVENT_COM_CMD) { pbio_com_cmd_t cmd = (uint32_t)data; switch (cmd) { - case PBIO_COM_CMD_START_USER_PROGRAM: - break; - case PBIO_COM_CMD_STOP_USER_PROGRAM: - if (user_stop_func) { - user_stop_func(); - } - break; + case PBIO_COM_CMD_START_USER_PROGRAM: + break; + case PBIO_COM_CMD_STOP_USER_PROGRAM: + if (user_stop_func) { + user_stop_func(); + } + break; } } IWDG->KR = 0xaaaa; diff --git a/lib/pbio/platform/cplus_hub/platform.c b/lib/pbio/platform/cplus_hub/platform.c index 4fd28b911..de5f42dd0 100644 --- a/lib/pbio/platform/cplus_hub/platform.c +++ b/lib/pbio/platform/cplus_hub/platform.c @@ -17,8 +17,8 @@ const pbdrv_button_gpio_platform_t pbdrv_button_gpio_platform[PBDRV_CONFIG_BUTTON_GPIO_NUM_BUTTON] = { [0] = { - .gpio = { .bank = GPIOC, .pin = 14 }, - .pull = PBDRV_GPIO_PULL_NONE, + .gpio = { .bank = GPIOC, .pin = 14 }, + .pull = PBDRV_GPIO_PULL_NONE, .button = PBIO_BUTTON_CENTER, .active_low = true, }, @@ -26,42 +26,42 @@ const pbdrv_button_gpio_platform_t pbdrv_button_gpio_platform[PBDRV_CONFIG_BUTTO // Port A const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_0 = { - .id1 = { .bank = GPIOC, .pin = 5 }, - .id2 = { .bank = GPIOB, .pin = 2 }, - .uart_buf = { .bank = GPIOH, .pin = 0 }, - .uart_tx = { .bank = GPIOB, .pin = 6 }, - .uart_rx = { .bank = GPIOB, .pin = 7 }, - .alt = GPIO_AF7_USART1, + .id1 = { .bank = GPIOC, .pin = 5 }, + .id2 = { .bank = GPIOB, .pin = 2 }, + .uart_buf = { .bank = GPIOH, .pin = 0 }, + .uart_tx = { .bank = GPIOB, .pin = 6 }, + .uart_rx = { .bank = GPIOB, .pin = 7 }, + .alt = GPIO_AF7_USART1, }; // Port B const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_1 = { - .id1 = { .bank = GPIOC, .pin = 3 }, - .id2 = { .bank = GPIOC, .pin = 0 }, - .uart_buf = { .bank = GPIOH, .pin = 1 }, - .uart_tx = { .bank = GPIOA, .pin = 2 }, - .uart_rx = { .bank = GPIOA, .pin = 3 }, - .alt = GPIO_AF7_USART2, + .id1 = { .bank = GPIOC, .pin = 3 }, + .id2 = { .bank = GPIOC, .pin = 0 }, + .uart_buf = { .bank = GPIOH, .pin = 1 }, + .uart_tx = { .bank = GPIOA, .pin = 2 }, + .uart_rx = { .bank = GPIOA, .pin = 3 }, + .alt = GPIO_AF7_USART2, }; // Port C const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_2 = { - .id1 = { .bank = GPIOC, .pin = 4 }, - .id2 = { .bank = GPIOA, .pin = 7 }, - .uart_buf = { .bank = GPIOC, .pin = 8 }, - .uart_tx = { .bank = GPIOC, .pin = 10 }, - .uart_rx = { .bank = GPIOC, .pin = 11 }, - .alt = GPIO_AF7_USART3, + .id1 = { .bank = GPIOC, .pin = 4 }, + .id2 = { .bank = GPIOA, .pin = 7 }, + .uart_buf = { .bank = GPIOC, .pin = 8 }, + .uart_tx = { .bank = GPIOC, .pin = 10 }, + .uart_rx = { .bank = GPIOC, .pin = 11 }, + .alt = GPIO_AF7_USART3, }; // Port D const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_3 = { - .id1 = { .bank = GPIOA, .pin = 4 }, - .id2 = { .bank = GPIOA, .pin = 5 }, - .uart_buf = { .bank = GPIOC, .pin = 7 }, - .uart_tx = { .bank = GPIOB, .pin = 11 }, - .uart_rx = { .bank = GPIOB, .pin = 10 }, - .alt = GPIO_AF8_LPUART1, + .id1 = { .bank = GPIOA, .pin = 4 }, + .id2 = { .bank = GPIOA, .pin = 5 }, + .uart_buf = { .bank = GPIOC, .pin = 7 }, + .uart_tx = { .bank = GPIOB, .pin = 11 }, + .uart_rx = { .bank = GPIOB, .pin = 10 }, + .alt = GPIO_AF8_LPUART1, }; enum { @@ -72,22 +72,22 @@ enum { }; const pbdrv_uart_stm32_hal_platform_data_t -pbdrv_uart_stm32_hal_platform_data[PBDRV_CONFIG_UART_STM32_HAL_NUM_UART] = { + pbdrv_uart_stm32_hal_platform_data[PBDRV_CONFIG_UART_STM32_HAL_NUM_UART] = { [UART_PORT_A] = { - .uart = USART1, - .irq = USART1_IRQn, + .uart = USART1, + .irq = USART1_IRQn, }, [UART_PORT_B] = { - .uart = USART2, - .irq = USART2_IRQn, + .uart = USART2, + .irq = USART2_IRQn, }, [UART_PORT_C] = { - .uart = USART3, - .irq = USART3_IRQn, + .uart = USART3, + .irq = USART3_IRQn, }, [UART_PORT_D] = { - .uart = LPUART1, - .irq = LPUART1_IRQn, + .uart = LPUART1, + .irq = LPUART1_IRQn, }, }; @@ -116,19 +116,19 @@ enum { const pbio_uartdev_platform_data_t pbio_uartdev_platform_data[PBIO_CONFIG_UARTDEV_NUM_DEV] = { [0] = { - .uart_id = UART_PORT_A, + .uart_id = UART_PORT_A, .counter_id = COUNTER_PORT_A, }, [1] = { - .uart_id = UART_PORT_B, + .uart_id = UART_PORT_B, .counter_id = COUNTER_PORT_B, }, [2] = { - .uart_id = UART_PORT_C, + .uart_id = UART_PORT_C, .counter_id = COUNTER_PORT_C, }, [3] = { - .uart_id = UART_PORT_D, + .uart_id = UART_PORT_D, .counter_id = COUNTER_PORT_D, }, }; @@ -140,14 +140,14 @@ const pbio_uartdev_platform_data_t pbio_uartdev_platform_data[PBIO_CONFIG_UARTDE uint32_t SystemCoreClock = 4000000; // copied from system_stm32.c in stm32 port -const uint8_t AHBPrescTable[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9 }; -const uint8_t APBPrescTable[8] = { 0, 0, 0, 0, 1, 2, 3, 4 }; +const uint8_t AHBPrescTable[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9 }; +const uint8_t APBPrescTable[8] = { 0, 0, 0, 0, 1, 2, 3, 4 }; const uint32_t MSIRangeTable[12] = { 100000, 200000, 400000, 800000, 1000000, 2000000, 4000000, 8000000, 16000000, 24000000, 32000000, 48000000 }; -void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) { +void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { GPIO_InitTypeDef gpio_init = { 0 }; ADC_ChannelConfTypeDef adc_ch_config = { 0 }; @@ -213,9 +213,9 @@ void SystemInit(void) { static TIM_HandleTypeDef htim15; static TIM_HandleTypeDef htim16; -#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) - SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ -#endif + #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10 and CP11 Full Access */ + #endif // Using external 16Mhz oscillator osc_init.OscillatorType = RCC_OSCILLATORTYPE_MSI; @@ -234,7 +234,7 @@ void SystemInit(void) { clk_init.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; clk_init.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - clk_init.AHBCLKDivider = RCC_SYSCLK_DIV1; // HCLK 80MHz + clk_init.AHBCLKDivider = RCC_SYSCLK_DIV1; // HCLK 80MHz clk_init.APB1CLKDivider = RCC_HCLK_DIV1; // disassembly shows DIV16, but 80MHz is OK according to data sheet clk_init.APB2CLKDivider = RCC_HCLK_DIV1; @@ -245,14 +245,14 @@ void SystemInit(void) { // enable clocks RCC->AHB1ENR |= RCC_AHB1ENR_DMA1EN | RCC_AHB1ENR_DMA2EN | RCC_AHB1ENR_FLASHEN | - RCC_AHB1ENR_CRCEN; + RCC_AHB1ENR_CRCEN; RCC->AHB2ENR |= RCC_AHB2ENR_GPIOAEN | RCC_AHB2ENR_GPIOBEN | RCC_AHB2ENR_GPIOCEN | - RCC_AHB2ENR_GPIODEN | RCC_AHB2ENR_GPIOHEN | RCC_AHB2ENR_ADCEN; + RCC_AHB2ENR_GPIODEN | RCC_AHB2ENR_GPIOHEN | RCC_AHB2ENR_ADCEN; RCC->APB1ENR1 |= RCC_APB1ENR1_TIM2EN | RCC_APB1ENR1_WWDGEN | RCC_APB1ENR1_USART2EN | - RCC_APB1ENR1_USART3EN | RCC_APB1ENR1_I2C1EN | RCC_APB1ENR1_PWREN; + RCC_APB1ENR1_USART3EN | RCC_APB1ENR1_I2C1EN | RCC_APB1ENR1_PWREN; RCC->APB1ENR2 |= RCC_APB1ENR2_LPUART1EN; RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN | RCC_APB2ENR_TIM1EN | RCC_APB2ENR_SPI1EN | - RCC_APB2ENR_USART1EN | RCC_APB2ENR_TIM15EN | RCC_APB2ENR_TIM16EN; + RCC_APB2ENR_USART1EN | RCC_APB2ENR_TIM15EN | RCC_APB2ENR_TIM16EN; // Keep main power on (PC12) @@ -270,17 +270,17 @@ void SystemInit(void) { htim1.Instance = TIM1; htim1.Init.Prescaler = 8 - 1; - htim1.Init.Period = 10000 -1; + htim1.Init.Period = 10000 - 1; HAL_TIM_Base_Init(&htim1); htim15.Instance = TIM15; htim15.Init.Prescaler = 8 - 1; - htim15.Init.Period = 10000 -1; + htim15.Init.Period = 10000 - 1; HAL_TIM_Base_Init(&htim15); htim16.Instance = TIM16; htim16.Init.Prescaler = 8 - 1; - htim16.Init.Period = 10000 -1; + htim16.Init.Period = 10000 - 1; HAL_TIM_Base_Init(&htim16); cplus_hub_htim1 = &htim1; diff --git a/lib/pbio/platform/cplus_hub/stm32l4xx_hal_conf.h b/lib/pbio/platform/cplus_hub/stm32l4xx_hal_conf.h index a227de260..d5b60bc8a 100644 --- a/lib/pbio/platform/cplus_hub/stm32l4xx_hal_conf.h +++ b/lib/pbio/platform/cplus_hub/stm32l4xx_hal_conf.h @@ -24,7 +24,7 @@ #define STM32L4xx_HAL_CONF_H #ifdef __cplusplus - extern "C" { +extern "C" { #endif /* Exported types ------------------------------------------------------------*/ @@ -92,11 +92,11 @@ * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ -#if !defined (HSE_VALUE) +#if !defined(HSE_VALUE) #define HSE_VALUE 8000000U /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ -#if !defined (HSE_STARTUP_TIMEOUT) +#if !defined(HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT 100U /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ @@ -104,7 +104,7 @@ * @brief Internal Multiple Speed oscillator (MSI) default value. * This value is the default MSI range value after Reset. */ -#if !defined (MSI_VALUE) +#if !defined(MSI_VALUE) #define MSI_VALUE 4000000U /*!< Value of the Internal oscillator in Hz*/ #endif /* MSI_VALUE */ @@ -113,7 +113,7 @@ * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ -#if !defined (HSI_VALUE) +#if !defined(HSI_VALUE) #define HSI_VALUE 16000000U /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ @@ -124,7 +124,7 @@ * When the CRS is not used, the HSI48 RC oscillator runs on it default frequency * which is subject to manufacturing process variations. */ -#if !defined (HSI48_VALUE) +#if !defined(HSI48_VALUE) #define HSI48_VALUE 48000000U /*!< Value of the Internal High Speed oscillator for USB FS/SDMMC/RNG in Hz. The real value my vary depending on manufacturing process variations.*/ #endif /* HSI48_VALUE */ @@ -132,7 +132,7 @@ /** * @brief Internal Low Speed oscillator (LSI) value. */ -#if !defined (LSI_VALUE) +#if !defined(LSI_VALUE) #define LSI_VALUE 32000U /*!< LSI Typical Value in Hz*/ #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz The real value may vary depending on the variations @@ -141,11 +141,11 @@ * @brief External Low Speed oscillator (LSE) value. * This value is used by the UART, RTC HAL module to compute the system frequency */ -#if !defined (LSE_VALUE) +#if !defined(LSE_VALUE) #define LSE_VALUE 32768U /*!< Value of the External oscillator in Hz*/ #endif /* LSE_VALUE */ -#if !defined (LSE_STARTUP_TIMEOUT) +#if !defined(LSE_STARTUP_TIMEOUT) #define LSE_STARTUP_TIMEOUT 5000U /*!< Time out for LSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ @@ -154,7 +154,7 @@ * This value is used by the RCC HAL module to compute the SAI1 & SAI2 clock source * frequency. */ -#if !defined (EXTERNAL_SAI1_CLOCK_VALUE) +#if !defined(EXTERNAL_SAI1_CLOCK_VALUE) #define EXTERNAL_SAI1_CLOCK_VALUE 48000U /*!< Value of the SAI1 External clock source in Hz*/ #endif /* EXTERNAL_SAI1_CLOCK_VALUE */ @@ -163,7 +163,7 @@ * This value is used by the RCC HAL module to compute the SAI1 & SAI2 clock source * frequency. */ -#if !defined (EXTERNAL_SAI2_CLOCK_VALUE) +#if !defined(EXTERNAL_SAI2_CLOCK_VALUE) #define EXTERNAL_SAI2_CLOCK_VALUE 48000U /*!< Value of the SAI2 External clock source in Hz*/ #endif /* EXTERNAL_SAI2_CLOCK_VALUE */ @@ -455,7 +455,7 @@ */ #define assert_param(expr) ((expr) ? (void)0U : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ - void assert_failed(uint8_t *file, uint32_t line); +void assert_failed(uint8_t *file, uint32_t line); #else #define assert_param(expr) ((void)0U) #endif /* USE_FULL_ASSERT */ diff --git a/lib/pbio/platform/cplus_hub/sys.c b/lib/pbio/platform/cplus_hub/sys.c index 49e703e47..14a70db69 100644 --- a/lib/pbio/platform/cplus_hub/sys.c +++ b/lib/pbio/platform/cplus_hub/sys.c @@ -52,8 +52,7 @@ void pbsys_prepare_user_program(const pbsys_user_program_callbacks_t *callbacks) if (callbacks) { user_stop_func = callbacks->stop; user_stdin_event_func = callbacks->stdin_event; - } - else { + } else { user_stop_func = NULL; user_stdin_event_func = NULL; } @@ -144,8 +143,7 @@ static void update_button(clock_time_t now) { pbsys_power_off(); } - } - else { + } else { button_press_start_time = now; button_pressed = true; led_status_flags |= LED_STATUS_BUTTON_PRESSED; @@ -153,8 +151,7 @@ static void update_button(clock_time_t now) { user_stop_func(); } } - } - else { + } else { button_pressed = false; led_status_flags &= ~LED_STATUS_BUTTON_PRESSED; } @@ -192,22 +189,20 @@ PROCESS_THREAD(pbsys_process, ev, data) { clock_time_t now = clock_time(); etimer_reset(&timer); update_button(now); - } - else if (ev == PBIO_EVENT_UART_RX) { + } else if (ev == PBIO_EVENT_UART_RX) { pbio_event_uart_rx_data_t *rx = data; handle_stdin_char(rx->byte); - } - else if (ev == PBIO_EVENT_COM_CMD) { + } else if (ev == PBIO_EVENT_COM_CMD) { pbio_com_cmd_t cmd = (uint32_t)data; switch (cmd) { - case PBIO_COM_CMD_START_USER_PROGRAM: - break; - case PBIO_COM_CMD_STOP_USER_PROGRAM: - if (user_stop_func) { - user_stop_func(); - } - break; + case PBIO_COM_CMD_START_USER_PROGRAM: + break; + case PBIO_COM_CMD_STOP_USER_PROGRAM: + if (user_stop_func) { + user_stop_func(); + } + break; } } } diff --git a/lib/pbio/platform/debug/platform.c b/lib/pbio/platform/debug/platform.c index b8a9464c4..af6c48923 100644 --- a/lib/pbio/platform/debug/platform.c +++ b/lib/pbio/platform/debug/platform.c @@ -15,7 +15,7 @@ #include "../../drv/button/button_gpio.h" #include "../../drv/uart/uart_stm32_hal.h" -void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) { +void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { GPIO_InitTypeDef gpio_init; ADC_ChannelConfTypeDef adc_ch_config; @@ -115,7 +115,7 @@ void DMA2_Stream0_IRQHandler() { const pbdrv_button_gpio_platform_t pbdrv_button_gpio_platform[PBDRV_CONFIG_BUTTON_GPIO_NUM_BUTTON] = { [0] = { - .gpio = { .bank = GPIOC, .pin = 13 }, + .gpio = { .bank = GPIOC, .pin = 13 }, .button = PBIO_BUTTON_CENTER, } }; @@ -130,16 +130,16 @@ enum { }; const pbdrv_uart_stm32_hal_platform_data_t -pbdrv_uart_stm32_hal_platform_data[PBDRV_CONFIG_UART_STM32_HAL_NUM_UART] = { + pbdrv_uart_stm32_hal_platform_data[PBDRV_CONFIG_UART_STM32_HAL_NUM_UART] = { [UART_ID_0] = { - .uart = USART2, - .irq = USART2_IRQn, + .uart = USART2, + .irq = USART2_IRQn, }, }; const pbio_uartdev_platform_data_t pbio_uartdev_platform_data[PBIO_CONFIG_UARTDEV_NUM_DEV] = { [0] = { - .uart_id = UART_ID_0, + .uart_id = UART_ID_0, }, }; @@ -201,23 +201,23 @@ void SystemInit(void) { clk_init.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; clk_init.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - clk_init.AHBCLKDivider = RCC_SYSCLK_DIV1; // HCLK 48MHz (max 180MHz) + clk_init.AHBCLKDivider = RCC_SYSCLK_DIV1; // HCLK 48MHz (max 180MHz) clk_init.APB1CLKDivider = RCC_HCLK_DIV1; // 48MHz (max 45MHz) clk_init.APB2CLKDivider = RCC_HCLK_DIV1; // 48MHz (max 90MHz) HAL_RCC_ClockConfig(&clk_init, FLASH_LATENCY_5); -#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) - SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ -#endif + #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10 and CP11 Full Access */ + #endif // dpgeorge: enable 8-byte stack alignment for IRQ handlers, in accord with EABI SCB->CCR |= SCB_CCR_STKALIGN_Msk; // enable GPIO clocks RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOCEN | - RCC_AHB1ENR_GPIODEN | RCC_AHB1ENR_GPIOEEN | RCC_AHB1ENR_GPIOFEN | - RCC_AHB1ENR_GPIOGEN | RCC_AHB1ENR_DMA2EN; + RCC_AHB1ENR_GPIODEN | RCC_AHB1ENR_GPIOEEN | RCC_AHB1ENR_GPIOFEN | + RCC_AHB1ENR_GPIOGEN | RCC_AHB1ENR_DMA2EN; RCC->APB1ENR |= RCC_APB1ENR_TIM2EN | RCC_APB1ENR_USART2EN; RCC->APB2ENR |= RCC_APB2ENR_ADC3EN | RCC_APB2ENR_USART6EN; @@ -230,6 +230,6 @@ void SystemInit(void) { USART6->CR1 = USART_CR1_UE | USART_CR1_TE | USART_CR1_RE; } -void assert_failed(uint8_t* file, uint32_t line) { +void assert_failed(uint8_t *file, uint32_t line) { // set a breakpoint here for debugging } diff --git a/lib/pbio/platform/debug/stm32f4xx_hal_conf.h b/lib/pbio/platform/debug/stm32f4xx_hal_conf.h index 0507c7127..ccf0b31f0 100644 --- a/lib/pbio/platform/debug/stm32f4xx_hal_conf.h +++ b/lib/pbio/platform/debug/stm32f4xx_hal_conf.h @@ -40,7 +40,7 @@ #define __STM32F4xx_HAL_CONF_H #ifdef __cplusplus - extern "C" { +extern "C" { #endif /* Exported types ------------------------------------------------------------*/ @@ -96,11 +96,11 @@ * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ -#if !defined (HSE_VALUE) +#if !defined(HSE_VALUE) #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ -#if !defined (HSE_STARTUP_TIMEOUT) +#if !defined(HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT ((uint32_t)100U) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ @@ -109,14 +109,14 @@ * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ -#if !defined (HSI_VALUE) +#if !defined(HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @brief Internal Low Speed oscillator (LSI) value. */ -#if !defined (LSI_VALUE) +#if !defined(LSI_VALUE) #define LSI_VALUE ((uint32_t)40000) #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz The real value may vary depending on the variations @@ -124,11 +124,11 @@ /** * @brief External Low Speed oscillator (LSE) value. */ -#if !defined (LSE_VALUE) +#if !defined(LSE_VALUE) #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ #endif /* LSE_VALUE */ -#if !defined (LSE_STARTUP_TIMEOUT) +#if !defined(LSE_STARTUP_TIMEOUT) #define LSE_STARTUP_TIMEOUT ((uint32_t)5000U) /*!< Time out for LSE start up, in ms */ #endif /* LSE_STARTUP_TIMEOUT */ @@ -137,7 +137,7 @@ * This value is used by the I2S HAL module to compute the I2S clock source * frequency, this source is inserted directly through I2S_CKIN pad. */ -#if !defined (EXTERNAL_CLOCK_VALUE) +#if !defined(EXTERNAL_CLOCK_VALUE) #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/ #endif /* EXTERNAL_CLOCK_VALUE */ @@ -393,7 +393,7 @@ */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ - void assert_failed(uint8_t* file, uint32_t line); +void assert_failed(uint8_t *file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ diff --git a/lib/pbio/platform/debug/sys.c b/lib/pbio/platform/debug/sys.c index 5a29144af..72f1db0aa 100644 --- a/lib/pbio/platform/debug/sys.c +++ b/lib/pbio/platform/debug/sys.c @@ -41,8 +41,7 @@ void pbsys_prepare_user_program(const pbsys_user_program_callbacks_t *callbacks) if (callbacks) { user_stop_func = callbacks->stop; user_stdin_event_func = callbacks->stdin_event; - } - else { + } else { user_stop_func = NULL; user_stdin_event_func = NULL; } @@ -130,8 +129,7 @@ static void update_button(clock_time_t now) { pbsys_power_off(); } - } - else { + } else { button_press_start_time = now; button_pressed = true; led_status_flags |= LED_STATUS_BUTTON_PRESSED; @@ -139,8 +137,7 @@ static void update_button(clock_time_t now) { user_stop_func(); } } - } - else { + } else { button_pressed = false; led_status_flags &= ~LED_STATUS_BUTTON_PRESSED; } @@ -160,18 +157,17 @@ PROCESS_THREAD(pbsys_process, ev, data) { clock_time_t now = clock_time(); etimer_reset(&timer); update_button(now); - } - else if (ev == PBIO_EVENT_COM_CMD) { + } else if (ev == PBIO_EVENT_COM_CMD) { pbio_com_cmd_t cmd = (uint32_t)data; switch (cmd) { - case PBIO_COM_CMD_START_USER_PROGRAM: - break; - case PBIO_COM_CMD_STOP_USER_PROGRAM: - if (user_stop_func) { - user_stop_func(); - } - break; + case PBIO_COM_CMD_START_USER_PROGRAM: + break; + case PBIO_COM_CMD_STOP_USER_PROGRAM: + if (user_stop_func) { + user_stop_func(); + } + break; } } } diff --git a/lib/pbio/platform/ev3dev_stretch/clock.c b/lib/pbio/platform/ev3dev_stretch/clock.c index 50adf5ac7..a20cdf998 100644 --- a/lib/pbio/platform/ev3dev_stretch/clock.c +++ b/lib/pbio/platform/ev3dev_stretch/clock.c @@ -13,16 +13,16 @@ void clock_init(void) { clock_time_t clock_time() { struct timespec time_val; clock_gettime(CLOCK_MONOTONIC_RAW, &time_val); - return (time_val.tv_sec*1000 + time_val.tv_nsec / 1000000); + return time_val.tv_sec * 1000 + time_val.tv_nsec / 1000000; } unsigned long clock_usecs() { struct timespec time_val; clock_gettime(CLOCK_MONOTONIC_RAW, &time_val); - return (time_val.tv_sec*1000000 + time_val.tv_nsec / 1000); + return time_val.tv_sec * 1000000 + time_val.tv_nsec / 1000; } -void clock_delay_usec(uint16_t duration){ +void clock_delay_usec(uint16_t duration) { // FIXME: is there a way to busy-wait on Linux? maybe call clock_gettime() in a loop? usleep(duration); } diff --git a/lib/pbio/platform/move_hub/hci_tl.h b/lib/pbio/platform/move_hub/hci_tl.h index f65ac285d..11a0f15fd 100644 --- a/lib/pbio/platform/move_hub/hci_tl.h +++ b/lib/pbio/platform/move_hub/hci_tl.h @@ -24,15 +24,15 @@ // TODO: response will eventually be removed from this struct struct hci_request { uint32_t event; /**< HCI Event */ - void *cparam; /**< HCI Command from MCU to Host */ - void *rparam; /**< Response from Host to MCU */ + void *cparam; /**< HCI Command from MCU to Host */ + void *rparam; /**< Response from Host to MCU */ uint16_t opcode; /**< Opcode */ uint8_t clen; /**< Command Length */ uint8_t rlen; /**< Response Length */ }; struct hci_response { - void *rparam; /**< Response from Host to MCU */ + void *rparam; /**< Response from Host to MCU */ uint8_t rlen; /**< Response Length */ }; diff --git a/lib/pbio/platform/move_hub/platform.c b/lib/pbio/platform/move_hub/platform.c index 5da01f577..0e6dcffac 100644 --- a/lib/pbio/platform/move_hub/platform.c +++ b/lib/pbio/platform/move_hub/platform.c @@ -16,8 +16,8 @@ const pbdrv_button_gpio_platform_t pbdrv_button_gpio_platform[PBDRV_CONFIG_BUTTON_GPIO_NUM_BUTTON] = { [0] = { - .gpio = { .bank = GPIOC, .pin = 13 }, - .pull = PBDRV_GPIO_PULL_UP, + .gpio = { .bank = GPIOC, .pin = 13 }, + .pull = PBDRV_GPIO_PULL_UP, .button = PBIO_BUTTON_CENTER, .active_low = true, }, @@ -33,37 +33,37 @@ enum { }; const pbdrv_counter_stm32f0_gpio_quad_enc_platform_data_t -pbdrv_counter_stm32f0_gpio_quad_enc_platform_data[] = { + pbdrv_counter_stm32f0_gpio_quad_enc_platform_data[] = { [0] = { - .gpio_int = { .bank = GPIOB, .pin = 1}, - .gpio_dir = { .bank = GPIOB, .pin = 9}, - .counter_id = COUNTER_PORT_A, + .gpio_int = { .bank = GPIOB, .pin = 1}, + .gpio_dir = { .bank = GPIOB, .pin = 9}, + .counter_id = COUNTER_PORT_A, }, [1] = { - .gpio_int = { .bank = GPIOA, .pin = 0}, - .gpio_dir = { .bank = GPIOA, .pin = 1}, - .counter_id = COUNTER_PORT_B, + .gpio_int = { .bank = GPIOA, .pin = 0}, + .gpio_dir = { .bank = GPIOA, .pin = 1}, + .counter_id = COUNTER_PORT_B, }, }; // Port C - USART4 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_0 = { - .id1 = { .bank = GPIOB, .pin = 7 }, - .id2 = { .bank = GPIOC, .pin = 15 }, - .uart_buf = { .bank = GPIOB, .pin = 4 }, - .uart_tx = { .bank = GPIOC, .pin = 10 }, - .uart_rx = { .bank = GPIOC, .pin = 11 }, - .alt = 0, + .id1 = { .bank = GPIOB, .pin = 7 }, + .id2 = { .bank = GPIOC, .pin = 15 }, + .uart_buf = { .bank = GPIOB, .pin = 4 }, + .uart_tx = { .bank = GPIOC, .pin = 10 }, + .uart_rx = { .bank = GPIOC, .pin = 11 }, + .alt = 0, }; // Port D - USART3 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_1 = { - .id1 = { .bank = GPIOB, .pin = 10 }, - .id2 = { .bank = GPIOA, .pin = 12 }, - .uart_buf = { .bank = GPIOB, .pin = 0 }, - .uart_tx = { .bank = GPIOC, .pin = 4 }, - .uart_rx = { .bank = GPIOC, .pin = 5 }, - .alt = 1, + .id1 = { .bank = GPIOB, .pin = 10 }, + .id2 = { .bank = GPIOA, .pin = 12 }, + .uart_buf = { .bank = GPIOB, .pin = 0 }, + .uart_tx = { .bank = GPIOC, .pin = 4 }, + .uart_rx = { .bank = GPIOC, .pin = 5 }, + .alt = 1, }; // UART @@ -75,12 +75,12 @@ enum { const pbdrv_uart_stm32f0_platform_data_t pbdrv_uart_stm32f0_platform_data[PBDRV_CONFIG_UART_STM32F0_NUM_UART] = { [UART_ID_0] = { - .uart = USART4, - .irq = USART3_4_IRQn, + .uart = USART4, + .irq = USART3_4_IRQn, }, [UART_ID_1] = { - .uart = USART3, - .irq = USART3_4_IRQn, + .uart = USART3, + .irq = USART3_4_IRQn, }, }; @@ -93,11 +93,11 @@ void USART3_4_IRQHandler(void) { #if PBIO_CONFIG_UARTDEV const pbio_uartdev_platform_data_t pbio_uartdev_platform_data[PBIO_CONFIG_UARTDEV_NUM_DEV] = { [0] = { - .uart_id = UART_ID_0, + .uart_id = UART_ID_0, .counter_id = COUNTER_PORT_C, }, [1] = { - .uart_id = UART_ID_1, + .uart_id = UART_ID_1, .counter_id = COUNTER_PORT_D, }, }; @@ -120,7 +120,7 @@ void SystemInit(void) { // Enable all of the shared hardware modules we are using RCC->AHBENR |= RCC_AHBENR_GPIOAEN | RCC_AHBENR_GPIOBEN | RCC_AHBENR_GPIOCEN - | RCC_AHBENR_GPIODEN | RCC_AHBENR_GPIOFEN; + | RCC_AHBENR_GPIODEN | RCC_AHBENR_GPIOFEN; RCC->APB1ENR |= RCC_APB1ENR_USART3EN | RCC_APB1ENR_USART4EN; RCC->APB2ENR |= RCC_APB2ENR_SYSCFGCOMPEN; diff --git a/lib/pbio/platform/move_hub/sys.c b/lib/pbio/platform/move_hub/sys.c index 2eb106461..d71e11ea4 100644 --- a/lib/pbio/platform/move_hub/sys.c +++ b/lib/pbio/platform/move_hub/sys.c @@ -67,8 +67,7 @@ void pbsys_prepare_user_program(const pbsys_user_program_callbacks_t *callbacks) if (callbacks) { user_stop_func = callbacks->stop; user_stdin_event_func = callbacks->stdin_event; - } - else { + } else { user_stop_func = NULL; user_stdin_event_func = NULL; } @@ -161,8 +160,7 @@ static void update_button(clock_time_t now) { pbsys_power_off(); } - } - else { + } else { button_press_start_time = now; button_pressed = true; led_status_flags |= LED_STATUS_BUTTON_PRESSED; @@ -170,8 +168,7 @@ static void update_button(clock_time_t now) { user_stop_func(); } } - } - else { + } else { button_pressed = false; led_status_flags &= ~LED_STATUS_BUTTON_PRESSED; } @@ -196,8 +193,7 @@ static void update_battery(clock_time_t now) { if (avg_battery_voltage <= BATTERY_LOW_MV) { led_status_flags |= LED_STATUS_BATTERY_LOW; - } - else if (avg_battery_voltage >= BATTERY_OK_MV) { + } else if (avg_battery_voltage >= BATTERY_OK_MV) { led_status_flags &= ~LED_STATUS_BATTERY_LOW; } } @@ -235,22 +231,20 @@ PROCESS_THREAD(pbsys_process, ev, data) { etimer_reset(&timer); update_button(now); update_battery(now); - } - else if (ev == PBIO_EVENT_UART_RX) { + } else if (ev == PBIO_EVENT_UART_RX) { pbio_event_uart_rx_data_t *rx = data; handle_stdin_char(rx->byte); - } - else if (ev == PBIO_EVENT_COM_CMD) { + } else if (ev == PBIO_EVENT_COM_CMD) { pbio_com_cmd_t cmd = (uint32_t)data; switch (cmd) { - case PBIO_COM_CMD_START_USER_PROGRAM: - break; - case PBIO_COM_CMD_STOP_USER_PROGRAM: - if (user_stop_func) { - user_stop_func(); - } - break; + case PBIO_COM_CMD_START_USER_PROGRAM: + break; + case PBIO_COM_CMD_STOP_USER_PROGRAM: + if (user_stop_func) { + user_stop_func(); + } + break; } } } diff --git a/lib/pbio/platform/nxt/clock.c b/lib/pbio/platform/nxt/clock.c index 60f34d4a0..783a85cf7 100644 --- a/lib/pbio/platform/nxt/clock.c +++ b/lib/pbio/platform/nxt/clock.c @@ -32,13 +32,13 @@ void clock_init(void) { /* The inner loop takes 4 cycles. The outer 5+SPIN_COUNT*4. */ #define SPIN_TIME 2 /* us */ -#define SPIN_COUNT (((CLOCK_FREQUENCY*SPIN_TIME/1000000)-5)/4) +#define SPIN_COUNT (((CLOCK_FREQUENCY * SPIN_TIME / 1000000) - 5) / 4) void clock_delay_usec(uint16_t t) { -#ifdef __THUMBEL__ - __asm volatile("1: mov r1,%2\n2:\tsub r1,#1\n\tbne 2b\n\tsub %0,#1\n\tbne 1b\n" - : "=l"(t) : "0"(t), "l"(SPIN_COUNT)); -#else -#error Must be compiled in thumb mode -#endif + #ifdef __THUMBEL__ + __asm volatile ("1: mov r1,%2\n2:\tsub r1,#1\n\tbne 2b\n\tsub %0,#1\n\tbne 1b\n" + : "=l" (t) : "0" (t), "l" (SPIN_COUNT)); + #else + #error Must be compiled in thumb mode + #endif } diff --git a/lib/pbio/platform/nxt/sys.c b/lib/pbio/platform/nxt/sys.c index d2df7f2ed..3eb2a5282 100644 --- a/lib/pbio/platform/nxt/sys.c +++ b/lib/pbio/platform/nxt/sys.c @@ -63,8 +63,7 @@ void pbsys_prepare_user_program(const pbsys_user_program_callbacks_t *callbacks) if (callbacks) { user_stop_func = callbacks->stop; user_stdin_event_func = callbacks->stdin_event; - } - else { + } else { user_stop_func = NULL; user_stdin_event_func = NULL; } @@ -122,14 +121,12 @@ static void update_button(clock_time_t now) { if (now - button_press_start_time > clock_from_msec(5000)) { pbsys_power_off(); } - } - else { + } else { button_press_start_time = now; button_pressed = true; led_status_flags |= LED_STATUS_BUTTON_PRESSED; } - } - else { + } else { button_pressed = false; led_status_flags &= ~LED_STATUS_BUTTON_PRESSED; } @@ -159,8 +156,7 @@ static void update_battery(clock_time_t now) { if (avg_battery_voltage <= BATTERY_LOW_MV) { led_status_flags |= LED_STATUS_BATTERY_LOW; - } - else if (avg_battery_voltage >= BATTERY_OK_MV) { + } else if (avg_battery_voltage >= BATTERY_OK_MV) { led_status_flags &= ~LED_STATUS_BATTERY_LOW; } } @@ -198,22 +194,20 @@ PROCESS_THREAD(pbsys_process, ev, data) { etimer_reset(&timer); update_button(now); update_battery(now); - } - else if (ev == PBIO_EVENT_UART_RX) { + } else if (ev == PBIO_EVENT_UART_RX) { pbio_event_uart_rx_data_t *rx = data; handle_stdin_char(rx->byte); - } - else if (ev == PBIO_EVENT_COM_CMD) { + } else if (ev == PBIO_EVENT_COM_CMD) { pbio_com_cmd_t cmd = (uint32_t)data; switch (cmd) { - case PBIO_COM_CMD_START_USER_PROGRAM: - break; - case PBIO_COM_CMD_STOP_USER_PROGRAM: - if (user_stop_func) { - user_stop_func(); - } - break; + case PBIO_COM_CMD_START_USER_PROGRAM: + break; + case PBIO_COM_CMD_STOP_USER_PROGRAM: + if (user_stop_func) { + user_stop_func(); + } + break; } } } diff --git a/lib/pbio/platform/prime_hub/platform.c b/lib/pbio/platform/prime_hub/platform.c index 4ef2e7169..2b38d5548 100644 --- a/lib/pbio/platform/prime_hub/platform.c +++ b/lib/pbio/platform/prime_hub/platform.c @@ -27,68 +27,68 @@ extern const uint32_t _checksum; const boot_t __attribute__((section(".boot"))) boot = { .fw_ver = "v0.5.00.0020-2b83556", .checksum = &_checksum, - .magic = (const uint8_t[16]){1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}, + .magic = (const uint8_t[16]) {1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4}, }; // Port A - UART7 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_0 = { - .id1 = { .bank = GPIOD, .pin = 7 }, - .id2 = { .bank = GPIOD, .pin = 8 }, - .uart_buf = { .bank = GPIOA, .pin = 10 }, - .uart_tx = { .bank = GPIOE, .pin = 8 }, - .uart_rx = { .bank = GPIOE, .pin = 7 }, - .alt = 8, + .id1 = { .bank = GPIOD, .pin = 7 }, + .id2 = { .bank = GPIOD, .pin = 8 }, + .uart_buf = { .bank = GPIOA, .pin = 10 }, + .uart_tx = { .bank = GPIOE, .pin = 8 }, + .uart_rx = { .bank = GPIOE, .pin = 7 }, + .alt = 8, }; // Port B - UART4 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_1 = { - .id1 = { .bank = GPIOD, .pin = 9 }, - .id2 = { .bank = GPIOD, .pin = 10 }, - .uart_buf = { .bank = GPIOA, .pin = 8 }, - .uart_tx = { .bank = GPIOD, .pin = 1 }, - .uart_rx = { .bank = GPIOD, .pin = 0 }, - .alt = 11, + .id1 = { .bank = GPIOD, .pin = 9 }, + .id2 = { .bank = GPIOD, .pin = 10 }, + .uart_buf = { .bank = GPIOA, .pin = 8 }, + .uart_tx = { .bank = GPIOD, .pin = 1 }, + .uart_rx = { .bank = GPIOD, .pin = 0 }, + .alt = 11, }; // Port C - UART8 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_2 = { - .id1 = { .bank = GPIOD, .pin = 11 }, - .id2 = { .bank = GPIOE, .pin = 4 }, - .uart_buf = { .bank = GPIOE, .pin = 5 }, - .uart_tx = { .bank = GPIOE, .pin = 1 }, - .uart_rx = { .bank = GPIOE, .pin = 0 }, - .alt = 8, + .id1 = { .bank = GPIOD, .pin = 11 }, + .id2 = { .bank = GPIOE, .pin = 4 }, + .uart_buf = { .bank = GPIOE, .pin = 5 }, + .uart_tx = { .bank = GPIOE, .pin = 1 }, + .uart_rx = { .bank = GPIOE, .pin = 0 }, + .alt = 8, }; // Port D - UART5 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_3 = { - .id1 = { .bank = GPIOC, .pin = 15 }, - .id2 = { .bank = GPIOC, .pin = 14 }, - .uart_buf = { .bank = GPIOB, .pin = 2 }, - .uart_tx = { .bank = GPIOC, .pin = 12 }, - .uart_rx = { .bank = GPIOD, .pin = 2 }, - .alt = 8, + .id1 = { .bank = GPIOC, .pin = 15 }, + .id2 = { .bank = GPIOC, .pin = 14 }, + .uart_buf = { .bank = GPIOB, .pin = 2 }, + .uart_tx = { .bank = GPIOC, .pin = 12 }, + .uart_rx = { .bank = GPIOD, .pin = 2 }, + .alt = 8, }; // Port E - UART10 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_4 = { - .id1 = { .bank = GPIOC, .pin = 13 }, - .id2 = { .bank = GPIOE, .pin = 12 }, - .uart_buf = { .bank = GPIOB, .pin = 5 }, - .uart_tx = { .bank = GPIOE, .pin = 3 }, - .uart_rx = { .bank = GPIOE, .pin = 2 }, - .alt = 11, + .id1 = { .bank = GPIOC, .pin = 13 }, + .id2 = { .bank = GPIOE, .pin = 12 }, + .uart_buf = { .bank = GPIOB, .pin = 5 }, + .uart_tx = { .bank = GPIOE, .pin = 3 }, + .uart_rx = { .bank = GPIOE, .pin = 2 }, + .alt = 11, }; // Port F - UART9 const pbdrv_ioport_lpf2_platform_port_t pbdrv_ioport_lpf2_platform_port_5 = { - .id1 = { .bank = GPIOC, .pin = 11 }, - .id2 = { .bank = GPIOE, .pin = 6 }, - .uart_buf = { .bank = GPIOC, .pin = 5 }, - .uart_tx = { .bank = GPIOD, .pin = 15 }, - .uart_rx = { .bank = GPIOD, .pin = 14 }, - .alt = 11, + .id1 = { .bank = GPIOC, .pin = 11 }, + .id2 = { .bank = GPIOE, .pin = 6 }, + .uart_buf = { .bank = GPIOC, .pin = 5 }, + .uart_tx = { .bank = GPIOD, .pin = 15 }, + .uart_rx = { .bank = GPIOD, .pin = 14 }, + .alt = 11, }; enum { @@ -101,26 +101,26 @@ enum { }; const pbdrv_uart_stm32_hal_platform_data_t -pbdrv_uart_stm32_hal_platform_data[PBDRV_CONFIG_UART_STM32_HAL_NUM_UART] = { + pbdrv_uart_stm32_hal_platform_data[PBDRV_CONFIG_UART_STM32_HAL_NUM_UART] = { [UART_PORT_A] = { - .uart = UART7, - .irq = UART7_IRQn, + .uart = UART7, + .irq = UART7_IRQn, }, [UART_PORT_B] = { - .uart = UART4, - .irq = UART4_IRQn, + .uart = UART4, + .irq = UART4_IRQn, }, [UART_PORT_C] = { - .uart = UART8, - .irq = UART8_IRQn, + .uart = UART8, + .irq = UART8_IRQn, }, [UART_PORT_D] = { - .uart = UART5, - .irq = UART5_IRQn, + .uart = UART5, + .irq = UART5_IRQn, }, [UART_PORT_E] = { - .uart = UART10, - .irq = UART10_IRQn, + .uart = UART10, + .irq = UART10_IRQn, }, // [UART_PORT_F] = { // .uart = UART9, @@ -169,23 +169,23 @@ enum { const pbio_uartdev_platform_data_t pbio_uartdev_platform_data[PBIO_CONFIG_UARTDEV_NUM_DEV] = { [COUNTER_PORT_A] = { - .uart_id = UART_PORT_A, + .uart_id = UART_PORT_A, .counter_id = COUNTER_PORT_A, }, [COUNTER_PORT_B] = { - .uart_id = UART_PORT_B, + .uart_id = UART_PORT_B, .counter_id = COUNTER_PORT_B, }, [COUNTER_PORT_C] = { - .uart_id = UART_PORT_C, + .uart_id = UART_PORT_C, .counter_id = COUNTER_PORT_C, }, [COUNTER_PORT_D] = { - .uart_id = UART_PORT_D, + .uart_id = UART_PORT_D, .counter_id = COUNTER_PORT_D, }, [COUNTER_PORT_E] = { - .uart_id = UART_PORT_E, + .uart_id = UART_PORT_E, .counter_id = COUNTER_PORT_E, }, // [COUNTER_PORT_F] = { @@ -204,7 +204,7 @@ uint32_t SystemCoreClock = 16000000; const uint8_t AHBPrescTable[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 6, 7, 8, 9 }; const uint8_t APBPrescTable[8] = { 0, 0, 0, 0, 1, 2, 3, 4 }; -void HAL_ADC_MspInit(ADC_HandleTypeDef* hadc) { +void HAL_ADC_MspInit(ADC_HandleTypeDef *hadc) { GPIO_InitTypeDef gpio_init = { 0 }; ADC_ChannelConfTypeDef adc_ch_config = { 0 }; @@ -323,7 +323,7 @@ void SystemInit(void) { clk_init.ClockType = RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2; clk_init.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - clk_init.AHBCLKDivider = RCC_SYSCLK_DIV1; // HCLK 96MHz + clk_init.AHBCLKDivider = RCC_SYSCLK_DIV1; // HCLK 96MHz clk_init.APB1CLKDivider = RCC_HCLK_DIV2; // changed from pyboard since max is 50MHz clk_init.APB2CLKDivider = RCC_HCLK_DIV1; // changed from pyboard since max is 100MHz @@ -334,12 +334,12 @@ void SystemInit(void) { // enable clocks RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIOBEN | RCC_AHB1ENR_GPIOCEN | - RCC_AHB1ENR_GPIODEN | RCC_AHB1ENR_GPIOEEN | RCC_AHB1ENR_DMA2EN; + RCC_AHB1ENR_GPIODEN | RCC_AHB1ENR_GPIOEEN | RCC_AHB1ENR_DMA2EN; RCC->APB1ENR |= RCC_APB1ENR_UART4EN | RCC_APB1ENR_UART5EN | RCC_APB1ENR_UART7EN | - RCC_APB1ENR_UART8EN | RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM3EN | - RCC_APB1ENR_TIM4EN; + RCC_APB1ENR_UART8EN | RCC_APB1ENR_TIM2EN | RCC_APB1ENR_TIM3EN | + RCC_APB1ENR_TIM4EN; RCC->APB2ENR |= RCC_APB2ENR_TIM1EN | RCC_APB2ENR_UART9EN | RCC_APB2ENR_UART10EN | - RCC_APB2ENR_ADC1EN | RCC_APB2ENR_SYSCFGEN; + RCC_APB2ENR_ADC1EN | RCC_APB2ENR_SYSCFGEN; // Keep main power on (PA13 == POWER_EN) GPIOA->BSRR = GPIO_BSRR_BS_13; diff --git a/lib/pbio/platform/prime_hub/stm32f4xx_hal_conf.h b/lib/pbio/platform/prime_hub/stm32f4xx_hal_conf.h index bb8dd7436..5f13eb4ae 100644 --- a/lib/pbio/platform/prime_hub/stm32f4xx_hal_conf.h +++ b/lib/pbio/platform/prime_hub/stm32f4xx_hal_conf.h @@ -40,7 +40,7 @@ #define __STM32F4xx_HAL_CONF_H #ifdef __cplusplus - extern "C" { +extern "C" { #endif /* Exported types ------------------------------------------------------------*/ @@ -96,11 +96,11 @@ * This value is used by the RCC HAL module to compute the system frequency * (when HSE is used as system clock source, directly or through the PLL). */ -#if !defined (HSE_VALUE) +#if !defined(HSE_VALUE) #define HSE_VALUE ((uint32_t)16000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ -#if !defined (HSE_STARTUP_TIMEOUT) +#if !defined(HSE_STARTUP_TIMEOUT) #define HSE_STARTUP_TIMEOUT ((uint32_t)100U) /*!< Time out for HSE start up, in ms */ #endif /* HSE_STARTUP_TIMEOUT */ @@ -109,14 +109,14 @@ * This value is used by the RCC HAL module to compute the system frequency * (when HSI is used as system clock source, directly or through the PLL). */ -#if !defined (HSI_VALUE) +#if !defined(HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ /** * @brief Internal Low Speed oscillator (LSI) value. */ -#if !defined (LSI_VALUE) +#if !defined(LSI_VALUE) #define LSI_VALUE ((uint32_t)40000) #endif /* LSI_VALUE */ /*!< Value of the Internal Low Speed oscillator in Hz The real value may vary depending on the variations @@ -124,11 +124,11 @@ /** * @brief External Low Speed oscillator (LSE) value. */ -#if !defined (LSE_VALUE) +#if !defined(LSE_VALUE) #define LSE_VALUE ((uint32_t)32768) /*!< Value of the External Low Speed oscillator in Hz */ #endif /* LSE_VALUE */ -#if !defined (LSE_STARTUP_TIMEOUT) +#if !defined(LSE_STARTUP_TIMEOUT) #define LSE_STARTUP_TIMEOUT ((uint32_t)5000U) /*!< Time out for LSE start up, in ms */ #endif /* LSE_STARTUP_TIMEOUT */ @@ -137,7 +137,7 @@ * This value is used by the I2S HAL module to compute the I2S clock source * frequency, this source is inserted directly through I2S_CKIN pad. */ -#if !defined (EXTERNAL_CLOCK_VALUE) +#if !defined(EXTERNAL_CLOCK_VALUE) #define EXTERNAL_CLOCK_VALUE ((uint32_t)12288000) /*!< Value of the Internal oscillator in Hz*/ #endif /* EXTERNAL_CLOCK_VALUE */ @@ -393,7 +393,7 @@ */ #define assert_param(expr) ((expr) ? (void)0 : assert_failed((uint8_t *)__FILE__, __LINE__)) /* Exported functions ------------------------------------------------------- */ - void assert_failed(uint8_t* file, uint32_t line); +void assert_failed(uint8_t *file, uint32_t line); #else #define assert_param(expr) ((void)0) #endif /* USE_FULL_ASSERT */ diff --git a/lib/pbio/platform/prime_hub/sys.c b/lib/pbio/platform/prime_hub/sys.c index 79068b751..023953bc4 100644 --- a/lib/pbio/platform/prime_hub/sys.c +++ b/lib/pbio/platform/prime_hub/sys.c @@ -45,8 +45,7 @@ void pbsys_prepare_user_program(const pbsys_user_program_callbacks_t *callbacks) if (callbacks) { user_stop_func = callbacks->stop; user_stdin_event_func = callbacks->stdin_event; - } - else { + } else { user_stop_func = NULL; user_stdin_event_func = NULL; } @@ -138,8 +137,7 @@ static void update_button(clock_time_t now) { pbsys_power_off(); } - } - else { + } else { button_press_start_time = now; button_pressed = true; led_status_flags |= LED_STATUS_BUTTON_PRESSED; @@ -147,8 +145,7 @@ static void update_button(clock_time_t now) { user_stop_func(); } } - } - else { + } else { button_pressed = false; led_status_flags &= ~LED_STATUS_BUTTON_PRESSED; } @@ -168,18 +165,17 @@ PROCESS_THREAD(pbsys_process, ev, data) { clock_time_t now = clock_time(); etimer_reset(&timer); update_button(now); - } - else if (ev == PBIO_EVENT_COM_CMD) { + } else if (ev == PBIO_EVENT_COM_CMD) { pbio_com_cmd_t cmd = (uint32_t)data; switch (cmd) { - case PBIO_COM_CMD_START_USER_PROGRAM: - break; - case PBIO_COM_CMD_STOP_USER_PROGRAM: - if (user_stop_func) { - user_stop_func(); - } - break; + case PBIO_COM_CMD_START_USER_PROGRAM: + break; + case PBIO_COM_CMD_STOP_USER_PROGRAM: + if (user_stop_func) { + user_stop_func(); + } + break; } } } diff --git a/lib/pbio/src/control.c b/lib/pbio/src/control.c index b8a67ac22..80c360091 100644 --- a/lib/pbio/src/control.c +++ b/lib/pbio/src/control.c @@ -31,8 +31,7 @@ void control_update(pbio_control_t *ctl, int32_t time_now, int32_t count_now, in pbio_count_integrator_update(&ctl->count_integrator, time_now, count_now, count_ref, ctl->trajectory.th3, ctl->settings.integral_range, ctl->settings.integral_rate); pbio_count_integrator_get_errors(&ctl->count_integrator, count_now, count_ref, &count_err, &count_err_integral); rate_err = rate_ref - rate_now; - } - else { + } else { // For time/speed based commands, the main error is speed. It integrates into a quantity with unit of position. // There is no count integral control, because we do not need a second order integrator for speed control. pbio_rate_integrator_get_errors(&ctl->rate_integrator, rate_now, rate_ref, count_now, count_ref, &rate_err, &rate_err_integral); @@ -41,10 +40,10 @@ void control_update(pbio_control_t *ctl, int32_t time_now, int32_t count_now, in } // Corresponding PID control signal - duty_due_to_proportional = ctl->settings.pid_kp*count_err; - duty_due_to_derivative = ctl->settings.pid_kd*rate_err; - duty_due_to_integral = (ctl->settings.pid_ki*(count_err_integral/US_PER_MS))/MS_PER_SECOND; - duty_feedforward = pbio_math_sign(rate_ref)*ctl->settings.control_offset; + duty_due_to_proportional = ctl->settings.pid_kp * count_err; + duty_due_to_derivative = ctl->settings.pid_kd * rate_err; + duty_due_to_integral = (ctl->settings.pid_ki * (count_err_integral / US_PER_MS)) / MS_PER_SECOND; + duty_feedforward = pbio_math_sign(rate_ref) * ctl->settings.control_offset; // Total duty signal, capped by the actuation limit duty = duty_due_to_proportional + duty_due_to_integral + duty_due_to_derivative + duty_feedforward; @@ -65,8 +64,7 @@ void control_update(pbio_control_t *ctl, int32_t time_now, int32_t count_now, in if (abs(duty_due_to_proportional) >= max_windup_duty) { // We are at the duty limit and we should prevent further position error integration. pbio_count_integrator_pause(&ctl->count_integrator, time_now, count_now, count_ref); - } - else { + } else { // Not at the limitm so continue integrating errors pbio_count_integrator_resume(&ctl->count_integrator, time_now, count_now, count_ref); } @@ -76,17 +74,16 @@ void control_update(pbio_control_t *ctl, int32_t time_now, int32_t count_now, in if (abs(duty_due_to_proportional) >= max_windup_duty && pbio_math_sign(duty_due_to_proportional) == pbio_math_sign(rate_err)) { // We are at the duty limit and we should prevent further speed error integration. pbio_rate_integrator_pause(&ctl->rate_integrator, time_now, count_now, count_ref); - } - else { + } else { // Not at the limitm so continue integrating errors pbio_rate_integrator_resume(&ctl->rate_integrator, time_now, count_now, count_ref); } } // Check if controller is stalled - ctl->stalled = ctl->type == PBIO_CONTROL_ANGLE ? - pbio_count_integrator_stalled(&ctl->count_integrator, time_now, rate_now, ctl->settings.stall_time, ctl->settings.stall_rate_limit) : - pbio_rate_integrator_stalled(&ctl->rate_integrator, time_now, rate_now, ctl->settings.stall_time, ctl->settings.stall_rate_limit); + ctl->stalled = ctl->type == PBIO_CONTROL_ANGLE ? + pbio_count_integrator_stalled(&ctl->count_integrator, time_now, rate_now, ctl->settings.stall_time, ctl->settings.stall_rate_limit) : + pbio_rate_integrator_stalled(&ctl->rate_integrator, time_now, rate_now, ctl->settings.stall_time, ctl->settings.stall_rate_limit); // Check if we are on target ctl->on_target = ctl->on_target_func(&ctl->trajectory, &ctl->settings, time_ref, count_now, rate_now, ctl->stalled); @@ -96,8 +93,7 @@ void control_update(pbio_control_t *ctl, int32_t time_now, int32_t count_now, in *actuation_type = ctl->after_stop; *control = 0; pbio_control_stop(ctl); - } - else if (ctl->on_target && ctl->after_stop == PBIO_ACTUATION_HOLD && ctl->type == PBIO_CONTROL_TIMED) { + } else if (ctl->on_target && ctl->after_stop == PBIO_ACTUATION_HOLD && ctl->type == PBIO_CONTROL_TIMED) { // If we are going to hold and we are already doing angle control, there is nothing we need to do. // But if we are going to hold when we are doing speed control right now, we must trigger a hold first. pbio_control_start_hold_control(ctl, time_now, count_now); @@ -105,8 +101,7 @@ void control_update(pbio_control_t *ctl, int32_t time_now, int32_t count_now, in // The new hold control does not take effect until the next iteration, so keep actuating for now. *actuation_type = PBIO_ACTUATION_DUTY; *control = duty; - } - else { + } else { // The end point not reached, or we have to keep holding, so return the calculated duty for actuation *actuation_type = PBIO_ACTUATION_DUTY; *control = duty; @@ -137,8 +132,7 @@ pbio_error_t pbio_control_start_angle_control(pbio_control_t *ctl, int32_t time_ if (err != PBIO_SUCCESS) { return err; } - } - else { + } else { // If control is ongoing, start from its current reference. First get time on current reference signal int32_t time_ref = pbio_control_get_ref_time(ctl, time_now); @@ -179,7 +173,7 @@ pbio_error_t pbio_control_start_relative_angle_control(pbio_control_t *ctl, int3 } // The target count is the start count plus the count to be traveled. If speed is negative, traveled count also flips. - int32_t target_count = count_start + (target_rate < 0 ? -relative_target_count: relative_target_count); + int32_t target_count = count_start + (target_rate < 0 ? -relative_target_count : relative_target_count); // FIXME: Enable 0 angle and angle > 0 with excess speed as standard case instead to decelerate & return. if (target_count == count_start) { @@ -228,8 +222,7 @@ pbio_error_t pbio_control_start_timed_control(pbio_control_t *ctl, int32_t time_ if (err != PBIO_SUCCESS) { return err; } - } - else if (ctl->type == PBIO_CONTROL_ANGLE) { + } else if (ctl->type == PBIO_CONTROL_ANGLE) { // If position based control is ongoing, start from its current reference. First get current reference signal. int32_t time_ref = pbio_control_get_ref_time(ctl, time_now); int32_t count_start, rate_start, unused; @@ -240,8 +233,7 @@ pbio_error_t pbio_control_start_timed_control(pbio_control_t *ctl, int32_t time_ if (err != PBIO_SUCCESS) { return err; } - } - else { + } else { // If no control is ongoing, start from physical state err = pbio_trajectory_make_time_based(&ctl->trajectory, time_now, duration, count_now, 0, rate_now, target_rate, ctl->settings.max_rate, acceleration, ctl->settings.abs_acceleration); if (err != PBIO_SUCCESS) { @@ -386,7 +378,7 @@ pbio_error_t pbio_control_settings_set_stall_tolerances(pbio_control_settings_t } s->stall_rate_limit = pbio_control_user_to_counts(s, speed); - s->stall_time = time * US_PER_MS; + s->stall_time = time * US_PER_MS; return PBIO_SUCCESS; } @@ -396,7 +388,7 @@ int32_t pbio_control_settings_get_max_integrator(pbio_control_settings_t *s) { return 1000000000; } // Get the maximum integrator value for which ki*integrator does not exceed max_control - return ((s->max_control*US_PER_MS)/s->pid_ki)*MS_PER_SECOND; + return ((s->max_control * US_PER_MS) / s->pid_ki) * MS_PER_SECOND; } int32_t pbio_control_get_ref_time(pbio_control_t *ctl, int32_t time_now) { diff --git a/lib/pbio/src/dcmotor.c b/lib/pbio/src/dcmotor.c index 1f9d0c65f..b5c357cf9 100644 --- a/lib/pbio/src/dcmotor.c +++ b/lib/pbio/src/dcmotor.c @@ -23,7 +23,7 @@ static pbio_error_t pbio_dcmotor_setup(pbio_dcmotor_t *dcmotor, pbio_direction_t err = pbdrv_motor_setup(dcmotor->port, is_servo); if (err != PBIO_SUCCESS) { return err; - } + } // Coast the device err = pbio_dcmotor_coast(dcmotor); @@ -89,7 +89,7 @@ pbio_error_t pbio_dcmotor_set_duty_cycle_sys(pbio_dcmotor_t *dcmotor, int32_t du dcmotor->duty_now = duty_steps; // Flip sign if motor is inverted - if (dcmotor->direction == PBIO_DIRECTION_COUNTERCLOCKWISE){ + if (dcmotor->direction == PBIO_DIRECTION_COUNTERCLOCKWISE) { duty_steps = -duty_steps; } pbio_error_t err = pbdrv_motor_set_duty_cycle(dcmotor->port, duty_steps); diff --git a/lib/pbio/src/drivebase.c b/lib/pbio/src/drivebase.c index abd9aaa4e..3a2a2df79 100644 --- a/lib/pbio/src/drivebase.c +++ b/lib/pbio/src/drivebase.c @@ -13,7 +13,7 @@ #if PBDRV_CONFIG_NUM_MOTOR_CONTROLLER != 0 static pbio_error_t drivebase_adopt_settings(pbio_control_settings_t *s_distance, pbio_control_settings_t *s_heading, pbio_control_settings_t *s_left, pbio_control_settings_t *s_right) { - + // All rate/count acceleration limits add up, because distance state is two motors counts added s_distance->max_rate = s_left->max_rate + s_right->max_rate; s_distance->rate_tolerance = s_left->rate_tolerance + s_right->rate_tolerance; @@ -24,12 +24,12 @@ static pbio_error_t drivebase_adopt_settings(pbio_control_settings_t *s_distance // As acceleration, we take double the single motor amount, because drivebases are // usually expected to respond quickly to speed setpoint changes - s_distance->abs_acceleration = (s_left->abs_acceleration + s_right->abs_acceleration)*2; + s_distance->abs_acceleration = (s_left->abs_acceleration + s_right->abs_acceleration) * 2; // Although counts/errors add up twice as fast, both motors actuate, so apply half of the average PID - s_distance->pid_kp = (s_left->pid_kp + s_right->pid_kp)/4; - s_distance->pid_ki = (s_left->pid_ki + s_right->pid_ki)/4; - s_distance->pid_kd = (s_left->pid_kd + s_right->pid_kd)/4; + s_distance->pid_kp = (s_left->pid_kp + s_right->pid_kp) / 4; + s_distance->pid_ki = (s_left->pid_ki + s_right->pid_ki) / 4; + s_distance->pid_kd = (s_left->pid_kd + s_right->pid_kd) / 4; // Maxima are bound by the least capable motor s_distance->max_control = min(s_left->max_control, s_right->max_control); @@ -50,11 +50,11 @@ static pbio_error_t drivebase_adopt_settings(pbio_control_settings_t *s_distance // Get the physical state of a drivebase static pbio_error_t drivebase_get_state(pbio_drivebase_t *db, - int32_t *time_now, - int32_t *sum, - int32_t *sum_rate, - int32_t *dif, - int32_t *dif_rate) { + int32_t *time_now, + int32_t *sum, + int32_t *sum_rate, + int32_t *dif, + int32_t *dif_rate) { pbio_error_t err; @@ -143,14 +143,14 @@ static pbio_error_t pbio_drivebase_actuate(pbio_drivebase_t *db, pbio_actuation_ } // Log motor data for a motor that is being actively controlled -static pbio_error_t drivebase_log_update(pbio_drivebase_t *db, - int32_t time_now, - int32_t sum, - int32_t sum_rate, - int32_t sum_control, - int32_t dif, - int32_t dif_rate, - int32_t dif_control) { +static pbio_error_t drivebase_log_update(pbio_drivebase_t *db, + int32_t time_now, + int32_t sum, + int32_t sum_rate, + int32_t sum_control, + int32_t dif, + int32_t dif_rate, + int32_t dif_control) { int32_t buf[DRIVEBASE_LOG_NUM_VALUES]; buf[0] = time_now; @@ -224,34 +224,34 @@ pbio_error_t pbio_drivebase_setup(pbio_drivebase_t *db, pbio_servo_t *left, pbio } // Count difference between the motors for every 1 degree drivebase rotation - db->control_heading.settings.counts_per_unit = - fix16_mul( - left->control.settings.counts_per_unit, - fix16_div( - fix16_mul( - axle_track, - fix16_from_int(2) - ), - wheel_diameter - ) - ); + db->control_heading.settings.counts_per_unit = + fix16_mul( + left->control.settings.counts_per_unit, + fix16_div( + fix16_mul( + axle_track, + fix16_from_int(2) + ), + wheel_diameter + ) + ); // Sum of motor counts for every 1 mm forward db->control_distance.settings.counts_per_unit = - fix16_mul( - left->control.settings.counts_per_unit, - fix16_div( - fix16_mul( - fix16_from_int(180), - FOUR_DIV_PI - ), - wheel_diameter - ) - ); + fix16_mul( + left->control.settings.counts_per_unit, + fix16_div( + fix16_mul( + fix16_from_int(180), + FOUR_DIV_PI + ), + wheel_diameter + ) + ); return PBIO_SUCCESS; } - + // Claim servos so that they cannot be used independently void pbio_drivebase_claim_servos(pbio_drivebase_t *db, bool claim) { // Stop control @@ -276,8 +276,7 @@ pbio_error_t pbio_drivebase_stop(pbio_drivebase_t *db, pbio_actuation_t after_st if (err != PBIO_SUCCESS) { return err; } - } - else { + } else { // Otherwise the payload is zero and control stops pbio_control_stop(&db->control_distance); pbio_control_stop(&db->control_heading); @@ -436,8 +435,7 @@ pbio_error_t pbio_drivebase_drive(pbio_drivebase_t *db, int32_t speed, int32_t t if (err != PBIO_SUCCESS) { return err; } - } - else { + } else { time_now = clock_usecs(); } @@ -463,10 +461,10 @@ pbio_error_t pbio_drivebase_get_state(pbio_drivebase_t *db, int32_t *distance, i if (err != PBIO_SUCCESS) { return err; } - *distance = pbio_control_counts_to_user(&db->control_distance.settings, sum - db->sum_offset); + *distance = pbio_control_counts_to_user(&db->control_distance.settings, sum - db->sum_offset); *drive_speed = pbio_control_counts_to_user(&db->control_distance.settings, sum_rate); - *angle = pbio_control_counts_to_user(&db->control_heading.settings, dif - db->dif_offset); - *turn_rate = pbio_control_counts_to_user(&db->control_heading.settings, dif_rate); + *angle = pbio_control_counts_to_user(&db->control_heading.settings, dif - db->dif_offset); + *turn_rate = pbio_control_counts_to_user(&db->control_heading.settings, dif_rate); return PBIO_SUCCESS; } diff --git a/lib/pbio/src/error.c b/lib/pbio/src/error.c index 02ab69e7f..9c45202a3 100644 --- a/lib/pbio/src/error.c +++ b/lib/pbio/src/error.c @@ -17,30 +17,30 @@ */ const char *pbio_error_str(pbio_error_t err) { switch (err) { - case PBIO_SUCCESS: - break; - case PBIO_ERROR_FAILED: - return "Unknown error"; - case PBIO_ERROR_INVALID_ARG: - return "Invalid argument"; - case PBIO_ERROR_INVALID_PORT: - return "Invalid port"; - case PBIO_ERROR_IO: - return "I/O error"; - case PBIO_ERROR_NO_DEV: - return "Device not connected"; - case PBIO_ERROR_NOT_IMPLEMENTED: - return "Not implemented"; - case PBIO_ERROR_NOT_SUPPORTED: - return "Not supported"; - case PBIO_ERROR_AGAIN: - return "Try again later"; - case PBIO_ERROR_INVALID_OP: - return "Invalid operation"; - case PBIO_ERROR_TIMEDOUT: - return "Timed out"; - case PBIO_ERROR_CANCELED: - return "Canceled"; + case PBIO_SUCCESS: + break; + case PBIO_ERROR_FAILED: + return "Unknown error"; + case PBIO_ERROR_INVALID_ARG: + return "Invalid argument"; + case PBIO_ERROR_INVALID_PORT: + return "Invalid port"; + case PBIO_ERROR_IO: + return "I/O error"; + case PBIO_ERROR_NO_DEV: + return "Device not connected"; + case PBIO_ERROR_NOT_IMPLEMENTED: + return "Not implemented"; + case PBIO_ERROR_NOT_SUPPORTED: + return "Not supported"; + case PBIO_ERROR_AGAIN: + return "Try again later"; + case PBIO_ERROR_INVALID_OP: + return "Invalid operation"; + case PBIO_ERROR_TIMEDOUT: + return "Timed out"; + case PBIO_ERROR_CANCELED: + return "Canceled"; } return NULL; diff --git a/lib/pbio/src/integrator.c b/lib/pbio/src/integrator.c index b102eaa6a..f6031bf3d 100644 --- a/lib/pbio/src/integrator.c +++ b/lib/pbio/src/integrator.c @@ -60,12 +60,12 @@ void pbio_rate_integrator_reset(pbio_rate_integrator_t *itg, int32_t time_now, i // Get reference errors and integrals void pbio_rate_integrator_get_errors(pbio_rate_integrator_t *itg, - int32_t rate, - int32_t rate_ref, - int32_t count, - int32_t count_ref, - int32_t *rate_err, - int32_t *rate_err_integral) { + int32_t rate, + int32_t rate_ref, + int32_t count, + int32_t count_ref, + int32_t *rate_err, + int32_t *rate_err_integral) { // The rate error is simply the instantaneous error *rate_err = rate_ref - rate; @@ -96,7 +96,7 @@ bool pbio_rate_integrator_stalled(pbio_rate_integrator_t *itg, int32_t time_now, } // All checks have failed, so we are stalled - return true; + return true; } /* Count integrator used for position-based control */ @@ -160,20 +160,20 @@ void pbio_count_integrator_update(pbio_count_integrator_t *itg, int32_t time_now int32_t cerr = itg->count_err_prev; // Check if integrator magnitude would decrease due to this error - bool decrease = abs(itg->count_err_integral + cerr*(time_now - itg->time_prev)) < abs(itg->count_err_integral); - + bool decrease = abs(itg->count_err_integral + cerr * (time_now - itg->time_prev)) < abs(itg->count_err_integral); + // If not deceasing, so growing, limit error growth by maximum integral rate if (!decrease) { - cerr = cerr > integral_rate ? integral_rate : cerr; + cerr = cerr > integral_rate ? integral_rate : cerr; cerr = cerr < -integral_rate ? -integral_rate : cerr; // It might be decreasing now after all (due to integral sign change), so re-evaluate - decrease = abs(itg->count_err_integral + cerr*(time_now - itg->time_prev)) < abs(itg->count_err_integral); + decrease = abs(itg->count_err_integral + cerr * (time_now - itg->time_prev)) < abs(itg->count_err_integral); } // Add change if we are near target, or always if it decreases the integral magnitude if (abs(count_target - count_ref) <= integral_range || decrease) { - itg->count_err_integral += cerr*(time_now - itg->time_prev); + itg->count_err_integral += cerr * (time_now - itg->time_prev); } // Limit integral to predefined bound @@ -214,5 +214,5 @@ bool pbio_count_integrator_stalled(pbio_count_integrator_t *itg, int32_t time_no } // All checks have failed, so we are stalled - return true; + return true; }; diff --git a/lib/pbio/src/iodev.c b/lib/pbio/src/iodev.c index aad045c43..954ac5aad 100644 --- a/lib/pbio/src/iodev.c +++ b/lib/pbio/src/iodev.c @@ -15,13 +15,13 @@ */ size_t pbio_iodev_size_of(pbio_iodev_data_type_t type) { switch (type) { - case PBIO_IODEV_DATA_TYPE_INT8: - return 1; - case PBIO_IODEV_DATA_TYPE_INT16: - return 2; - case PBIO_IODEV_DATA_TYPE_INT32: - case PBIO_IODEV_DATA_TYPE_FLOAT: - return 4; + case PBIO_IODEV_DATA_TYPE_INT8: + return 1; + case PBIO_IODEV_DATA_TYPE_INT16: + return 2; + case PBIO_IODEV_DATA_TYPE_INT32: + case PBIO_IODEV_DATA_TYPE_FLOAT: + return 4; } assert(0); // bug if reached diff --git a/lib/pbio/src/light.c b/lib/pbio/src/light.c index 932c89073..125042eb3 100644 --- a/lib/pbio/src/light.c +++ b/lib/pbio/src/light.c @@ -72,24 +72,24 @@ void _pbio_light_poll(uint32_t now) { data = user_light_data; switch (data.pattern) { - case PBIO_LIGHT_PATTERN_NONE: - break; - case PBIO_LIGHT_PATTERN_BREATHE: - // breathe pattern has 64 values over the course of two seconds (2048ms) - idx = (now >> 5) & (64 - 1); - scale = breathe_pattern_data[idx] + 1; - data.r = data.r * scale / 256; - data.g = data.g * scale / 256; - data.b = data.b * scale / 256; - break; - case PBIO_LIGHT_PATTERN_FLASH: - // flash pattern has 8 value over the course of two seconds (2048ms) - idx = (now >> 8) & (8 - 1); - scale = flash_pattern_data[idx] + 1; - data.r = data.r * scale / 256; - data.g = data.g * scale / 256; - data.b = data.b * scale / 256; - break; + case PBIO_LIGHT_PATTERN_NONE: + break; + case PBIO_LIGHT_PATTERN_BREATHE: + // breathe pattern has 64 values over the course of two seconds (2048ms) + idx = (now >> 5) & (64 - 1); + scale = breathe_pattern_data[idx] + 1; + data.r = data.r * scale / 256; + data.g = data.g * scale / 256; + data.b = data.b * scale / 256; + break; + case PBIO_LIGHT_PATTERN_FLASH: + // flash pattern has 8 value over the course of two seconds (2048ms) + idx = (now >> 8) & (8 - 1); + scale = flash_pattern_data[idx] + 1; + data.r = data.r * scale / 256; + data.g = data.g * scale / 256; + data.b = data.b * scale / 256; + break; } pbdrv_light_set_rgb(PBIO_PORT_SELF, data.r, data.g, data.b); diff --git a/lib/pbio/src/logger.c b/lib/pbio/src/logger.c index f8f3cabc3..b8193d09b 100644 --- a/lib/pbio/src/logger.c +++ b/lib/pbio/src/logger.c @@ -68,11 +68,11 @@ pbio_error_t pbio_logger_update(pbio_log_t *log, int32_t *buf) { } // Write time of logging - log->data[log->sampled*log->num_values] = (clock_usecs() - log->start)/1000; + log->data[log->sampled * log->num_values] = (clock_usecs() - log->start) / 1000; // Write the data for (uint8_t i = NUM_DEFAULT_LOG_VALUES; i < log->num_values; i++) { - log->data[log->sampled*log->num_values + i] = buf[i-NUM_DEFAULT_LOG_VALUES]; + log->data[log->sampled * log->num_values + i] = buf[i - NUM_DEFAULT_LOG_VALUES]; } // Increment sample counter @@ -98,7 +98,7 @@ pbio_error_t pbio_logger_read(pbio_log_t *log, int32_t sindex, int32_t *buf) { // Read the data for (uint8_t i = 0; i < log->num_values; i++) { - buf[i] = log->data[index*log->num_values + i]; + buf[i] = log->data[index * log->num_values + i]; } return PBIO_SUCCESS; diff --git a/lib/pbio/src/main.c b/lib/pbio/src/main.c index 4ae429c19..ec0391067 100644 --- a/lib/pbio/src/main.c +++ b/lib/pbio/src/main.c @@ -54,7 +54,7 @@ AUTOSTART_PROCESSES( #if PBIO_CONFIG_ENABLE_SYS ,&pbsys_process #endif -); + ); /** * Initialize the Pybricks I/O Library. This function must be called once, diff --git a/lib/pbio/src/math.c b/lib/pbio/src/math.c index aa1e42bdd..a9b7f094b 100644 --- a/lib/pbio/src/math.c +++ b/lib/pbio/src/math.c @@ -39,7 +39,7 @@ int32_t pbio_math_sqrt(int32_t n) { int32_t x1 = x0; while (true) { - x1 = (x0 + n/x0)/2; + x1 = (x0 + n / x0) / 2; if (x1 == x0 || x1 == x0 + 1) { return x0; } diff --git a/lib/pbio/src/serial.c b/lib/pbio/src/serial.c index 45410b6bd..914fa4090 100644 --- a/lib/pbio/src/serial.c +++ b/lib/pbio/src/serial.c @@ -34,7 +34,7 @@ pbio_error_t pbio_serial_get(pbio_serial_t **_ser, pbio_port_t port, int baudrat return PBIO_ERROR_INVALID_PORT; } - pbio_serial_t *ser = &serials[port-PBDRV_CONFIG_IOPORT_LPF2_FIRST_PORT]; + pbio_serial_t *ser = &serials[port - PBDRV_CONFIG_IOPORT_LPF2_FIRST_PORT]; pbio_error_t err = pbdrv_serial_get(&ser->dev, port, baudrate); @@ -65,7 +65,7 @@ static pbio_error_t pbio_serial_read_start(pbio_serial_t *ser, size_t count) { // Reset state variables ser->busy = true; - ser->time_start = clock_usecs()/1000; + ser->time_start = clock_usecs() / 1000; ser->remaining = count; return PBIO_SUCCESS; @@ -105,7 +105,7 @@ pbio_error_t pbio_serial_read(pbio_serial_t *ser, uint8_t *buf, size_t count) { } // If we have timed out, let the user know - if (ser->timeout >= 0 && clock_usecs()/1000 - ser->time_start > ser->timeout) { + if (ser->timeout >= 0 && clock_usecs() / 1000 - ser->time_start > ser->timeout) { return pbio_serial_read_stop(ser, PBIO_ERROR_TIMEDOUT); } diff --git a/lib/pbio/src/servo.c b/lib/pbio/src/servo.c index 680a7485f..625c5b710 100644 --- a/lib/pbio/src/servo.c +++ b/lib/pbio/src/servo.c @@ -24,7 +24,7 @@ static pbio_control_settings_t settings_servo_ev3_medium = { .rate_tolerance = 100, .count_tolerance = 10, .stall_rate_limit = 30, - .stall_time = 200*US_PER_MS, + .stall_time = 200 * US_PER_MS, .pid_kp = 300, .pid_ki = 400, .pid_kd = 3, @@ -41,7 +41,7 @@ static pbio_control_settings_t settings_servo_ev3_large = { .rate_tolerance = 100, .count_tolerance = 10, .stall_rate_limit = 30, - .stall_time = 200*US_PER_MS, + .stall_time = 200 * US_PER_MS, .pid_kp = 400, .pid_ki = 1200, .pid_kd = 5, @@ -58,7 +58,7 @@ static pbio_control_settings_t settings_servo_move_hub = { .rate_tolerance = 50, .count_tolerance = 6, .stall_rate_limit = 15, - .stall_time = 200*US_PER_MS, + .stall_time = 200 * US_PER_MS, .pid_kp = 400, .pid_ki = 600, .pid_kd = 5, @@ -75,7 +75,7 @@ static pbio_control_settings_t settings_servo_boost_interactive = { .rate_tolerance = 50, .count_tolerance = 5, .stall_rate_limit = 15, - .stall_time = 200*US_PER_MS, + .stall_time = 200 * US_PER_MS, .pid_kp = 600, .pid_ki = 600, .pid_kd = 5, @@ -92,7 +92,7 @@ static pbio_control_settings_t settings_servo_cplus_xl = { .rate_tolerance = 50, .count_tolerance = 10, .stall_rate_limit = 20, - .stall_time = 200*US_PER_MS, + .stall_time = 200 * US_PER_MS, .pid_kp = 250, .pid_ki = 350, .pid_kd = 0, @@ -109,7 +109,7 @@ static pbio_control_settings_t settings_servo_default = { .rate_tolerance = 5, .count_tolerance = 3, .stall_rate_limit = 2, - .stall_time = 200*US_PER_MS, + .stall_time = 200 * US_PER_MS, .pid_kp = 200, .pid_ki = 100, .pid_kd = 0, @@ -255,14 +255,14 @@ static pbio_error_t pbio_servo_actuate(pbio_servo_t *srv, pbio_actuation_t actua // Apply the calculated actuation, by type switch (actuation_type) { - case PBIO_ACTUATION_COAST: - return pbio_dcmotor_coast(srv->dcmotor); - case PBIO_ACTUATION_BRAKE: - return pbio_dcmotor_brake(srv->dcmotor); - case PBIO_ACTUATION_HOLD: - return pbio_control_start_hold_control(&srv->control, clock_usecs(), control); - case PBIO_ACTUATION_DUTY: - return pbio_dcmotor_set_duty_cycle_sys(srv->dcmotor, control); + case PBIO_ACTUATION_COAST: + return pbio_dcmotor_coast(srv->dcmotor); + case PBIO_ACTUATION_BRAKE: + return pbio_dcmotor_brake(srv->dcmotor); + case PBIO_ACTUATION_HOLD: + return pbio_control_start_hold_control(&srv->control, clock_usecs(), control); + case PBIO_ACTUATION_DUTY: + return pbio_dcmotor_set_duty_cycle_sys(srv->dcmotor, control); } return PBIO_SUCCESS; @@ -273,7 +273,7 @@ static pbio_error_t pbio_servo_log_update(pbio_servo_t *srv, int32_t time_now, i int32_t buf[SERVO_LOG_NUM_VALUES]; memset(buf, 0, sizeof(buf)); - + // Log the physical state of the motor buf[1] = count_now; buf[2] = rate_now; @@ -284,7 +284,7 @@ static pbio_error_t pbio_servo_log_update(pbio_servo_t *srv, int32_t time_now, i // If control is active, log additional data about the maneuver if (srv->control.type != PBIO_CONTROL_NONE) { - + // Get the time of reference evaluation int32_t time_ref = pbio_control_get_ref_time(&srv->control, time_now); @@ -297,8 +297,7 @@ static pbio_error_t pbio_servo_log_update(pbio_servo_t *srv, int32_t time_now, i if (srv->control.type == PBIO_CONTROL_ANGLE) { pbio_count_integrator_get_errors(&srv->control.count_integrator, count_now, count_ref, &err, &err_integral); - } - else { + } else { pbio_rate_integrator_get_errors(&srv->control.rate_integrator, rate_now, rate_ref, count_now, count_ref, &err, &err_integral); } @@ -378,8 +377,7 @@ pbio_error_t pbio_servo_stop(pbio_servo_t *srv, pbio_actuation_t after_stop) { if (err != PBIO_SUCCESS) { return err; } - } - else { + } else { // Otherwise the payload is zero and control stops control = 0; pbio_control_stop(&srv->control); @@ -399,8 +397,7 @@ pbio_error_t pbio_servo_stop_force(pbio_servo_t *srv) { // Try to stop / coast motor whether or not initialized already if (srv->dcmotor) { return pbio_dcmotor_coast(srv->dcmotor); - } - else { + } else { return pbdrv_motor_coast(srv->port); } } @@ -430,8 +427,7 @@ pbio_error_t pbio_servo_run(pbio_servo_t *srv, int32_t speed) { if (err != PBIO_SUCCESS) { return err; } - } - else { + } else { time_now = clock_usecs(); } @@ -459,7 +455,7 @@ pbio_error_t pbio_servo_run_time(pbio_servo_t *srv, int32_t speed, int32_t durat } // Start a timed maneuver, duration finite - return pbio_control_start_timed_control(&srv->control, time_now, duration*US_PER_MS, count_now, rate_now, target_rate, srv->control.settings.abs_acceleration, pbio_control_on_target_time, after_stop); + return pbio_control_start_timed_control(&srv->control, time_now, duration * US_PER_MS, count_now, rate_now, target_rate, srv->control.settings.abs_acceleration, pbio_control_on_target_time, after_stop); } pbio_error_t pbio_servo_run_until_stalled(pbio_servo_t *srv, int32_t speed, pbio_actuation_t after_stop) { diff --git a/lib/pbio/src/sound.c b/lib/pbio/src/sound.c index 445fd5a20..c3445c88e 100644 --- a/lib/pbio/src/sound.c +++ b/lib/pbio/src/sound.c @@ -64,7 +64,7 @@ static pbio_error_t beep_start(pbio_sound_t *sound, uint32_t freq, int32_t durat // Reset state variables sound->busy = true; - sound->time_start = clock_usecs()/1000; + sound->time_start = clock_usecs() / 1000; sound->time_duration = duration; // Start beeping by setting the frequency @@ -97,7 +97,7 @@ pbio_error_t pbio_sound_beep(pbio_sound_t *sound, uint32_t freq, int32_t duratio } // If we are done, stop - if (clock_usecs()/1000 - sound->time_start > duration) { + if (clock_usecs() / 1000 - sound->time_start > duration) { return beep_stop(sound, PBIO_SUCCESS); } @@ -119,7 +119,7 @@ static pbio_error_t file_start(pbio_sound_t *sound, const char *path) { // Reset state variables sound->busy = true; - sound->time_start = clock_usecs()/1000; + sound->time_start = clock_usecs() / 1000; // Init the sound return pbdrv_pcm_play_file_start(sound->pcm_dev, path, &sound->time_duration); @@ -160,7 +160,7 @@ pbio_error_t pbio_sound_play_file(pbio_sound_t *sound, const char *path) { return file_stop(sound, err); } // If we are done and the timer is done too, stop - if (clock_usecs()/1000 - sound->time_start > sound->time_duration) { + if (clock_usecs() / 1000 - sound->time_start > sound->time_duration) { return file_stop(sound, PBIO_SUCCESS); } diff --git a/lib/pbio/src/tacho.c b/lib/pbio/src/tacho.c index 57d60c268..c738ccf36 100644 --- a/lib/pbio/src/tacho.c +++ b/lib/pbio/src/tacho.c @@ -39,7 +39,7 @@ static pbio_error_t pbio_tacho_reset_count(pbio_tacho_t *tacho, int32_t reset_co } static pbio_error_t pbio_tacho_reset_count_to_abs(pbio_tacho_t *tacho) { - + int32_t abs_count; pbio_error_t err = pbdrv_counter_get_abs_count(tacho->counter, &abs_count); if (err != PBIO_SUCCESS) { @@ -130,8 +130,7 @@ pbio_error_t pbio_tacho_get_angle(pbio_tacho_t *tacho, int32_t *angle) { pbio_error_t pbio_tacho_reset_angle(pbio_tacho_t *tacho, int32_t reset_angle, bool reset_to_abs) { if (reset_to_abs) { return pbio_tacho_reset_count_to_abs(tacho); - } - else { + } else { return pbio_tacho_reset_count(tacho, pbio_math_mul_i32_fix16(reset_angle, tacho->counts_per_degree)); } } diff --git a/lib/pbio/src/trajectory.c b/lib/pbio/src/trajectory.c index 531892d56..118ba9229 100644 --- a/lib/pbio/src/trajectory.c +++ b/lib/pbio/src/trajectory.c @@ -11,27 +11,27 @@ #include static int64_t as_mcount(int32_t count, int32_t count_ext) { - return ((int64_t) count)*1000 + count_ext; + return ((int64_t)count) * 1000 + count_ext; } static void as_count(int64_t mcount, int32_t *count, int32_t *count_ext) { - *count = (int32_t) (mcount/1000); - *count_ext = mcount - ((int64_t) *count)*1000; + *count = (int32_t)(mcount / 1000); + *count_ext = mcount - ((int64_t)*count) * 1000; } void reverse_trajectory(pbio_trajectory_t *ref) { // Mirror angles about initial angle th0 - // First load as high res types + // First load as high res types int64_t mth0 = as_mcount(ref->th0, ref->th0_ext); int64_t mth1 = as_mcount(ref->th1, ref->th1_ext); int64_t mth2 = as_mcount(ref->th2, ref->th2_ext); int64_t mth3 = as_mcount(ref->th3, ref->th3_ext); // Perform the math - mth1 = 2*mth0 - mth1; - mth2 = 2*mth0 - mth2; - mth3 = 2*mth0 - mth3; + mth1 = 2 * mth0 - mth1; + mth2 = 2 * mth0 - mth2; + mth3 = 2 * mth0 - mth3; // Store as simple type again as_count(mth1, &ref->th1, &ref->th1_ext); @@ -75,11 +75,11 @@ void pbio_trajectory_make_stationary(pbio_trajectory_t *ref, int32_t t0, int32_t } static int64_t x_time(int32_t b, int32_t t) { - return (((int64_t) b) * ((int64_t) t))/US_PER_MS; + return (((int64_t)b) * ((int64_t)t)) / US_PER_MS; } static int64_t x_time2(int32_t b, int32_t t) { - return x_time(x_time(b, t), t)/(2*US_PER_MS); + return x_time(x_time(b, t), t) / (2 * US_PER_MS); } pbio_error_t pbio_trajectory_make_time_based(pbio_trajectory_t *ref, int32_t t0, int32_t duration, int32_t th0, int32_t th0_ext, int32_t w0, int32_t wt, int32_t wmax, int32_t a, int32_t amax) { @@ -93,12 +93,11 @@ pbio_error_t pbio_trajectory_make_time_based(pbio_trajectory_t *ref, int32_t t0, // Duration of the maneuver if (duration == DURATION_FOREVER) { // In case of forever, we set the duration to a fictitious 60 seconds. - t3mt0 = 60*US_PER_SECOND; + t3mt0 = 60 * US_PER_SECOND; // This is an infinite maneuver. (This means we'll just ignore the deceleration // phase when computing references later, so we keep going even after 60 seconds.) - ref->forever = true; - } - else { + ref->forever = true; + } else { // Otherwise, the interval is just the duration t3mt0 = duration; // This is a finite maneuver @@ -133,21 +132,21 @@ pbio_error_t pbio_trajectory_make_time_based(pbio_trajectory_t *ref, int32_t t0, // Therefore accelerate ref->a0 = a; // If target speed can be reached - if (wdiva(wt-w0, a) - (t3mt0-wdiva(w0, a))/2 < 0) { - t1mt0 = wdiva(wt-w0, a); + if (wdiva(wt - w0, a) - (t3mt0 - wdiva(w0, a)) / 2 < 0) { + t1mt0 = wdiva(wt - w0, a); ref->w1 = wt; } // If target speed cannot be reached else { - t1mt0 = (t3mt0-wdiva(w0, a))/2; - ref->w1 = timest(a, t3mt0)/2+w0/2; + t1mt0 = (t3mt0 - wdiva(w0, a)) / 2; + ref->w1 = timest(a, t3mt0) / 2 + w0 / 2; } } // Initial speed is more than the target speed else if (w0 > wt) { // Therefore decelerate ref->a0 = -a; - t1mt0 = wdiva(w0-wt, a); + t1mt0 = wdiva(w0 - wt, a); ref->w1 = wt; } // Initial speed is equal to the target speed @@ -218,7 +217,7 @@ pbio_error_t pbio_trajectory_make_angle_based(pbio_trajectory_t *ref, int32_t t0 // Convert user parameters into a forward maneuver to simplify computations (we negate results at the end) if (backward) { - th3 = 2*th0 - th3; + th3 = 2 * th0 - th3; w0 *= -1; } @@ -233,8 +232,8 @@ pbio_error_t pbio_trajectory_make_angle_based(pbio_trajectory_t *ref, int32_t t0 w0 = max(-wmax, min(w0, wmax)); // Limit initial speed, but evaluate square root only if necessary (usually not) - if (w0 > 0 && (w0*w0)/(2*a) > th3 - th0) { - w0 = pbio_math_sqrt(2*a*(th3 - th0)); + if (w0 > 0 && (w0 * w0) / (2 * a) > th3 - th0) { + w0 = pbio_math_sqrt(2 * a * (th3 - th0)); } // Initial speed is less than the target speed @@ -244,33 +243,32 @@ pbio_error_t pbio_trajectory_make_angle_based(pbio_trajectory_t *ref, int32_t t0 ref->a0 = a; // Fictitious zero speed angle (ahead of us if we have negative initial speed; behind us if we have initial positive speed) - int32_t thf = th0 - (w0*w0)/(2*a); + int32_t thf = th0 - (w0 * w0) / (2 * a); // Test if we can get to ref speed - if (th3-thf >= (wt*wt)/a) { + if (th3 - thf >= (wt * wt) / a) { // If so, find both constant speed intersections - ref->th1 = thf + (wt*wt)/(2*a); - ref->th2 = th3 - (wt*wt)/(2*a); + ref->th1 = thf + (wt * wt) / (2 * a); + ref->th2 = th3 - (wt * wt) / (2 * a); ref->w1 = wt; - } - else { + } else { // Otherwise, intersect halfway between accelerating and decelerating square root arcs - ref->th1 = (th3+thf)/2; + ref->th1 = (th3 + thf) / 2; ref->th2 = ref->th1; - ref->w1 = pbio_math_sqrt(2*a*(ref->th1 - thf)); + ref->w1 = pbio_math_sqrt(2 * a * (ref->th1 - thf)); } } // Initial speed is equal to or more than the target speed else { // Therefore decelerate towards intersection from above ref->a0 = -a; - ref->th1 = th0 + (w0*w0-wt*wt)/(2*a); - ref->th2 = th3 - (wt*wt)/(2*a); + ref->th1 = th0 + (w0 * w0 - wt * wt) / (2 * a); + ref->th2 = th3 - (wt * wt) / (2 * a); ref->w1 = wt; } // Corresponding time intervals - int32_t t1mt0 = wdiva(ref->w1-w0, ref->a0); - int32_t t2mt1 = ref->th2 == ref->th1 ? 0 : wdiva(ref->th2-ref->th1, ref->w1); + int32_t t1mt0 = wdiva(ref->w1 - w0, ref->a0); + int32_t t2mt1 = ref->th2 == ref->th1 ? 0 : wdiva(ref->th2 - ref->th1, ref->w1); int32_t t3mt2 = wdiva(ref->w1, a); // Store other results/arguments @@ -307,23 +305,20 @@ void pbio_trajectory_get_reference(pbio_trajectory_t *traject, int32_t time_ref, if (time_ref - traject->t1 < 0) { // If we are here, then we are still in the acceleration phase. Includes conversion from microseconds to seconds, in two steps to avoid overflows and round off errors - *rate_ref = traject->w0 + timest(traject->a0, time_ref-traject->t0); - mcount_ref = as_mcount(traject->th0, traject->th0_ext) + x_time(traject->w0, time_ref-traject->t0) + x_time2(traject->a0, time_ref-traject->t0); + *rate_ref = traject->w0 + timest(traject->a0, time_ref - traject->t0); + mcount_ref = as_mcount(traject->th0, traject->th0_ext) + x_time(traject->w0, time_ref - traject->t0) + x_time2(traject->a0, time_ref - traject->t0); *acceleration_ref = traject->a0; - } - else if (traject->forever || time_ref - traject->t2 <= 0) { + } else if (traject->forever || time_ref - traject->t2 <= 0) { // If we are here, then we are in the constant speed phase *rate_ref = traject->w1; - mcount_ref = as_mcount(traject->th1, traject->th1_ext) + x_time(traject->w1, time_ref-traject->t1); + mcount_ref = as_mcount(traject->th1, traject->th1_ext) + x_time(traject->w1, time_ref - traject->t1); *acceleration_ref = 0; - } - else if (time_ref - traject->t3 <= 0) { + } else if (time_ref - traject->t3 <= 0) { // If we are here, then we are in the deceleration phase - *rate_ref = traject->w1 + timest(traject->a2, time_ref-traject->t2); - mcount_ref = as_mcount(traject->th2, traject->th2_ext) + x_time(traject->w1, time_ref-traject->t2) + x_time2(traject->a2, time_ref-traject->t2); + *rate_ref = traject->w1 + timest(traject->a2, time_ref - traject->t2); + mcount_ref = as_mcount(traject->th2, traject->th2_ext) + x_time(traject->w1, time_ref - traject->t2) + x_time2(traject->a2, time_ref - traject->t2); *acceleration_ref = traject->a2; - } - else { + } else { // If we are here, we are in the zero speed phase (relevant when holding position) *rate_ref = 0; mcount_ref = as_mcount(traject->th3, traject->th3_ext); @@ -334,7 +329,7 @@ void pbio_trajectory_get_reference(pbio_trajectory_t *traject, int32_t time_ref, as_count(mcount_ref, count_ref, count_ref_ext); // Rebase the reference before it overflows after 35 minutes - if (time_ref - traject->t0 > (DURATION_MAX_S+120)*MS_PER_SECOND*US_PER_MS) { + if (time_ref - traject->t0 > (DURATION_MAX_S + 120) * MS_PER_SECOND * US_PER_MS) { // Infinite maneuvers just maintain the same reference speed, continuing again from current time if (traject->forever) { pbio_trajectory_make_time_based(traject, time_ref, DURATION_FOREVER, *count_ref, *count_ref_ext, traject->w1, traject->w1, traject->w1, abs(traject->a2), abs(traject->a2)); diff --git a/lib/pbio/src/trajectory_ext.c b/lib/pbio/src/trajectory_ext.c index b3a3af684..18a7731ee 100644 --- a/lib/pbio/src/trajectory_ext.c +++ b/lib/pbio/src/trajectory_ext.c @@ -21,16 +21,15 @@ static pbio_error_t pbio_trajectory_patch(pbio_trajectory_t *ref, bool time_base pbio_error_t err; pbio_trajectory_t nominal; if (time_based) { - err = pbio_trajectory_make_time_based(&nominal, t0, duration, th0, th0_ext, w0, wt, wmax, a, amax); - } - else { + err = pbio_trajectory_make_time_based(&nominal, t0, duration, th0, th0_ext, w0, wt, wmax, a, amax); + } else { err = pbio_trajectory_make_angle_based(&nominal, t0, th0, th3, w0, wt, wmax, a, amax); } if (err != PBIO_SUCCESS) { return err; } - // If the reference acceleration equals the acceleration of the new nominal trajectory, + // If the reference acceleration equals the acceleration of the new nominal trajectory, // the trajectories are tangent at this point. Then we can patch the new trajectory // by letting its first segment be equal to the current segment of the ongoing trajectory. // This provides a seamless transition without having to resort to numerical tricks. @@ -54,8 +53,7 @@ static pbio_error_t pbio_trajectory_patch(pbio_trajectory_t *ref, bool time_base w0 = ref->w1; th0 = ref->th2; th0_ext = ref->th2_ext; - } - else { + } else { // We are in the zero speed phase, so we can restart from its starting point t0 = ref->t3; w0 = 0; @@ -72,13 +70,11 @@ static pbio_error_t pbio_trajectory_patch(pbio_trajectory_t *ref, bool time_base // with a point on the existing trajectory if (time_based) { return pbio_trajectory_make_time_based(ref, t0, duration, th0, th0_ext, w0, wt, wmax, a, amax); - } - else { + } else { return pbio_trajectory_make_angle_based(ref, t0, th0, th3, w0, wt, wmax, a, amax); } - - } - else { + + } else { // Trajectories were not tangent, so just return the nominal, unpatched trajectory *ref = nominal; return PBIO_SUCCESS; diff --git a/lib/pbio/src/uartdev.c b/lib/pbio/src/uartdev.c index 8cabc4feb..6ce3d0b99 100644 --- a/lib/pbio/src/uartdev.c +++ b/lib/pbio/src/uartdev.c @@ -100,20 +100,20 @@ enum ev3_uart_info_flags { EV3_UART_INFO_FLAG_INFO_FORMAT = 1 << EV3_UART_INFO_BIT_INFO_FORMAT, EV3_UART_INFO_FLAG_ALL_INFO = EV3_UART_INFO_FLAG_INFO_NAME - | EV3_UART_INFO_FLAG_INFO_RAW - | EV3_UART_INFO_FLAG_INFO_PCT - | EV3_UART_INFO_FLAG_INFO_SI - | EV3_UART_INFO_FLAG_INFO_UNITS - | EV3_UART_INFO_FLAG_INFO_MAPPING - | EV3_UART_INFO_FLAG_INFO_MODE_COMBOS - | EV3_UART_INFO_FLAG_INFO_UNK7 - | EV3_UART_INFO_FLAG_INFO_UNK8 - | EV3_UART_INFO_FLAG_INFO_UNK9 - | EV3_UART_INFO_FLAG_INFO_FORMAT, + | EV3_UART_INFO_FLAG_INFO_RAW + | EV3_UART_INFO_FLAG_INFO_PCT + | EV3_UART_INFO_FLAG_INFO_SI + | EV3_UART_INFO_FLAG_INFO_UNITS + | EV3_UART_INFO_FLAG_INFO_MAPPING + | EV3_UART_INFO_FLAG_INFO_MODE_COMBOS + | EV3_UART_INFO_FLAG_INFO_UNK7 + | EV3_UART_INFO_FLAG_INFO_UNK8 + | EV3_UART_INFO_FLAG_INFO_UNK9 + | EV3_UART_INFO_FLAG_INFO_FORMAT, EV3_UART_INFO_FLAG_REQUIRED = EV3_UART_INFO_FLAG_CMD_TYPE - | EV3_UART_INFO_FLAG_CMD_MODES - | EV3_UART_INFO_FLAG_INFO_NAME - | EV3_UART_INFO_FLAG_INFO_FORMAT, + | EV3_UART_INFO_FLAG_CMD_MODES + | EV3_UART_INFO_FLAG_INFO_NAME + | EV3_UART_INFO_FLAG_INFO_FORMAT, }; /** @@ -140,12 +140,12 @@ typedef enum { * @status: The current device connection state * @type_id: The type ID received * @requested_mode: Mode that was requested by user. Used to restore previous - * mode in case of a reconnect. + * mode in case of a reconnect. * @new_mode: The mode requested by set_mode. Also used to keep track of mode * in INFO messages while syncing. * @new_baud_rate: New baud rate that will be set with ev3_uart_change_bitrate * @info_flags: Flags indicating what information has already been read - * from the data. + * from the data. * @tacho_count: The tacho count received from an LPF2 motor * @abs_pos: The absolute position received from an LPF2 motor * @tx_msg: Buffer to hold messages transmitted to the device @@ -159,7 +159,7 @@ typedef enum { * @err_count: Total number of errors that have occurred * @num_data_err: Number of bad reads when receiving DATA data->msgs. * @data_rec: Flag that indicates that good DATA data->msg has been received - * since last watchdog timeout. + * since last watchdog timeout. * @tx_busy: mutex that protects tx_msg * @mode_change_tx_done: Flag to keep ev3_uart_set_mode_end() blocked until * mode has actually changed @@ -220,10 +220,10 @@ static uint8_t bufs[PBIO_CONFIG_UARTDEV_NUM_DEV][NUM_BUF][EV3_UART_MAX_MESSAGE_S static uartdev_port_data_t dev_data[PBIO_CONFIG_UARTDEV_NUM_DEV]; static const pbio_iodev_mode_t ev3_uart_default_mode_info = { - .raw_max = 1023, - .pct_max = 100, - .si_max = 1, - .digits = 4, + .raw_max = 1023, + .pct_max = 100, + .si_max = 1, + .digits = 4, }; #define PBIO_PT_WAIT_READY(pt, expr) PT_WAIT_UNTIL((pt), (expr) != PBIO_ERROR_AGAIN) @@ -273,9 +273,10 @@ static uint8_t ev3_uart_get_msg_size(uint8_t header) { size = LUMP_MSG_SIZE(header); size += 2; /* header and checksum */ - if ((header & LUMP_MSG_TYPE_MASK) == LUMP_MSG_TYPE_INFO) + if ((header & LUMP_MSG_TYPE_MASK) == LUMP_MSG_TYPE_INFO) { size++; /* extra command byte */ + } return size; } @@ -283,23 +284,23 @@ static void pbio_uartdev_set_mode_flags(pbio_iodev_type_id_t type_id, uint8_t mo memset(flags, 0, sizeof(*flags)); switch (type_id) { - case PBIO_IODEV_TYPE_ID_INTERACTIVE_MOTOR: - switch (mode) { - case 0: // POWER - flags->flags0 = LUMP_MODE_FLAGS0_MOTOR_POWER | LUMP_MODE_FLAGS0_MOTOR; - break; - case 1: // SPEED - flags->flags0 = LUMP_MODE_FLAGS0_MOTOR_SPEED | LUMP_MODE_FLAGS0_MOTOR; + case PBIO_IODEV_TYPE_ID_INTERACTIVE_MOTOR: + switch (mode) { + case 0: // POWER + flags->flags0 = LUMP_MODE_FLAGS0_MOTOR_POWER | LUMP_MODE_FLAGS0_MOTOR; + break; + case 1: // SPEED + flags->flags0 = LUMP_MODE_FLAGS0_MOTOR_SPEED | LUMP_MODE_FLAGS0_MOTOR; + break; + case 2: // POS + flags->flags0 = LUMP_MODE_FLAGS0_MOTOR_REL_POS | LUMP_MODE_FLAGS0_MOTOR; + break; + } + flags->flags4 = LUMP_MODE_FLAGS4_USES_HBRIDGE; + flags->flags5 = LUMP_MODE_FLAGS5_UNKNOWN_BIT1; // TODO: figure out what this flag means break; - case 2: // POS - flags->flags0 = LUMP_MODE_FLAGS0_MOTOR_REL_POS | LUMP_MODE_FLAGS0_MOTOR; + default: break; - } - flags->flags4 = LUMP_MODE_FLAGS4_USES_HBRIDGE; - flags->flags5 = LUMP_MODE_FLAGS5_UNKNOWN_BIT1; // TODO: figure out what this flag means - break; - default: - break; } } @@ -320,8 +321,7 @@ static void pbio_uartdev_parse_msg(uartdev_port_data_t *data) { if (msg_type == LUMP_MSG_TYPE_INFO && (cmd2 & LUMP_INFO_MODE_PLUS_8)) { mode += 8; cmd2 &= ~LUMP_INFO_MODE_PLUS_8; - } - else { + } else { mode += data->ext_mode; } @@ -350,346 +350,339 @@ static void pbio_uartdev_parse_msg(uartdev_port_data_t *data) { } switch (msg_type) { - case LUMP_MSG_TYPE_SYS: - switch(cmd) { - case LUMP_SYS_SYNC: - /* IR sensor (type 33) sends checksum after SYNC */ - if (msg_size > 1 && (cmd ^ cmd2) == 0xFF) { - msg_size++; - } - break; - case LUMP_SYS_ACK: - if (!data->info->num_modes) { - DBG_ERR(data->last_err = "Received ACK before all mode INFO"); - goto err; - } - if ((data->info_flags & EV3_UART_INFO_FLAG_REQUIRED) != EV3_UART_INFO_FLAG_REQUIRED) { - DBG_ERR(data->last_err = "Did not receive all required INFO"); - goto err; - } + case LUMP_MSG_TYPE_SYS: + switch (cmd) { + case LUMP_SYS_SYNC: + /* IR sensor (type 33) sends checksum after SYNC */ + if (msg_size > 1 && (cmd ^ cmd2) == 0xFF) { + msg_size++; + } + break; + case LUMP_SYS_ACK: + if (!data->info->num_modes) { + DBG_ERR(data->last_err = "Received ACK before all mode INFO"); + goto err; + } + if ((data->info_flags & EV3_UART_INFO_FLAG_REQUIRED) != EV3_UART_INFO_FLAG_REQUIRED) { + DBG_ERR(data->last_err = "Did not receive all required INFO"); + goto err; + } + + data->status = PBIO_UARTDEV_STATUS_ACK; + data->iodev.mode = data->new_mode; - data->status = PBIO_UARTDEV_STATUS_ACK; - data->iodev.mode = data->new_mode; - - return; - } - break; - case LUMP_MSG_TYPE_CMD: - switch (cmd) { - case LUMP_CMD_MODES: - if (test_and_set_bit(EV3_UART_INFO_BIT_CMD_MODES, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate modes INFO"); - goto err; - } - if (cmd2 > LUMP_MAX_MODE) { - DBG_ERR(data->last_err = "Number of modes is out of range"); - goto err; - } - data->info->num_modes = cmd2 + 1; - if (msg_size > 5) { - // Powered Up devices can have an extended mode message that - // includes modes > LUMP_MAX_MODE - data->info->num_modes = data->rx_msg[3] + 1; - data->info->num_view_modes = data->rx_msg[4] + 1; - } - else if (msg_size > 3) { - data->info->num_view_modes = data->rx_msg[2] + 1; - } - else { - data->info->num_view_modes = data->info->num_modes; + return; } - - debug_pr("num_modes: %d\n", data->info->num_modes); - debug_pr("num_view_modes: %d\n", data->info->num_view_modes); - break; - case LUMP_CMD_SPEED: - if (test_and_set_bit(EV3_UART_INFO_BIT_CMD_SPEED, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate speed INFO"); - goto err; - } - speed = uint32_le(data->rx_msg + 1); - if (speed < EV3_UART_SPEED_MIN || speed > EV3_UART_SPEED_MAX) { - DBG_ERR(data->last_err = "Speed is out of range"); - goto err; + case LUMP_MSG_TYPE_CMD: + switch (cmd) { + case LUMP_CMD_MODES: + if (test_and_set_bit(EV3_UART_INFO_BIT_CMD_MODES, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate modes INFO"); + goto err; + } + if (cmd2 > LUMP_MAX_MODE) { + DBG_ERR(data->last_err = "Number of modes is out of range"); + goto err; + } + data->info->num_modes = cmd2 + 1; + if (msg_size > 5) { + // Powered Up devices can have an extended mode message that + // includes modes > LUMP_MAX_MODE + data->info->num_modes = data->rx_msg[3] + 1; + data->info->num_view_modes = data->rx_msg[4] + 1; + } else if (msg_size > 3) { + data->info->num_view_modes = data->rx_msg[2] + 1; + } else { + data->info->num_view_modes = data->info->num_modes; + } + + debug_pr("num_modes: %d\n", data->info->num_modes); + debug_pr("num_view_modes: %d\n", data->info->num_view_modes); + + break; + case LUMP_CMD_SPEED: + if (test_and_set_bit(EV3_UART_INFO_BIT_CMD_SPEED, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate speed INFO"); + goto err; + } + speed = uint32_le(data->rx_msg + 1); + if (speed < EV3_UART_SPEED_MIN || speed > EV3_UART_SPEED_MAX) { + DBG_ERR(data->last_err = "Speed is out of range"); + goto err; + } + data->new_baud_rate = speed; + + debug_pr("speed: %" PRIu32 "\n", speed); + + break; + case LUMP_CMD_WRITE: + if (cmd2 & 0x20) { + data->write_cmd_size = cmd2 & 0x3; + if (PBIO_IODEV_IS_FEEDBACK_MOTOR(&data->iodev)) { + // TODO: msg[3] and msg[4] probably give us useful information + } else { + // TODO: handle other write commands + } + } + break; + case LUMP_CMD_EXT_MODE: + // Powered up devices can have modes > LUMP_MAX_MODE. This + // command precedes other commands to add the extra 8 to the mode + data->ext_mode = data->rx_msg[1]; + break; + case LUMP_CMD_VERSION: + if (test_and_set_bit(EV3_UART_INFO_BIT_CMD_VERSION, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate version INFO"); + goto err; + } + // TODO: this might be useful someday + debug_pr("fw version: %08" PRIx32 "\n", uint32_le(data->rx_msg + 1)); + debug_pr("hw version: %08" PRIx32 "\n", uint32_le(data->rx_msg + 5)); + break; + default: + DBG_ERR(data->last_err = "Unknown command"); + goto err; } - data->new_baud_rate = speed; - - debug_pr("speed: %" PRIu32 "\n", speed); - break; - case LUMP_CMD_WRITE: - if (cmd2 & 0x20) { - data->write_cmd_size = cmd2 & 0x3; - if (PBIO_IODEV_IS_FEEDBACK_MOTOR(&data->iodev)) { - // TODO: msg[3] and msg[4] probably give us useful information - } - else { - // TODO: handle other write commands + case LUMP_MSG_TYPE_INFO: + switch (cmd2) { + case LUMP_INFO_NAME: { + data->info_flags &= ~EV3_UART_INFO_FLAG_ALL_INFO; + if (data->rx_msg[2] < 'A' || data->rx_msg[2] > 'z') { + DBG_ERR(data->last_err = "Invalid name INFO"); + goto err; + } + /* + * Name may not have null terminator and we + * are done with the checksum at this point + * so we are writing 0 over the checksum to + * ensure a null terminator for the string + * functions. + */ + data->rx_msg[msg_size - 1] = 0; + size_t name_len = strlen((char *)(data->rx_msg + 2)); + if (name_len > LUMP_MAX_NAME_SIZE) { + DBG_ERR(data->last_err = "Name is too long"); + goto err; + } + snprintf(data->info->mode_info[mode].name, + PBIO_IODEV_MODE_NAME_SIZE + 1, "%s", data->rx_msg + 2); + data->new_mode = mode; + data->info_flags |= EV3_UART_INFO_FLAG_INFO_NAME; + + lump_mode_flags_t *flags = &data->info->mode_info[mode].flags; + if (name_len <= LUMP_MAX_SHORT_NAME_SIZE && msg_size > LUMP_MAX_NAME_SIZE) { + // newer LPF2 devices send additional mode flags along with the name + memcpy(flags, data->rx_msg + 8, 6); + } else { + // otherwise look up flags + pbio_uartdev_set_mode_flags(data->type_id, mode, flags); + } + + if (flags->flags0 & LUMP_MODE_FLAGS0_MOTOR_POWER) { + data->iodev.motor_flags |= PBIO_IODEV_MOTOR_FLAG_IS_MOTOR; + } + if (flags->flags0 & LUMP_MODE_FLAGS0_MOTOR_SPEED) { + data->iodev.motor_flags |= PBIO_IODEV_MOTOR_FLAG_HAS_SPEED; + } + if (flags->flags0 & LUMP_MODE_FLAGS0_MOTOR_REL_POS) { + data->iodev.motor_flags |= PBIO_IODEV_MOTOR_FLAG_HAS_REL_POS; + } + if (flags->flags0 & LUMP_MODE_FLAGS0_MOTOR_ABS_POS) { + data->iodev.motor_flags |= PBIO_IODEV_MOTOR_FLAG_HAS_ABS_POS; + } + + debug_pr("new_mode: %d\n", data->new_mode); + debug_pr("name: %s\n", data->info->mode_info[mode].name); + debug_pr("flags: %02X %02X %02X %02X %02X %02X\n", + flags->flags0, flags->flags1, flags->flags2, + flags->flags3, flags->flags4, flags->flags5); } + break; + case LUMP_INFO_RAW: + if (data->new_mode != mode) { + DBG_ERR(data->last_err = "Received INFO for incorrect mode"); + goto err; + } + if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_RAW, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate raw scaling INFO"); + goto err; + } + data->info->mode_info[mode].raw_min = float_le(data->rx_msg + 2); + data->info->mode_info[mode].raw_max = float_le(data->rx_msg + 6); + + debug_pr("raw: %f %f\n", (double)data->info->mode_info[mode].raw_min, + (double)data->info->mode_info[mode].raw_max); + + break; + case LUMP_INFO_PCT: + if (data->new_mode != mode) { + DBG_ERR(data->last_err = "Received INFO for incorrect mode"); + goto err; + } + if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_PCT, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate percent scaling INFO"); + goto err; + } + data->info->mode_info[mode].pct_min = float_le(data->rx_msg + 2); + data->info->mode_info[mode].pct_max = float_le(data->rx_msg + 6); + + debug_pr("pct: %f %f\n", (double)data->info->mode_info[mode].pct_min, + (double)data->info->mode_info[mode].pct_max); + + break; + case LUMP_INFO_SI: + if (data->new_mode != mode) { + DBG_ERR(data->last_err = "Received INFO for incorrect mode"); + goto err; + } + if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_SI, + &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate SI scaling INFO"); + goto err; + } + data->info->mode_info[mode].si_min = float_le(data->rx_msg + 2); + data->info->mode_info[mode].si_max = float_le(data->rx_msg + 6); + + debug_pr("si: %f %f\n", (double)data->info->mode_info[mode].si_min, + (double)data->info->mode_info[mode].si_max); + + break; + case LUMP_INFO_UNITS: + if (data->new_mode != mode) { + DBG_ERR(data->last_err = "Received INFO for incorrect mode"); + goto err; + } + if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_UNITS, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate SI units INFO"); + goto err; + } + // Units may not have null terminator and we are done with the + // checksum at this point so we are writing 0 over the checksum to + // ensure a null terminator for the string functions. + data->rx_msg[msg_size - 1] = 0; + snprintf(data->info->mode_info[mode].uom, PBIO_IODEV_UOM_SIZE + 1, + "%s", data->rx_msg + 2); + + debug_pr("uom: %s\n", data->info->mode_info[mode].uom); + + break; + case LUMP_INFO_MAPPING: + if (data->new_mode != mode) { + DBG_ERR(data->last_err = "Received INFO for incorrect mode"); + goto err; + } + if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_MAPPING, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate mapping INFO"); + goto err; + } + + data->info->mode_info[mode].input_flags = data->rx_msg[2]; + data->info->mode_info[mode].output_flags = data->rx_msg[3]; + + debug_pr("mapping: in %02x out %02x\n", data->rx_msg[2], data->rx_msg[3]); + + break; + case LUMP_INFO_MODE_COMBOS: + if (data->new_mode != mode) { + DBG_ERR(data->last_err = "Received INFO for incorrect mode"); + goto err; + } + if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_MODE_COMBOS, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate mode combos INFO"); + goto err; + } + + // REVISIT: this is potentially an array of combos + data->info->mode_combos = data->rx_msg[3] << 8 | data->rx_msg[2]; + + debug_pr("mode combos: %04x\n", data->info->mode_combos); + + break; + case LUMP_INFO_UNK9: + if (data->new_mode != mode) { + DBG_ERR(data->last_err = "Received INFO for incorrect mode"); + goto err; + } + if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_UNK9, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate UNK9 INFO"); + goto err; + } + + // first 3 parameters look like PID constants + data->max_tacho_rate = uint32_le(data->rx_msg + 14); + + debug_pr("motor parameters: %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 "\n", + uint32_le(data->rx_msg + 2), uint32_le(data->rx_msg + 6), + uint32_le(data->rx_msg + 10), data->max_tacho_rate); + + break; + case LUMP_INFO_FORMAT: + if (data->new_mode != mode) { + DBG_ERR(data->last_err = "Received INFO for incorrect mode"); + goto err; + } + if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_FORMAT, &data->info_flags)) { + DBG_ERR(data->last_err = "Received duplicate format INFO"); + goto err; + } + data->info->mode_info[mode].num_values = data->rx_msg[2]; + if (!data->info->mode_info[mode].num_values) { + DBG_ERR(data->last_err = "Invalid number of data sets"); + goto err; + } + if (msg_size < 7) { + DBG_ERR(data->last_err = "Invalid format data->msg size"); + goto err; + } + if ((data->info_flags & EV3_UART_INFO_FLAG_REQUIRED) != EV3_UART_INFO_FLAG_REQUIRED) { + DBG_ERR(data->last_err = "Did not receive all required INFO"); + goto err; + } + data->info->mode_info[mode].data_type = data->rx_msg[3]; + data->info->mode_info[mode].digits = data->rx_msg[4]; + data->info->mode_info[mode].decimals = data->rx_msg[5]; + if (data->new_mode) { + data->new_mode--; + } + + debug_pr("num_values: %d\n", data->info->mode_info[mode].num_values); + debug_pr("data_type: %d\n", data->info->mode_info[mode].data_type); + debug_pr("digits: %d\n", data->info->mode_info[mode].digits); + debug_pr("decimals: %d\n", data->info->mode_info[mode].decimals); + + break; } break; - case LUMP_CMD_EXT_MODE: - // Powered up devices can have modes > LUMP_MAX_MODE. This - // command precedes other commands to add the extra 8 to the mode - data->ext_mode = data->rx_msg[1]; - break; - case LUMP_CMD_VERSION: - if (test_and_set_bit(EV3_UART_INFO_BIT_CMD_VERSION, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate version INFO"); + case LUMP_MSG_TYPE_DATA: + if (data->status != PBIO_UARTDEV_STATUS_DATA) { + DBG_ERR(data->last_err = "Received DATA before INFO was complete"); goto err; } - // TODO: this might be useful someday - debug_pr("fw version: %08" PRIx32 "\n", uint32_le(data->rx_msg + 1)); - debug_pr("hw version: %08" PRIx32 "\n", uint32_le(data->rx_msg + 5)); - break; - default: - DBG_ERR(data->last_err = "Unknown command"); - goto err; - } - break; - case LUMP_MSG_TYPE_INFO: - switch (cmd2) { - case LUMP_INFO_NAME: - { - data->info_flags &= ~EV3_UART_INFO_FLAG_ALL_INFO; - if (data->rx_msg[2] < 'A' || data->rx_msg[2] > 'z') { - DBG_ERR(data->last_err = "Invalid name INFO"); - goto err; - } - /* - * Name may not have null terminator and we - * are done with the checksum at this point - * so we are writing 0 over the checksum to - * ensure a null terminator for the string - * functions. - */ - data->rx_msg[msg_size - 1] = 0; - size_t name_len = strlen((char *)(data->rx_msg + 2)); - if (name_len > LUMP_MAX_NAME_SIZE) { - DBG_ERR(data->last_err = "Name is too long"); - goto err; - } - snprintf(data->info->mode_info[mode].name, - PBIO_IODEV_MODE_NAME_SIZE + 1, "%s", data->rx_msg + 2); - data->new_mode = mode; - data->info_flags |= EV3_UART_INFO_FLAG_INFO_NAME; - - lump_mode_flags_t *flags = &data->info->mode_info[mode].flags; - if (name_len <= LUMP_MAX_SHORT_NAME_SIZE && msg_size > LUMP_MAX_NAME_SIZE) { - // newer LPF2 devices send additional mode flags along with the name - memcpy(flags, data->rx_msg + 8, 6); - } - else { - // otherwise look up flags - pbio_uartdev_set_mode_flags(data->type_id, mode, flags); - } - if (flags->flags0 & LUMP_MODE_FLAGS0_MOTOR_POWER) { - data->iodev.motor_flags |= PBIO_IODEV_MOTOR_FLAG_IS_MOTOR; - } - if (flags->flags0 & LUMP_MODE_FLAGS0_MOTOR_SPEED) { - data->iodev.motor_flags |= PBIO_IODEV_MOTOR_FLAG_HAS_SPEED; + if (PBIO_IODEV_IS_FEEDBACK_MOTOR(&data->iodev) && data->write_cmd_size > 0) { + data->tacho_rate = data->rx_msg[1]; + data->tacho_count = uint32_le(data->rx_msg + 2); + if (data->iodev.motor_flags & PBIO_IODEV_MOTOR_FLAG_HAS_ABS_POS) { + data->abs_pos = data->rx_msg[7] << 8 | data->rx_msg[6]; } - if (flags->flags0 & LUMP_MODE_FLAGS0_MOTOR_REL_POS) { - data->iodev.motor_flags |= PBIO_IODEV_MOTOR_FLAG_HAS_REL_POS; + } else { + if (mode >= data->info->num_modes) { + DBG_ERR(data->last_err = "Invalid mode received"); + goto err; } - if (flags->flags0 & LUMP_MODE_FLAGS0_MOTOR_ABS_POS) { - data->iodev.motor_flags |= PBIO_IODEV_MOTOR_FLAG_HAS_ABS_POS; + data->iodev.mode = mode; + if (mode == data->new_mode) { + memcpy(data->iodev.bin_data, data->rx_msg + 1, msg_size - 2); } - - debug_pr("new_mode: %d\n", data->new_mode); - debug_pr("name: %s\n", data->info->mode_info[mode].name); - debug_pr("flags: %02X %02X %02X %02X %02X %02X\n", - flags->flags0, flags->flags1, flags->flags2, - flags->flags3, flags->flags4, flags->flags5); - } - break; - case LUMP_INFO_RAW: - if (data->new_mode != mode) { - DBG_ERR(data->last_err = "Received INFO for incorrect mode"); - goto err; - } - if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_RAW, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate raw scaling INFO"); - goto err; - } - data->info->mode_info[mode].raw_min = float_le(data->rx_msg + 2); - data->info->mode_info[mode].raw_max = float_le(data->rx_msg + 6); - - debug_pr("raw: %f %f\n", (double)data->info->mode_info[mode].raw_min, - (double)data->info->mode_info[mode].raw_max); - - break; - case LUMP_INFO_PCT: - if (data->new_mode != mode) { - DBG_ERR(data->last_err = "Received INFO for incorrect mode"); - goto err; - } - if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_PCT, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate percent scaling INFO"); - goto err; - } - data->info->mode_info[mode].pct_min = float_le(data->rx_msg + 2); - data->info->mode_info[mode].pct_max = float_le(data->rx_msg + 6); - - debug_pr("pct: %f %f\n", (double)data->info->mode_info[mode].pct_min, - (double)data->info->mode_info[mode].pct_max); - - break; - case LUMP_INFO_SI: - if (data->new_mode != mode) { - DBG_ERR(data->last_err = "Received INFO for incorrect mode"); - goto err; - } - if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_SI, - &data->info_flags)) - { - DBG_ERR(data->last_err = "Received duplicate SI scaling INFO"); - goto err; } - data->info->mode_info[mode].si_min = float_le(data->rx_msg + 2); - data->info->mode_info[mode].si_max = float_le(data->rx_msg + 6); - debug_pr("si: %f %f\n", (double)data->info->mode_info[mode].si_min, - (double)data->info->mode_info[mode].si_max); - - break; - case LUMP_INFO_UNITS: - if (data->new_mode != mode) { - DBG_ERR(data->last_err = "Received INFO for incorrect mode"); - goto err; - } - if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_UNITS, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate SI units INFO"); - goto err; - } - // Units may not have null terminator and we are done with the - // checksum at this point so we are writing 0 over the checksum to - // ensure a null terminator for the string functions. - data->rx_msg[msg_size - 1] = 0; - snprintf(data->info->mode_info[mode].uom, PBIO_IODEV_UOM_SIZE + 1, - "%s", data->rx_msg + 2); - - debug_pr("uom: %s\n", data->info->mode_info[mode].uom); - - break; - case LUMP_INFO_MAPPING: - if (data->new_mode != mode) { - DBG_ERR(data->last_err = "Received INFO for incorrect mode"); - goto err; - } - if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_MAPPING, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate mapping INFO"); - goto err; - } - - data->info->mode_info[mode].input_flags = data->rx_msg[2]; - data->info->mode_info[mode].output_flags = data->rx_msg[3]; - - debug_pr("mapping: in %02x out %02x\n", data->rx_msg[2], data->rx_msg[3]); - - break; - case LUMP_INFO_MODE_COMBOS: - if (data->new_mode != mode) { - DBG_ERR(data->last_err = "Received INFO for incorrect mode"); - goto err; - } - if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_MODE_COMBOS, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate mode combos INFO"); - goto err; - } - - // REVISIT: this is potentially an array of combos - data->info->mode_combos = data->rx_msg[3] << 8 | data->rx_msg[2]; - - debug_pr("mode combos: %04x\n", data->info->mode_combos); - - break; - case LUMP_INFO_UNK9: - if (data->new_mode != mode) { - DBG_ERR(data->last_err = "Received INFO for incorrect mode"); - goto err; - } - if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_UNK9, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate UNK9 INFO"); - goto err; - } - - // first 3 parameters look like PID constants - data->max_tacho_rate = uint32_le(data->rx_msg + 14); - - debug_pr("motor parameters: %" PRIu32 " %" PRIu32 " %" PRIu32 " %" PRIu32 "\n", - uint32_le(data->rx_msg + 2), uint32_le(data->rx_msg + 6), - uint32_le(data->rx_msg + 10), data->max_tacho_rate); - - break; - case LUMP_INFO_FORMAT: - if (data->new_mode != mode) { - DBG_ERR(data->last_err = "Received INFO for incorrect mode"); - goto err; - } - if (test_and_set_bit(EV3_UART_INFO_BIT_INFO_FORMAT, &data->info_flags)) { - DBG_ERR(data->last_err = "Received duplicate format INFO"); - goto err; - } - data->info->mode_info[mode].num_values = data->rx_msg[2]; - if (!data->info->mode_info[mode].num_values) { - DBG_ERR(data->last_err = "Invalid number of data sets"); - goto err; - } - if (msg_size < 7) { - DBG_ERR(data->last_err = "Invalid format data->msg size"); - goto err; + data->data_rec = true; + if (data->num_data_err) { + data->num_data_err--; } - if ((data->info_flags & EV3_UART_INFO_FLAG_REQUIRED) != EV3_UART_INFO_FLAG_REQUIRED) { - DBG_ERR(data->last_err = "Did not receive all required INFO"); - goto err; - } - data->info->mode_info[mode].data_type = data->rx_msg[3]; - data->info->mode_info[mode].digits = data->rx_msg[4]; - data->info->mode_info[mode].decimals = data->rx_msg[5]; - if (data->new_mode) { - data->new_mode--; - } - - debug_pr("num_values: %d\n", data->info->mode_info[mode].num_values); - debug_pr("data_type: %d\n", data->info->mode_info[mode].data_type); - debug_pr("digits: %d\n", data->info->mode_info[mode].digits); - debug_pr("decimals: %d\n", data->info->mode_info[mode].decimals); - break; - } - break; - case LUMP_MSG_TYPE_DATA: - if (data->status != PBIO_UARTDEV_STATUS_DATA) { - DBG_ERR(data->last_err = "Received DATA before INFO was complete"); - goto err; - } - - if (PBIO_IODEV_IS_FEEDBACK_MOTOR(&data->iodev) && data->write_cmd_size > 0) { - data->tacho_rate = data->rx_msg[1]; - data->tacho_count = uint32_le(data->rx_msg + 2); - if (data->iodev.motor_flags & PBIO_IODEV_MOTOR_FLAG_HAS_ABS_POS) { - data->abs_pos = data->rx_msg[7] << 8 | data->rx_msg[6]; - } - } - else { - if (mode >= data->info->num_modes) { - DBG_ERR(data->last_err = "Invalid mode received"); - goto err; - } - data->iodev.mode = mode; - if (mode == data->new_mode) { - memcpy(data->iodev.bin_data, data->rx_msg + 1, msg_size - 2); - } - } - - data->data_rec = true; - if (data->num_data_err) { - data->num_data_err--; - } - break; } return; @@ -700,13 +693,12 @@ static void pbio_uartdev_parse_msg(uartdev_port_data_t *data) { data->status = PBIO_UARTDEV_STATUS_ERR; } -static uint8_t ev3_uart_set_msg_hdr(lump_msg_type_t type, lump_msg_size_t size, lump_cmd_t cmd) -{ +static uint8_t ev3_uart_set_msg_hdr(lump_msg_type_t type, lump_msg_size_t size, lump_cmd_t cmd) { return (type & LUMP_MSG_TYPE_MASK) | (size & LUMP_MSG_SIZE_MASK) | (cmd & LUMP_MSG_CMD_MASK); } static pbio_error_t ev3_uart_begin_tx_msg(uartdev_port_data_t *port_data, lump_msg_type_t msg_type, - lump_cmd_t cmd, const uint8_t *data, uint8_t len) { + lump_cmd_t cmd, const uint8_t *data, uint8_t len) { uint8_t header, checksum, i; uint8_t offset = 0; lump_msg_size_t size; @@ -740,23 +732,18 @@ static pbio_error_t ev3_uart_begin_tx_msg(uartdev_port_data_t *port_data, lump_m // can't send arbitrary number of bytes, so find nearest match if (i == 1) { size = LUMP_MSG_SIZE_1; - } - else if (i == 2) { + } else if (i == 2) { size = LUMP_MSG_SIZE_2; - } - else if (i <= 4) { + } else if (i <= 4) { size = LUMP_MSG_SIZE_4; len = 4; - } - else if (i <= 8) { + } else if (i <= 8) { size = LUMP_MSG_SIZE_8; len = 8; - } - else if (i <= 16) { + } else if (i <= 16) { size = LUMP_MSG_SIZE_16; len = 16; - } - else if (i <= 32) { + } else if (i <= 32) { size = LUMP_MSG_SIZE_32; len = 32; } @@ -780,7 +767,7 @@ static pbio_error_t ev3_uart_begin_tx_msg(uartdev_port_data_t *port_data, lump_m return err; } -static PT_THREAD(pbio_uartdev_send_speed_msg(uartdev_port_data_t *data, uint32_t speed)) { +static PT_THREAD(pbio_uartdev_send_speed_msg(uartdev_port_data_t * data, uint32_t speed)) { pbio_error_t err; PT_BEGIN(&data->speed_pt); @@ -806,7 +793,7 @@ static PT_THREAD(pbio_uartdev_send_speed_msg(uartdev_port_data_t *data, uint32_t goto err; } - data->tx_busy =false; + data->tx_busy = false; PT_END(&data->speed_pt); @@ -814,7 +801,7 @@ static PT_THREAD(pbio_uartdev_send_speed_msg(uartdev_port_data_t *data, uint32_t PT_EXIT(&data->speed_pt); } -static PT_THREAD(pbio_uartdev_update(uartdev_port_data_t *data)) { +static PT_THREAD(pbio_uartdev_update(uartdev_port_data_t * data)) { pbio_error_t err; uint8_t checksum; @@ -843,11 +830,10 @@ static PT_THREAD(pbio_uartdev_update(uartdev_port_data_t *data)) { } PBIO_PT_WAIT_READY(&data->pt, err = pbdrv_uart_read_end(data->uart)); - if ((err == PBIO_SUCCESS && data->rx_msg[0] != LUMP_SYS_ACK) || err == PBIO_ERROR_TIMEDOUT) { + if ((err == PBIO_SUCCESS && data->rx_msg[0] != LUMP_SYS_ACK) || err == PBIO_ERROR_TIMEDOUT) { // if we did not get ACK within 100ms, then switch to slow baud rate for sync PBIO_PT_WAIT_READY(&data->pt, pbdrv_uart_set_baud_rate(data->uart, EV3_UART_SPEED_MIN)); - } - else if (err != PBIO_SUCCESS) { + } else if (err != PBIO_SUCCESS) { DBG_ERR(data->last_err = "UART Rx error during baud"); goto err; } @@ -1065,7 +1051,7 @@ static PT_THREAD(pbio_uartdev_update(uartdev_port_data_t *data)) { // REVISIT: This is not the greatest. We can easily get a buffer overrun and // loose data. For now, the retry after bad message size helps get back into // sync with the data stream. -static PT_THREAD(pbio_uartdev_receive_data(uartdev_port_data_t *data)) { +static PT_THREAD(pbio_uartdev_receive_data(uartdev_port_data_t * data)) { pbio_error_t err; PT_BEGIN(&data->data_pt); @@ -1090,9 +1076,9 @@ static PT_THREAD(pbio_uartdev_receive_data(uartdev_port_data_t *data)) { } uint8_t msg_type = data->rx_msg[0] & LUMP_MSG_TYPE_MASK; - uint8_t cmd = data->rx_msg[0] & LUMP_MSG_CMD_MASK; + uint8_t cmd = data->rx_msg[0] & LUMP_MSG_CMD_MASK; if (msg_type != LUMP_MSG_TYPE_DATA && (msg_type != LUMP_MSG_TYPE_CMD || - (cmd != LUMP_CMD_WRITE && cmd != LUMP_CMD_EXT_MODE))) { + (cmd != LUMP_CMD_WRITE && cmd != LUMP_CMD_EXT_MODE))) { DBG_ERR(data->last_err = "Bad msg type"); continue; } @@ -1264,7 +1250,7 @@ static PT_THREAD(pbio_uartdev_init(struct pt *pt, uint8_t id)) { port_data->counter_dev.get_abs_count = pbio_uartdev_get_abs_count; port_data->counter_dev.get_rate = pbio_uartdev_get_rate; port_data->counter_dev.initalized = true; - port_data->info = &infos[id].info; + port_data->info = &infos[id].info; port_data->tx_msg = &bufs[id][BUF_TX_MSG][0]; port_data->rx_msg = &bufs[id][BUF_RX_MSG][0]; diff --git a/lib/pbio/test/test-pbio.c b/lib/pbio/test/test-pbio.c index 11eea3e35..2fc9f0a64 100644 --- a/lib/pbio/test/test-pbio.c +++ b/lib/pbio/test/test-pbio.c @@ -70,7 +70,7 @@ static struct testcase_setup_t pbio_test_setup = { .cleanup_fn = cleanup, }; -static struct testcase_t example_tests[] = { +static struct testcase_t example_tests[] = { PBIO_PT_THREAD_TEST(example_test), END_OF_TESTCASES }; diff --git a/lib/pbio/test/uartdev.c b/lib/pbio/test/uartdev.c index 96fc6b9d8..2f3c1edd8 100644 --- a/lib/pbio/test/uartdev.c +++ b/lib/pbio/test/uartdev.c @@ -21,7 +21,7 @@ // TODO: submit this upstream #ifndef tt_want_float_op #define tt_want_float_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,float,(val1_ op val2_),"%f",(void)0) + tt_assert_test_type(a,b,#a " "#op " "#b,float,(val1_ op val2_),"%f",(void)0) #endif static struct { @@ -88,14 +88,14 @@ PT_THREAD(simulate_tx_msg(struct pt *pt, const uint8_t *msg, uint8_t length, boo PT_EXIT(pt); } -#define SIMULATE_RX_MSG(msg) do {\ - PT_SPAWN(pt, &child, simulate_rx_msg(&child, (msg), PBIO_ARRAY_SIZE(msg), &ok)); \ - tt_assert_msg(ok, #msg); \ +#define SIMULATE_RX_MSG(msg) do { \ + PT_SPAWN(pt, &child, simulate_rx_msg(&child, (msg), PBIO_ARRAY_SIZE(msg), &ok)); \ + tt_assert_msg(ok, #msg); \ } while (0) -#define SIMULATE_TX_MSG(msg) do {\ - PT_SPAWN(pt, &child, simulate_tx_msg(&child, (msg), PBIO_ARRAY_SIZE(msg), &ok)); \ - tt_assert_msg(ok, #msg); \ +#define SIMULATE_TX_MSG(msg) do { \ + PT_SPAWN(pt, &child, simulate_tx_msg(&child, (msg), PBIO_ARRAY_SIZE(msg), &ok)); \ + tt_assert_msg(ok, #msg); \ } while (0) static const uint8_t msg_speed_115200[] = { 0x52, 0x00, 0xC2, 0x01, 0x00, 0x6E }; // SPEED 115200 @@ -1007,7 +1007,7 @@ PT_THREAD(test_technic_large_motor(struct pt *pt)) { // TODO: verify fw/hw versions tt_want_uint_op(iodev->info->mode_combos, ==, 1 << 3 | 1 << 2 | 1 << 1); tt_want_uint_op(iodev->motor_flags, ==, PBIO_IODEV_MOTOR_FLAG_IS_MOTOR | PBIO_IODEV_MOTOR_FLAG_HAS_SPEED - | PBIO_IODEV_MOTOR_FLAG_HAS_REL_POS | PBIO_IODEV_MOTOR_FLAG_HAS_ABS_POS); + | PBIO_IODEV_MOTOR_FLAG_HAS_REL_POS | PBIO_IODEV_MOTOR_FLAG_HAS_ABS_POS); tt_want_uint_op(iodev->mode, ==, 0); tt_want_str_op(iodev->info->mode_info[0].name, ==, "POWER"); @@ -1327,7 +1327,7 @@ PT_THREAD(test_technic_xl_motor(struct pt *pt)) { // TODO: verify fw/hw versions tt_want_uint_op(iodev->info->mode_combos, ==, 1 << 3 | 1 << 2 | 1 << 1); tt_want_uint_op(iodev->motor_flags, ==, PBIO_IODEV_MOTOR_FLAG_IS_MOTOR | PBIO_IODEV_MOTOR_FLAG_HAS_SPEED - | PBIO_IODEV_MOTOR_FLAG_HAS_REL_POS | PBIO_IODEV_MOTOR_FLAG_HAS_ABS_POS); + | PBIO_IODEV_MOTOR_FLAG_HAS_REL_POS | PBIO_IODEV_MOTOR_FLAG_HAS_ABS_POS); tt_want_uint_op(iodev->mode, ==, 0); tt_want_str_op(iodev->info->mode_info[0].name, ==, "POWER"); @@ -1519,7 +1519,7 @@ void pbdrv_uart_read_cancel(pbdrv_uart_dev_t *uart) { } pbio_error_t pbdrv_uart_write_begin(pbdrv_uart_dev_t *uart, uint8_t *msg, uint8_t length, uint32_t timeout) { - if (test_uart_dev.tx_msg) { + if (test_uart_dev.tx_msg) { return PBIO_ERROR_AGAIN; } diff --git a/py/pb_type_enum.h b/py/pb_type_enum.h index b78ca8db5..754fea4a1 100644 --- a/py/pb_type_enum.h +++ b/py/pb_type_enum.h @@ -23,23 +23,23 @@ typedef struct _pb_obj_enum_member_t { { \ MP_ROM_QSTR(member_name), \ MP_ROM_PTR(( \ - &(pb_obj_enum_member_t) { \ - {&enum_type}, \ - .name = member_name, \ - .value = member_value \ - }\ - )) \ + &(pb_obj_enum_member_t) { \ + {&enum_type}, \ + .name = member_name, \ + .value = member_value \ + } \ + )) \ } // Shortcut for converting table to Enum-like class object #define PB_DEFINE_ENUM(enum_type, enum_name, table_name) \ -STATIC MP_DEFINE_CONST_DICT(enum_type ## _locals_dict, table_name); \ -const mp_obj_type_t enum_type = { \ - { &mp_type_type }, \ - .name = enum_name, \ - .print = pb_type_enum_print, \ - .unary_op = mp_generic_unary_op, \ - .locals_dict = (mp_obj_dict_t*)&(enum_type ## _locals_dict),\ -} + STATIC MP_DEFINE_CONST_DICT(enum_type##_locals_dict, table_name); \ + const mp_obj_type_t enum_type = { \ + { &mp_type_type }, \ + .name = enum_name, \ + .print = pb_type_enum_print, \ + .unary_op = mp_generic_unary_op, \ + .locals_dict = (mp_obj_dict_t *)&(enum_type##_locals_dict), \ + } #endif // PYBRICKS_INCLUDED_PY_PB_TYPE_ENUM_H diff --git a/py/pberror.c b/py/pberror.c index b7f34ce5f..dd0ed9b6b 100644 --- a/py/pberror.c +++ b/py/pberror.c @@ -16,50 +16,50 @@ * cases that use another built-in python exception when it is more appropriate. */ void pb_assert(pbio_error_t error) { -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE // using EINVAL to mean that the argument to this function was invalid. // since we raise ValueError for PBIO_ERROR_INVALID_ARG, there isn't a // possible conflict int os_err = MP_EINVAL; switch (error) { - case PBIO_SUCCESS: - return; - case PBIO_ERROR_FAILED: - mp_raise_msg(&mp_type_RuntimeError, NULL); - return; - case PBIO_ERROR_INVALID_ARG: - case PBIO_ERROR_INVALID_PORT: - mp_raise_ValueError(NULL); - return; - case PBIO_ERROR_NOT_IMPLEMENTED: - mp_raise_NotImplementedError(NULL); - return; - case PBIO_ERROR_IO: - os_err = MP_EIO; - break; - case PBIO_ERROR_NO_DEV: - os_err = MP_ENODEV; - return; - case PBIO_ERROR_NOT_SUPPORTED: - os_err = MP_EOPNOTSUPP; - break; - case PBIO_ERROR_AGAIN: - os_err = MP_EAGAIN; - break; - case PBIO_ERROR_INVALID_OP: - os_err = MP_EPERM; - break; - case PBIO_ERROR_TIMEDOUT: - os_err = MP_ETIMEDOUT; - break; - case PBIO_ERROR_CANCELED: - os_err = MP_ECANCELED; - break; + case PBIO_SUCCESS: + return; + case PBIO_ERROR_FAILED: + mp_raise_msg(&mp_type_RuntimeError, NULL); + return; + case PBIO_ERROR_INVALID_ARG: + case PBIO_ERROR_INVALID_PORT: + mp_raise_ValueError(NULL); + return; + case PBIO_ERROR_NOT_IMPLEMENTED: + mp_raise_NotImplementedError(NULL); + return; + case PBIO_ERROR_IO: + os_err = MP_EIO; + break; + case PBIO_ERROR_NO_DEV: + os_err = MP_ENODEV; + return; + case PBIO_ERROR_NOT_SUPPORTED: + os_err = MP_EOPNOTSUPP; + break; + case PBIO_ERROR_AGAIN: + os_err = MP_EAGAIN; + break; + case PBIO_ERROR_INVALID_OP: + os_err = MP_EPERM; + break; + case PBIO_ERROR_TIMEDOUT: + os_err = MP_ETIMEDOUT; + break; + case PBIO_ERROR_CANCELED: + os_err = MP_ECANCELED; + break; } mp_raise_OSError(os_err); -#else // MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE + #else // MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE static const MP_DEFINE_STR_OBJ(msg_io_obj, "\n\n" "Unexpected hardware input/output error with a motor or sensor:\n" "--> Try unplugging the sensor or motor and plug it back in again.\n" @@ -91,50 +91,50 @@ void pb_assert(pbio_error_t error) { mp_obj_t args[2]; switch (error) { - case PBIO_SUCCESS: - return; - case PBIO_ERROR_FAILED: - mp_raise_msg(&mp_type_RuntimeError, pbio_error_str(error)); - return; - case PBIO_ERROR_INVALID_ARG: - case PBIO_ERROR_INVALID_PORT: - mp_raise_ValueError(pbio_error_str(error)); - return; - case PBIO_ERROR_NOT_IMPLEMENTED: - mp_raise_NotImplementedError(pbio_error_str(error)); - return; - case PBIO_ERROR_IO: - args[0] = MP_OBJ_NEW_SMALL_INT(MP_EIO); - args[1] = MP_OBJ_FROM_PTR(&msg_io_obj); - break; - case PBIO_ERROR_NO_DEV: - args[0] = MP_OBJ_NEW_SMALL_INT(MP_ENODEV); - args[1] = MP_OBJ_FROM_PTR(&msg_no_dev_obj); - break; - case PBIO_ERROR_NOT_SUPPORTED: - args[0] = MP_OBJ_NEW_SMALL_INT(MP_EOPNOTSUPP); - args[1] = MP_OBJ_FROM_PTR(&msg_not_supported_obj); - break; - case PBIO_ERROR_AGAIN: - args[0] = MP_OBJ_NEW_SMALL_INT(MP_EAGAIN); - args[1] = MP_OBJ_NEW_QSTR(qstr_from_str(pbio_error_str(error))); - break; - case PBIO_ERROR_INVALID_OP: - args[0] = MP_OBJ_NEW_SMALL_INT(MP_EPERM); - args[1] = MP_OBJ_FROM_PTR(&msg_invalid_op_obj); - break; - case PBIO_ERROR_TIMEDOUT: - args[0] = MP_OBJ_NEW_SMALL_INT(MP_ETIMEDOUT); - args[1] = MP_OBJ_NEW_QSTR(qstr_from_str(pbio_error_str(error))); - break; - case PBIO_ERROR_CANCELED: - args[0] = MP_OBJ_NEW_SMALL_INT(MP_ECANCELED); - args[1] = MP_OBJ_NEW_QSTR(qstr_from_str(pbio_error_str(error))); - break; + case PBIO_SUCCESS: + return; + case PBIO_ERROR_FAILED: + mp_raise_msg(&mp_type_RuntimeError, pbio_error_str(error)); + return; + case PBIO_ERROR_INVALID_ARG: + case PBIO_ERROR_INVALID_PORT: + mp_raise_ValueError(pbio_error_str(error)); + return; + case PBIO_ERROR_NOT_IMPLEMENTED: + mp_raise_NotImplementedError(pbio_error_str(error)); + return; + case PBIO_ERROR_IO: + args[0] = MP_OBJ_NEW_SMALL_INT(MP_EIO); + args[1] = MP_OBJ_FROM_PTR(&msg_io_obj); + break; + case PBIO_ERROR_NO_DEV: + args[0] = MP_OBJ_NEW_SMALL_INT(MP_ENODEV); + args[1] = MP_OBJ_FROM_PTR(&msg_no_dev_obj); + break; + case PBIO_ERROR_NOT_SUPPORTED: + args[0] = MP_OBJ_NEW_SMALL_INT(MP_EOPNOTSUPP); + args[1] = MP_OBJ_FROM_PTR(&msg_not_supported_obj); + break; + case PBIO_ERROR_AGAIN: + args[0] = MP_OBJ_NEW_SMALL_INT(MP_EAGAIN); + args[1] = MP_OBJ_NEW_QSTR(qstr_from_str(pbio_error_str(error))); + break; + case PBIO_ERROR_INVALID_OP: + args[0] = MP_OBJ_NEW_SMALL_INT(MP_EPERM); + args[1] = MP_OBJ_FROM_PTR(&msg_invalid_op_obj); + break; + case PBIO_ERROR_TIMEDOUT: + args[0] = MP_OBJ_NEW_SMALL_INT(MP_ETIMEDOUT); + args[1] = MP_OBJ_NEW_QSTR(qstr_from_str(pbio_error_str(error))); + break; + case PBIO_ERROR_CANCELED: + args[0] = MP_OBJ_NEW_SMALL_INT(MP_ECANCELED); + args[1] = MP_OBJ_NEW_QSTR(qstr_from_str(pbio_error_str(error))); + break; } nlr_raise(mp_obj_new_exception_args(&mp_type_OSError, 2, args)); -#endif // MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE + #endif // MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE } void pb_assert_type(mp_obj_t obj, const mp_obj_type_t *type) { diff --git a/py/pbkwarg.h b/py/pbkwarg.h index 1ea811bcc..f00ee6270 100644 --- a/py/pbkwarg.h +++ b/py/pbkwarg.h @@ -12,18 +12,18 @@ #define NUM_ARGS(...) EXPAND(_GET_NTH_ARG(__VA_ARGS__,9,8,7,6,5,4,3,2,1,0)) // Perform an action on a variable number of arguments. Extended from https://stackoverflow.com/a/11994395/11744630 -#define FI_1(WHAT, N, X) WHAT(N-1, X) -#define FI_2(WHAT, N, X, ...) WHAT(N-2, X)FI_1(WHAT, N, __VA_ARGS__) -#define FI_3(WHAT, N, X, ...) WHAT(N-3, X)FI_2(WHAT, N, __VA_ARGS__) -#define FI_4(WHAT, N, X, ...) WHAT(N-4, X)FI_3(WHAT, N, __VA_ARGS__) -#define FI_5(WHAT, N, X, ...) WHAT(N-5, X)FI_4(WHAT, N, __VA_ARGS__) -#define FI_6(WHAT, N, X, ...) WHAT(N-6, X)FI_5(WHAT, N, __VA_ARGS__) -#define FI_7(WHAT, N, X, ...) WHAT(N-7, X)FI_6(WHAT, N, __VA_ARGS__) -#define FI_8(WHAT, N, X, ...) WHAT(N-8, X)FI_7(WHAT, N, __VA_ARGS__) -#define FI_9(WHAT, N, X, ...) WHAT(N-9, X)FI_8(WHAT, N, __VA_ARGS__) +#define FI_1(WHAT, N, X) WHAT(N - 1, X) +#define FI_2(WHAT, N, X, ...) WHAT(N - 2, X) FI_1(WHAT, N, __VA_ARGS__) +#define FI_3(WHAT, N, X, ...) WHAT(N - 3, X) FI_2(WHAT, N, __VA_ARGS__) +#define FI_4(WHAT, N, X, ...) WHAT(N - 4, X) FI_3(WHAT, N, __VA_ARGS__) +#define FI_5(WHAT, N, X, ...) WHAT(N - 5, X) FI_4(WHAT, N, __VA_ARGS__) +#define FI_6(WHAT, N, X, ...) WHAT(N - 6, X) FI_5(WHAT, N, __VA_ARGS__) +#define FI_7(WHAT, N, X, ...) WHAT(N - 7, X) FI_6(WHAT, N, __VA_ARGS__) +#define FI_8(WHAT, N, X, ...) WHAT(N - 8, X) FI_7(WHAT, N, __VA_ARGS__) +#define FI_9(WHAT, N, X, ...) WHAT(N - 9, X) FI_8(WHAT, N, __VA_ARGS__) #define GET_MACRO(_1,_2,_3,_4,_5,_6,_7,_8,_9,NAME,...) NAME #define FOR_EACH_IDX(action,...) \ - GET_MACRO(__VA_ARGS__,FI_9,FI_8,FI_7,FI_6,FI_5,FI_4,FI_3,FI_2,FI_1,)(action, NUM_ARGS(__VA_ARGS__), __VA_ARGS__) + GET_MACRO(__VA_ARGS__,FI_9,FI_8,FI_7,FI_6,FI_5,FI_4,FI_3,FI_2,FI_1,)(action, NUM_ARGS(__VA_ARGS__), __VA_ARGS__) // Make a QSTR, even if the name is generated from a macro #define MAKE_QSTR_(name) MP_QSTR_##name @@ -51,7 +51,7 @@ // Create the arguments table, parse it, and declare mp_obj_t's for each one #define PB_PARSE_GENERIC(n_args, pos_args, kw_args, n_ignore, ...) STATIC const mp_arg_t allowed_args[] = { \ FOR_EACH_IDX(PB_ARG_DO, __VA_ARGS__) \ - }; \ +}; \ PB_PARSE_ARGS(parsed_args, n_args, pos_args, kw_args, allowed_args, n_ignore); \ FOR_EACH_IDX(GEN_ARG_OBJ, __VA_ARGS__) @@ -78,13 +78,13 @@ #define PB_ARG_REQUIRED(name) (name, MP_ARG_OBJ | MP_ARG_REQUIRED, ) // Optional keyword argument with default integer value -#define PB_ARG_DEFAULT_INT(name, value) (name, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_INT(value)} ) +#define PB_ARG_DEFAULT_INT(name, value) (name, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_INT(value)}) // Optional keyword argument with default enum value -#define PB_ARG_DEFAULT_OBJ(name, value) (name, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&value)} ) +#define PB_ARG_DEFAULT_OBJ(name, value) (name, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&value)}) // Optional keyword argument with default qstr value -#define PB_ARG_DEFAULT_QSTR(name, value) (name, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_QSTR(MP_QSTR_##value)} ) +#define PB_ARG_DEFAULT_QSTR(name, value) (name, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_QSTR(MP_QSTR_##value)}) // Optional keyword argument with default false value #define PB_ARG_DEFAULT_FALSE(name)(name, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&mp_const_false_obj)}) diff --git a/py/pbobj.c b/py/pbobj.c index 7fb06f200..371feccb4 100644 --- a/py/pbobj.c +++ b/py/pbobj.c @@ -32,11 +32,11 @@ mp_int_t pb_obj_get_int(mp_obj_t arg) { #endif fix16_t pb_obj_get_fix16(mp_obj_t arg) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT if (mp_obj_is_float(arg)) { - return fix16_from_float((float) mp_obj_get_float(arg)); + return fix16_from_float((float)mp_obj_get_float(arg)); } -#endif + #endif return fix16_from_int(mp_obj_get_int(arg)); } @@ -51,8 +51,8 @@ mp_obj_t pb_obj_get_base_class_obj(mp_obj_t obj, const mp_obj_type_t *type) { return obj; } // If it is an instance of a derived class, get base instance - if (mp_obj_is_obj(obj) && mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)MP_OBJ_TO_PTR(obj))->type), type)) { - return ((mp_obj_instance_t*)MP_OBJ_TO_PTR(obj))->subobj[0]; + if (mp_obj_is_obj(obj) && mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)MP_OBJ_TO_PTR(obj))->type), type)) { + return ((mp_obj_instance_t *)MP_OBJ_TO_PTR(obj))->subobj[0]; } // On failure, say why we could not do it pb_assert_type(obj, type); diff --git a/tests/benchmark/looptime.py b/tests/benchmark/looptime.py index 050d9a6d6..82c0e42f6 100644 --- a/tests/benchmark/looptime.py +++ b/tests/benchmark/looptime.py @@ -5,7 +5,7 @@ watch = StopWatch() for i in range(0, 10000): avg_pos = left.angle() + right.angle() - formula = i//100-avg_pos//36 + formula = i // 100 - avg_pos // 36 left.duty(formula) right.duty(formula) @@ -14,4 +14,4 @@ left.coast() right.coast() -print("usec/loop:", watch.time()//10) # 433 us/loop as of 817bc7b +print("usec/loop:", watch.time() // 10) # 433 us/loop as of 817bc7b diff --git a/tests/ev3dev/brick/screen.py b/tests/ev3dev/brick/screen.py index bc0c0f6cf..6c7eff098 100644 --- a/tests/ev3dev/brick/screen.py +++ b/tests/ev3dev/brick/screen.py @@ -1,4 +1,3 @@ - from pybricks.hubs import EV3Brick from pybricks.parameters import Color from pybricks.media.ev3dev import Font @@ -95,20 +94,20 @@ # Test draw_text() # three required arguments -ev3.screen.draw_text(0, 0, '') -ev3.screen.draw_text(x=0, y=0, text='') +ev3.screen.draw_text(0, 0, "") +ev3.screen.draw_text(x=0, y=0, text="") try: ev3.screen.draw_text(0, 0) except TypeError: pass # 4th argument is kwarg -ev3.screen.draw_text(0, 0, '', Color.BLACK) -ev3.screen.draw_text(0, 0, '', text_color=Color.BLACK) +ev3.screen.draw_text(0, 0, "", Color.BLACK) +ev3.screen.draw_text(0, 0, "", text_color=Color.BLACK) # 5th argument is kwarg -ev3.screen.draw_text(0, 0, '', Color.BLACK, Color.WHITE) -ev3.screen.draw_text(0, 0, '', background_color=Color.WHITE) +ev3.screen.draw_text(0, 0, "", Color.BLACK, Color.WHITE) +ev3.screen.draw_text(0, 0, "", background_color=Color.WHITE) # Test set_font() @@ -127,12 +126,12 @@ ev3.screen.print() # positional args take any object type -ev3.screen.print('', 0, False, ev3.screen, {}, []) +ev3.screen.print("", 0, False, ev3.screen, {}, []) # keyword-only arg end -ev3.screen.print(end='\n') -ev3.screen.print('', end='\n') +ev3.screen.print(end="\n") +ev3.screen.print("", end="\n") # keyword-only arg sep -ev3.screen.print(sep=' ') -ev3.screen.print('', sep=' ') +ev3.screen.print(sep=" ") +ev3.screen.print("", sep=" ") diff --git a/tests/ev3dev/brick/speaker.py b/tests/ev3dev/brick/speaker.py index 092d98650..9fe039ed7 100644 --- a/tests/ev3dev/brick/speaker.py +++ b/tests/ev3dev/brick/speaker.py @@ -47,43 +47,43 @@ # String doesn't work because it iterates each character try: - ev3.speaker.play_notes('C4/4') + ev3.speaker.play_notes("C4/4") except ValueError as ex: print(ex) # First character must be A-G or R try: - ev3.speaker.play_notes(['X']) + ev3.speaker.play_notes(["X"]) except ValueError as ex: print(ex) # Second character must be 2-8 try: - ev3.speaker.play_notes(['C1']) + ev3.speaker.play_notes(["C1"]) except ValueError as ex: print(ex) # Certain notes can't have sharp or flat try: - ev3.speaker.play_notes(['Cb']) + ev3.speaker.play_notes(["Cb"]) except ValueError as ex: print(ex) # '/' delimiter is required try: - ev3.speaker.play_notes(['C#4']) + ev3.speaker.play_notes(["C#4"]) except ValueError as ex: print(ex) # fraction is required try: - ev3.speaker.play_notes(['Db4/']) + ev3.speaker.play_notes(["Db4/"]) except ValueError as ex: print(ex) def notes(): - yield 'E4/4' + yield "E4/4" raise RuntimeError("notes iter error") @@ -110,7 +110,7 @@ def notes(): # file not found gives RuntimeError try: - ev3.speaker.play_file('bad') + ev3.speaker.play_file("bad") except RuntimeError as ex: print(ex) @@ -124,10 +124,10 @@ def notes(): print(ex) # one argument OK -ev3.speaker.say('hi') +ev3.speaker.say("hi") # keyword argument OK -ev3.speaker.say(text='hi') +ev3.speaker.say(text="hi") # set_volume method @@ -142,14 +142,14 @@ def notes(): ev3.speaker.set_volume(0) # two arguments OK -ev3.speaker.set_volume(0, 'Beep') +ev3.speaker.set_volume(0, "Beep") # keyword argument OK -ev3.speaker.set_volume(volume=0, which='Beep') +ev3.speaker.set_volume(volume=0, which="Beep") # only certain values allowed for which= try: - ev3.speaker.set_volume(0, 'bad') + ev3.speaker.set_volume(0, "bad") except ValueError as ex: print(ex) @@ -160,16 +160,16 @@ def notes(): ev3.speaker.set_speech_options() # one argument is OK -ev3.speaker.set_speech_options('en') +ev3.speaker.set_speech_options("en") # two options are OK -ev3.speaker.set_speech_options('en', 'f1') +ev3.speaker.set_speech_options("en", "f1") # three options are OK -ev3.speaker.set_speech_options('en', 'f1', 100) +ev3.speaker.set_speech_options("en", "f1", 100) # four options are OK -ev3.speaker.set_speech_options('en', 'f1', 100, 50) +ev3.speaker.set_speech_options("en", "f1", 100, 50) # keyword args are OK -ev3.speaker.set_speech_options(language='en', voice='f1', speed=100, pitch=50) +ev3.speaker.set_speech_options(language="en", voice="f1", speed=100, pitch=50) diff --git a/tests/ev3dev/experimental/thread_tools.py b/tests/ev3dev/experimental/thread_tools.py index 925114100..56f84d153 100644 --- a/tests/ev3dev/experimental/thread_tools.py +++ b/tests/ev3dev/experimental/thread_tools.py @@ -3,25 +3,25 @@ from pybricks.experimental import run_parallel from pybricks.tools import wait -if uos.getenv('PYBRICKS_BUILD_ENV') == 'docker-armel': +if uos.getenv("PYBRICKS_BUILD_ENV") == "docker-armel": # qemu-user-static has issues with threads - print('SKIP') + print("SKIP") raise SystemExit def task1(): wait(1000) - return 'OK1' + return "OK1" def task2(): wait(500) - return 'OK2' + return "OK2" def task3(): # Unhandled Exception should interrupt all other tasks - raise Exception('oops') + raise Exception("oops") def task4(): diff --git a/tests/ev3dev/media/font.py b/tests/ev3dev/media/font.py index 6167d1a22..b302c762d 100644 --- a/tests/ev3dev/media/font.py +++ b/tests/ev3dev/media/font.py @@ -4,16 +4,16 @@ print(Font.DEFAULT.style) print(Font.DEFAULT.width) print(Font.DEFAULT.height) -print(Font.DEFAULT.text_width('test')) -print(Font.DEFAULT.text_height('test')) +print(Font.DEFAULT.text_width("test")) +print(Font.DEFAULT.text_height("test")) # all args are optional Font() # 1st arg can be None or str -Font('sans-serif') +Font("sans-serif") Font(None) -Font(family='sans-serif') +Font(family="sans-serif") Font(family=None) # 2nd arg is int @@ -30,16 +30,16 @@ # 5th arg is None or str Font(None, 12, False, False, None) -Font(None, 12, False, False, 'en-US') +Font(None, 12, False, False, "en-US") Font(lang=None) -Font(lang='en-US') +Font(lang="en-US") # 6th arg is None or str with len() 4 Font(None, 12, False, False, None, None) -Font(None, 12, False, False, None, 'Latn') +Font(None, 12, False, False, None, "Latn") Font(script=None) -Font(script='Latn') +Font(script="Latn") try: - Font(script='bad') + Font(script="bad") except ValueError: pass diff --git a/tests/ev3dev/media/image.py b/tests/ev3dev/media/image.py index 8c54e9705..7a70b9284 100644 --- a/tests/ev3dev/media/image.py +++ b/tests/ev3dev/media/image.py @@ -4,7 +4,7 @@ from pybricks.media.ev3dev import Font, Image # Working directory is top-level tests directory -TEST_IMAGE = '../ports/pybricks/tests/ev3dev/media/test.png' +TEST_IMAGE = "../ports/pybricks/tests/ev3dev/media/test.png" # requires one argument try: @@ -17,7 +17,7 @@ # error if file does not exist try: - img = Image('bad.png') + img = Image("bad.png") except OSError as ex: print(ex) @@ -36,7 +36,7 @@ # default args for empty are same size as screen empty = Image.empty() -screen = Image('_screen_') +screen = Image("_screen_") print(empty.width == screen.width) print(empty.height == screen.height) @@ -164,20 +164,20 @@ # Test draw_text() # three required arguments -img.draw_text(0, 0, '') -img.draw_text(x=0, y=0, text='') +img.draw_text(0, 0, "") +img.draw_text(x=0, y=0, text="") try: img.draw_text(0, 0) except TypeError as ex: print(ex) # 4th argument is kwarg -img.draw_text(0, 0, '', Color.BLACK) -img.draw_text(0, 0, '', text_color=Color.BLACK) +img.draw_text(0, 0, "", Color.BLACK) +img.draw_text(0, 0, "", text_color=Color.BLACK) # 5th argument is kwarg -img.draw_text(0, 0, '', Color.BLACK, Color.WHITE) -img.draw_text(0, 0, '', background_color=Color.WHITE) +img.draw_text(0, 0, "", Color.BLACK, Color.WHITE) +img.draw_text(0, 0, "", background_color=Color.WHITE) # Test set_font() @@ -196,15 +196,15 @@ img.print() # positional args take any object type -img.print('', 0, False, img, {}, []) +img.print("", 0, False, img, {}, []) # keyword-only arg end -img.print(end='\n') -img.print('', end='\n') +img.print(end="\n") +img.print("", end="\n") # keyword-only arg sep -img.print(sep=' ') -img.print('', sep=' ') +img.print(sep=" ") +img.print("", sep=" ") # Test save() @@ -216,23 +216,23 @@ print(ex) # actually creates file on disk -img.save('test.png') -uos.stat('test.png') -uos.remove('test.png') +img.save("test.png") +uos.stat("test.png") +uos.remove("test.png") # automatically adds file extension if missing -img.save('test') -uos.stat('test.png') -uos.remove('test.png') +img.save("test") +uos.stat("test.png") +uos.remove("test.png") # upper-case is OK too -img.save('TEST.PNG') -uos.stat('TEST.PNG') -uos.remove('TEST.PNG') +img.save("TEST.PNG") +uos.stat("TEST.PNG") +uos.remove("TEST.PNG") # illegal name or permissions issue gives OSError try: # this should fail because we are not root - img.save('/test.png') + img.save("/test.png") except OSError as ex: print(ex) diff --git a/tests/ev3dev/messaging/compat.py b/tests/ev3dev/messaging/compat.py index 6d39b34a0..05b6a63a8 100644 --- a/tests/ev3dev/messaging/compat.py +++ b/tests/ev3dev/messaging/compat.py @@ -27,12 +27,12 @@ def print_payload(self, mbox): print(self._bricks[self._name].get(mbox)) -SERVER = 'server' -CLIENT = 'client' +SERVER = "server" +CLIENT = "client" -LOGIC = 'logic' -NUMERIC = 'numeric' -TEXT = 'text' +LOGIC = "logic" +NUMERIC = "numeric" +TEXT = "text" server = MockConnection(SERVER) @@ -78,7 +78,7 @@ def print_payload(self, mbox): # mailbox that has not received a value returns None print(client_text.read()) -server_text.send('hi') +server_text.send("hi") # should be hi print(client_text.read()) client.print_payload(TEXT) diff --git a/tests/ev3dev/motor/motor.py b/tests/ev3dev/motor/motor.py index 7bb176960..2fefd430a 100644 --- a/tests/ev3dev/motor/motor.py +++ b/tests/ev3dev/motor/motor.py @@ -1,30 +1,34 @@ from pybricks.ev3devices import Motor from pybricks.parameters import Port -IIO_BASE = ('/sys/devices/platform/soc@1c00000/ti-pruss/1c32000.pru1' - '/remoteproc/remoteproc0/virtio0/virtio0.ev3-tacho-rpmsg.-1.0' - '/iio:device1/') -TACHO_BASE = ('/sys/devices/platform/ev3-ports/ev3-ports:outA/lego-port' - '/port4/ev3-ports:outA:lego-ev3-l-motor/tacho-motor/motor0/') +IIO_BASE = ( + "/sys/devices/platform/soc@1c00000/ti-pruss/1c32000.pru1" + "/remoteproc/remoteproc0/virtio0/virtio0.ev3-tacho-rpmsg.-1.0" + "/iio:device1/" +) +TACHO_BASE = ( + "/sys/devices/platform/ev3-ports/ev3-ports:outA/lego-port" + "/port4/ev3-ports:outA:lego-ev3-l-motor/tacho-motor/motor0/" +) def write_iio(attr, value): - with open(IIO_BASE + attr, 'w') as f: - f.write(value + '\n') + with open(IIO_BASE + attr, "w") as f: + f.write(value + "\n") def print_iio(attr): - with open(IIO_BASE + attr, 'r') as f: + with open(IIO_BASE + attr, "r") as f: print(f.read().strip()) def write_tacho(attr, value): - with open(TACHO_BASE + attr, 'w') as f: - f.write(value + '\n') + with open(TACHO_BASE + attr, "w") as f: + f.write(value + "\n") def print_tacho(attr): - with open(TACHO_BASE + attr, 'r') as f: + with open(TACHO_BASE + attr, "r") as f: print(f.read().strip()) @@ -35,7 +39,7 @@ def print_tacho(attr): print(m.angle()) # expect 0 -write_iio('in_count0_raw', '360') +write_iio("in_count0_raw", "360") print(m.angle()) # expect 180 @@ -43,7 +47,7 @@ def print_tacho(attr): print(m.speed()) # expect 0 -write_iio('in_frequency0_input', '1000') +write_iio("in_frequency0_input", "1000") print(m.speed()) # expect 500 @@ -55,26 +59,26 @@ def print_tacho(attr): # testing direct control of duty cycle m.dc(50) -print_tacho('command') # expect "run-direct" -print_tacho('duty_cycle_sp') # expect 50 +print_tacho("command") # expect "run-direct" +print_tacho("duty_cycle_sp") # expect 50 m.dc(100) -print_tacho('command') # expect "run-direct" -print_tacho('duty_cycle_sp') # expect 100 +print_tacho("command") # expect "run-direct" +print_tacho("duty_cycle_sp") # expect 100 # duty cycle > 100 is clipped m.dc(101) -print_tacho('command') # expect "run-direct" -print_tacho('duty_cycle_sp') # expect 100 +print_tacho("command") # expect "run-direct" +print_tacho("duty_cycle_sp") # expect 100 m.dc(-100) -print_tacho('command') # expect "run-direct" -print_tacho('duty_cycle_sp') # expect -100 +print_tacho("command") # expect "run-direct" +print_tacho("duty_cycle_sp") # expect -100 # duty cycle less than -100 is clipped m.dc(-101) -print_tacho('command') # expect "run-direct" -print_tacho('duty_cycle_sp') # expect -100 +print_tacho("command") # expect "run-direct" +print_tacho("duty_cycle_sp") # expect -100 # testing __str__/__repr__ diff --git a/tests/ev3dev/parameters/color.py b/tests/ev3dev/parameters/color.py index 5cf522e3e..aae07edd9 100644 --- a/tests/ev3dev/parameters/color.py +++ b/tests/ev3dev/parameters/color.py @@ -2,9 +2,9 @@ # "enums" should be able to be used as hash values map = { - Color.RED: 'red', - Color.GREEN: 'green', - Color.BLUE: 'blue', + Color.RED: "red", + Color.GREEN: "green", + Color.BLUE: "blue", } print(map[Color.RED]) print(map[Color.GREEN]) diff --git a/tests/ev3dev/v1/display.py b/tests/ev3dev/v1/display.py index 759603923..837a98efd 100644 --- a/tests/ev3dev/v1/display.py +++ b/tests/ev3dev/v1/display.py @@ -4,13 +4,13 @@ from pybricks.parameters import Align # Working directory is top-level tests directory -TEST_IMAGE = '../ports/pybricks/tests/ev3dev/v1/test.png' +TEST_IMAGE = "../ports/pybricks/tests/ev3dev/v1/test.png" ev3.display.clear() -ev3.display.text('test') -ev3.display.text('test', (0, 0)) -ev3.display.text('test', location=(0, 0)) +ev3.display.text("test") +ev3.display.text("test", (0, 0)) +ev3.display.text("test", location=(0, 0)) # NOTE: image() method implementation in v1.0.0 does not match official LEGO # v1.0.0 docs. The LEGO docs list alignment= and coordinates= as separate diff --git a/tests/ev3dev/v1/lights.py b/tests/ev3dev/v1/lights.py index acb2bdc51..a8930f884 100644 --- a/tests/ev3dev/v1/lights.py +++ b/tests/ev3dev/v1/lights.py @@ -2,42 +2,42 @@ from pybricks.parameters import Color from pybricks.tools import wait -SYSFS = '/sys/class/leds/led{}:{}:brick-status/{}' +SYSFS = "/sys/class/leds/led{}:{}:brick-status/{}" LEDS = [ - (0, 'green'), - (0, 'red'), - (1, 'green'), - (1, 'red'), + (0, "green"), + (0, "red"), + (1, "green"), + (1, "red"), ] # since pbio library is just seeking, we need to clear the file to verify # that a new value was written def clear_sysfs(id, color, attr): - with open(SYSFS.format(id, color, attr), 'w') as f: + with open(SYSFS.format(id, color, attr), "w") as f: pass def print_sysfs(id, color, attr): - with open(SYSFS.format(id, color, attr), 'r') as f: + with open(SYSFS.format(id, color, attr), "r") as f: print(f.read()) def test(color_arg): for id, color in LEDS: - clear_sysfs(id, color, 'brightness') + clear_sysfs(id, color, "brightness") ev3.light(color_arg) wait(100) # change doesn't take effect until background thread runs for id, color in LEDS: - print_sysfs(id, color, 'brightness') + print_sysfs(id, color, "brightness") # trigger should be intialized to "none" for id, color in LEDS: - print_sysfs(id, color, 'trigger') + print_sysfs(id, color, "trigger") test(Color.RED) diff --git a/tools/checksum.py b/tools/checksum.py index 65dded35a..451bdf546 100755 --- a/tools/checksum.py +++ b/tools/checksum.py @@ -36,16 +36,16 @@ def sum_complement(fw, max_size): word = fw.read(4) if not word: break - checksum += struct.unpack('I', word)[0] + checksum += struct.unpack("I", word)[0] size += 4 if size > max_size: raise ValueError("File is too large") for _ in range(size, max_size, 4): - checksum += 0xffffffff + checksum += 0xFFFFFFFF - checksum &= 0xffffffff + checksum &= 0xFFFFFFFF correction = checksum and (1 << 32) - checksum or 0 return correction @@ -53,10 +53,24 @@ def sum_complement(fw, max_size): # thanks https://stackoverflow.com/a/33152544/1976323 -_CRC_TABLE = (0x00000000, 0x04C11DB7, 0x09823B6E, 0x0D4326D9, - 0x130476DC, 0x17C56B6B, 0x1A864DB2, 0x1E475005, - 0x2608EDB8, 0x22C9F00F, 0x2F8AD6D6, 0x2B4BCB61, - 0x350C9B64, 0x31CD86D3, 0x3C8EA00A, 0x384FBDBD) +_CRC_TABLE = ( + 0x00000000, + 0x04C11DB7, + 0x09823B6E, + 0x0D4326D9, + 0x130476DC, + 0x17C56B6B, + 0x1A864DB2, + 0x1E475005, + 0x2608EDB8, + 0x22C9F00F, + 0x2F8AD6D6, + 0x2B4BCB61, + 0x350C9B64, + 0x31CD86D3, + 0x3C8EA00A, + 0x384FBDBD, +) def _dword(value): @@ -100,27 +114,26 @@ def crc32_checksum(fw, max_size): raise ValueError("File is too large") if len(fw) & 3: - raise ValueError('bytes_data length must be multiple of four') + raise ValueError("bytes_data length must be multiple of four") - crc = 0xffffffff + crc = 0xFFFFFFFF for index in range(0, len(fw), 4): - data = int.from_bytes(fw[index:index+4], 'little') + data = int.from_bytes(fw[index : index + 4], "little") crc = _crc32_fast(crc, data) return crc -if __name__ == '__main__': - parser = argparse.ArgumentParser(description='Compute checksum.') - parser.add_argument('checksum_type', metavar='type', choices=['xor', 'crc32'], - help='checksum type') - parser.add_argument('fw_file', type=argparse.FileType('rb'), - help='firmware file name') - parser.add_argument('max_size', type=int, - help='max size of firmware file') +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Compute checksum.") + parser.add_argument( + "checksum_type", metavar="type", choices=["xor", "crc32"], help="checksum type" + ) + parser.add_argument("fw_file", type=argparse.FileType("rb"), help="firmware file name") + parser.add_argument("max_size", type=int, help="max size of firmware file") args = parser.parse_args() - if args.checksum_type == 'xor': + if args.checksum_type == "xor": print(hex(sum_complement(args.fw_file, args.max_size))) - elif args.checksum_type == 'crc32': + elif args.checksum_type == "crc32": print(hex(crc32_checksum(args.fw_file, args.max_size))) diff --git a/tools/metadata.py b/tools/metadata.py index 435530358..075930519 100755 --- a/tools/metadata.py +++ b/tools/metadata.py @@ -107,27 +107,15 @@ def generate( if __name__ == "__main__": # want to ignore "-"" prefix so we can pass mpy-cross options but prefix_chars # cant be empty string so we use "+" as dummy value - parser = argparse.ArgumentParser( - description="Generate firmware metadata.", prefix_chars="+" - ) + parser = argparse.ArgumentParser(description="Generate firmware metadata.", prefix_chars="+") parser.add_argument( - "fw_version", - metavar="", - type=str, - help="Pybricks firmware version", + "fw_version", metavar="", type=str, help="Pybricks firmware version", ) parser.add_argument( - "hub_type", - metavar="", - choices=HUB_INFO.keys(), - help="hub type/device ID", + "hub_type", metavar="", choices=HUB_INFO.keys(), help="hub type/device ID", ) parser.add_argument( - "mpy_options", - metavar="", - nargs="*", - type=str, - help="mpy-cross option", + "mpy_options", metavar="", nargs="*", type=str, help="mpy-cross option", ) parser.add_argument( "map_file", @@ -136,13 +124,8 @@ def generate( help="firmware linker map file name", ) parser.add_argument( - "out_file", - metavar="", - type=argparse.FileType("w"), - help="output file name", + "out_file", metavar="", type=argparse.FileType("w"), help="output file name", ) args = parser.parse_args() - generate( - args.fw_version, args.hub_type, args.mpy_options, args.map_file, args.out_file - ) + generate(args.fw_version, args.hub_type, args.mpy_options, args.map_file, args.out_file) diff --git a/tools/mpybytes.py b/tools/mpybytes.py index 33814ac9c..d77f37bab 100755 --- a/tools/mpybytes.py +++ b/tools/mpybytes.py @@ -9,9 +9,9 @@ from pathlib import Path -BUILD_DIR = 'build' -TMP_PY_SCRIPT = '_tmp.py' -TMP_MPY_SCRIPT = '_tmp.mpy' +BUILD_DIR = "build" +TMP_PY_SCRIPT = "_tmp.py" +TMP_MPY_SCRIPT = "_tmp.mpy" def make_build_dir(): @@ -28,20 +28,18 @@ def mpy_bytes_from_file(mpy_cross, path): """Compile a Python file with mpy-cross and return as bytes.""" # Show mpy_cross version - proc = subprocess.Popen([mpy_cross, '--version']) + proc = subprocess.Popen([mpy_cross, "--version"]) proc.wait() # Make the build directory make_build_dir() # Cross-compile Python file to .mpy and raise errors if any - mpy_path = os.path.join(BUILD_DIR, Path(path).stem + '.mpy') - proc = subprocess.run( - [mpy_cross, path, '-mno-unicode', '-o', mpy_path], check=True - ) + mpy_path = os.path.join(BUILD_DIR, Path(path).stem + ".mpy") + proc = subprocess.run([mpy_cross, path, "-mno-unicode", "-o", mpy_path], check=True) # Read the .mpy file and return as bytes - with open(mpy_path, 'rb') as mpy: + with open(mpy_path, "rb") as mpy: return mpy.read() @@ -55,8 +53,8 @@ def mpy_bytes_from_str(mpy_cross, string): py_path = os.path.join(BUILD_DIR, TMP_PY_SCRIPT) # Write Python command to a file and convert as if it is a regular script. - with open(py_path, 'w') as f: - f.write(string + '\n') + with open(py_path, "w") as f: + f.write(string + "\n") # Convert to mpy and get the bytes return mpy_bytes_from_file(mpy_cross, py_path) @@ -64,15 +62,12 @@ def mpy_bytes_from_str(mpy_cross, string): if __name__ == "__main__": parser = argparse.ArgumentParser( - description='Convert Python scripts or commands to .mpy bytes.' - ) - parser.add_argument( - '--mpy_cross', dest='mpy_cross', - nargs='?', type=str, required=True + description="Convert Python scripts or commands to .mpy bytes." ) + parser.add_argument("--mpy_cross", dest="mpy_cross", nargs="?", type=str, required=True) group = parser.add_mutually_exclusive_group(required=True) - group.add_argument('--file', dest='file', nargs='?', const=1, type=str) - group.add_argument('--string', dest='string', nargs='?', const=1, type=str) + group.add_argument("--file", dest="file", nargs="?", const=1, type=str) + group.add_argument("--string", dest="string", nargs="?", const=1, type=str) args = parser.parse_args() if args.file: @@ -88,10 +83,12 @@ def mpy_bytes_from_str(mpy_cross, string): # Print the bytes as a C byte array for development of new MicroPython # ports without usable I/O, REPL or otherwise. WIDTH = 8 - print("\n// MPY file. Version: {0}. Size: {1}".format(data[1], len(data)) + - "\nconst uint8_t script[] = ") + print( + "\n// MPY file. Version: {0}. Size: {1}".format(data[1], len(data)) + + "\nconst uint8_t script[] = " + ) for i in range(0, len(data), WIDTH): - chunk = data[i:i+WIDTH] + chunk = data[i : i + WIDTH] hex_repr = ["0x{0}".format(hex(i)[2:].zfill(2).upper()) for i in chunk] print(" " + ", ".join(hex_repr) + ",") print("};") diff --git a/tools/runserial.py b/tools/runserial.py index 4f963a5f6..5bd1e29c4 100755 --- a/tools/runserial.py +++ b/tools/runserial.py @@ -44,7 +44,7 @@ def download_and_run(device, mpy_bytes): # Split binary up in digestable chunks n = 100 - chunks = [mpy_bytes[i:i+n] for i in range(0, len(mpy_bytes), n)] + chunks = [mpy_bytes[i : i + n] for i in range(0, len(mpy_bytes), n)] # Send the data for chunk in chunks: @@ -58,8 +58,8 @@ def download_and_run(device, mpy_bytes): printed = 0 # Read status to see if program started - RUNNING = b'>>>> RUNNING' - IDLE = b'>>>> IDLE' + RUNNING = b">>>> RUNNING" + IDLE = b">>>> IDLE" if RUNNING not in data: raise OSError("Failed to run program") @@ -69,9 +69,9 @@ def download_and_run(device, mpy_bytes): data += ser.read_all() # Split into lines, printing anything new - text = data.decode().split('\r\n') + text = data.decode().split("\r\n") while printed < len(text): - print(text[printed-1]) + print(text[printed - 1]) printed += 1 # Sleep and exit when done @@ -80,19 +80,19 @@ def download_and_run(device, mpy_bytes): break # Save log if detected in output - start_key = b'PB_OF' - end_key = b'PB_EOF' + start_key = b"PB_OF" + end_key = b"PB_EOF" if start_key in data and end_key in data: # Get data between keys - start = data.index(start_key)+len(start_key)+1 - end = data.index(end_key)-2 + start = data.index(start_key) + len(start_key) + 1 + end = data.index(end_key) - 2 log_data = data[start:end] # Extract file name and data - lines = log_data.decode().split('\r\n') - with open(lines[0], 'w') as f: - print(*lines[1:], sep='\n', file=f) + lines = log_data.decode().split("\r\n") + with open(lines[0], "w") as f: + print(*lines[1:], sep="\n", file=f) if __name__ == "__main__": @@ -103,19 +103,16 @@ def download_and_run(device, mpy_bytes): """ parser = argparse.ArgumentParser( - description='Run Pybricks scripts or commands over serial port.', + description="Run Pybricks scripts or commands over serial port.", epilog=examples, - formatter_class=argparse.RawDescriptionHelpFormatter) - - parser.add_argument( - '--mpy_cross', dest='mpy_cross', - nargs='?', type=str, required=True + formatter_class=argparse.RawDescriptionHelpFormatter, ) - parser.add_argument( - '--dev', dest='device', nargs='?', type=str, required=True) + + parser.add_argument("--mpy_cross", dest="mpy_cross", nargs="?", type=str, required=True) + parser.add_argument("--dev", dest="device", nargs="?", type=str, required=True) group = parser.add_mutually_exclusive_group(required=True) - group.add_argument('--file', dest='file', nargs='?', const=1, type=str) - group.add_argument('--string', dest='string', nargs='?', const=1, type=str) + group.add_argument("--file", dest="file", nargs="?", const=1, type=str) + group.add_argument("--string", dest="string", nargs="?", const=1, type=str) args = parser.parse_args() if args.file: