From a52eb88031620a81521b937f2a0651dbac2bb350 Mon Sep 17 00:00:00 2001 From: microDev <70126934+microDev1@users.noreply.github.com> Date: Mon, 15 Mar 2021 19:27:36 +0530 Subject: [PATCH] run code formatting script --- devices/ble_hci/common-hal/_bleio/Adapter.c | 38 +- devices/ble_hci/common-hal/_bleio/Adapter.h | 12 +- .../common-hal/_bleio/Characteristic.c | 28 +- .../common-hal/_bleio/CharacteristicBuffer.c | 18 +- .../ble_hci/common-hal/_bleio/Connection.c | 26 +- .../ble_hci/common-hal/_bleio/Connection.h | 8 +- .../ble_hci/common-hal/_bleio/Descriptor.c | 14 +- .../ble_hci/common-hal/_bleio/Descriptor.h | 2 +- .../ble_hci/common-hal/_bleio/PacketBuffer.c | 20 +- .../ble_hci/common-hal/_bleio/PacketBuffer.h | 2 +- devices/ble_hci/common-hal/_bleio/Service.c | 8 +- devices/ble_hci/common-hal/_bleio/Service.h | 2 +- devices/ble_hci/common-hal/_bleio/UUID.c | 2 +- devices/ble_hci/common-hal/_bleio/UUID.h | 22 +- devices/ble_hci/common-hal/_bleio/__init__.c | 2 +- devices/ble_hci/common-hal/_bleio/__init__.h | 2 +- devices/ble_hci/common-hal/_bleio/att.c | 202 ++- devices/ble_hci/common-hal/_bleio/att.h | 12 +- devices/ble_hci/common-hal/_bleio/hci.c | 109 +- devices/ble_hci/common-hal/_bleio/hci_debug.c | 688 ++++++---- .../common-hal/_bleio/hci_include/addr.h | 52 +- .../common-hal/_bleio/hci_include/att.h | 46 +- .../_bleio/hci_include/att_internal.h | 226 ++-- .../common-hal/_bleio/hci_include/hci.h | 1152 ++++++++--------- .../common-hal/_bleio/hci_include/hci_raw.h | 68 +- .../common-hal/_bleio/hci_include/hci_vs.h | 276 ++-- .../_bleio/hci_include/l2cap_internal.h | 132 +- drivers/bus/softqspi.c | 18 +- drivers/bus/softspi.c | 4 +- extmod/machine_mem.c | 24 +- extmod/machine_signal.c | 7 +- extmod/modbtree.c | 36 +- extmod/modframebuf.c | 70 +- extmod/modlwip.c | 126 +- extmod/modonewire.c | 4 +- extmod/modubinascii.c | 21 +- extmod/moductypes.c | 93 +- extmod/moduhashlib.c | 42 +- extmod/moduheapq.c | 4 +- extmod/modujson.c | 55 +- extmod/modurandom.c | 25 +- extmod/modure.c | 50 +- extmod/moduselect.c | 24 +- extmod/modussl_axtls.c | 22 +- extmod/modussl_mbedtls.c | 32 +- extmod/modutimeq.c | 15 +- extmod/moduzlib.c | 18 +- extmod/modwebrepl.c | 16 +- extmod/modwebsocket.c | 14 +- extmod/utime_mphal.c | 2 +- extmod/vfs.c | 10 +- extmod/vfs.h | 4 +- extmod/vfs_fat.c | 22 +- extmod/vfs_fat_diskio.c | 41 +- extmod/vfs_fat_file.c | 6 +- extmod/vfs_posix.c | 6 +- extmod/vfs_posix_file.c | 12 +- extmod/vfs_reader.c | 6 +- extmod/virtpin.c | 4 +- lib/netutils/netutils.c | 2 +- lib/timeutils/timeutils.c | 10 +- lib/timeutils/timeutils.h | 18 +- lib/utils/buffer_helper.c | 4 +- lib/utils/buffer_helper.h | 2 +- lib/utils/context_manager_helpers.c | 2 +- lib/utils/printf.c | 4 +- lib/utils/pyexec.c | 32 +- lib/utils/pyexec.h | 2 +- lib/utils/stdout_helpers.c | 2 +- lib/utils/sys_stdio_mphal.c | 12 +- mpy-cross/fmode.c | 6 +- mpy-cross/gccollect.c | 20 +- mpy-cross/main.c | 47 +- mpy-cross/mpconfigport.h | 82 +- .../asf4_conf/samd21/hpl_gclk_config.h | 32 +- .../asf4_conf/samd21/hpl_sercom_config.h | 40 +- .../asf4_conf/samd21/hpl_sysctrl_config.h | 16 +- .../asf4_conf/samd21/hpl_tc_config.h | 18 +- .../atmel-samd/asf4_conf/samd21/usbd_config.h | 26 +- .../asf4_conf/samd51/hpl_gclk_config.h | 74 +- .../asf4_conf/samd51/hpl_oscctrl_config.h | 22 +- .../asf4_conf/samd51/hpl_sercom_config.h | 40 +- .../asf4_conf/samd51/hpl_tc_config.h | 30 +- .../atmel-samd/asf4_conf/samd51/usbd_config.h | 26 +- .../asf4_conf/same51/hpl_gclk_config.h | 74 +- .../asf4_conf/same51/hpl_oscctrl_config.h | 22 +- .../asf4_conf/same51/hpl_sercom_config.h | 40 +- .../asf4_conf/same51/hpl_tc_config.h | 30 +- .../atmel-samd/asf4_conf/same51/usbd_config.h | 26 +- .../asf4_conf/same54/hpl_gclk_config.h | 74 +- .../asf4_conf/same54/hpl_oscctrl_config.h | 22 +- .../asf4_conf/same54/hpl_sercom_config.h | 40 +- .../asf4_conf/same54/hpl_tc_config.h | 30 +- .../atmel-samd/asf4_conf/same54/usbd_config.h | 26 +- ports/atmel-samd/audio_dma.c | 126 +- ports/atmel-samd/audio_dma.h | 34 +- ports/atmel-samd/background.c | 15 +- ports/atmel-samd/bindings/samd/Clock.c | 38 +- ports/atmel-samd/bindings/samd/Clock.h | 52 +- ports/atmel-samd/bindings/samd/__init__.c | 4 +- .../boards/8086_commander/mpconfigboard.h | 6 +- .../boards/aloriumtech_evo_m51/board.c | 29 +- .../aloriumtech_evo_m51/mpconfigboard.h | 10 +- .../atmel-samd/boards/arduino_mkr1300/board.c | 3 +- .../boards/arduino_nano_33_iot/board.c | 3 +- ports/atmel-samd/boards/arduino_zero/board.c | 3 +- .../boards/bast_pro_mini_m0/board.c | 3 +- .../boards/bdmicro_vina_d21/board.c | 3 +- .../boards/bdmicro_vina_d51/board.c | 3 +- .../atmel-samd/boards/catwan_usbstick/board.c | 3 +- .../boards/circuitbrains_basic_m0/pins.c | 0 .../boards/circuitplayground_express/board.c | 3 +- .../circuitplayground_express/mpconfigboard.h | 2 +- .../circuitplayground_express_crickit/board.c | 3 +- .../board.c | 3 +- .../atmel-samd/boards/cp32-m4/mpconfigboard.h | 4 +- .../boards/cp_sapling_m0/mpconfigboard.h | 14 +- .../cp_sapling_m0_spiflash/mpconfigboard.h | 14 +- .../atmel-samd/boards/datum_distance/board.c | 3 +- ports/atmel-samd/boards/datum_imu/board.c | 3 +- ports/atmel-samd/boards/datum_light/board.c | 3 +- ports/atmel-samd/boards/datum_weather/board.c | 3 +- .../boards/dynossat_edu_eps/board.c | 3 +- .../boards/dynossat_edu_eps/mpconfigboard.h | 8 +- .../boards/dynossat_edu_obc/board.c | 3 +- .../boards/dynossat_edu_obc/mpconfigboard.h | 8 +- .../boards/escornabot_makech/board.c | 3 +- .../boards/escornabot_makech/pins.c | 4 +- .../boards/feather_m0_adalogger/board.c | 3 +- .../boards/feather_m0_basic/board.c | 3 +- .../boards/feather_m0_express/board.c | 3 +- .../boards/feather_m0_express/mpconfigboard.h | 4 +- .../boards/feather_m0_express_crickit/board.c | 3 +- .../mpconfigboard.h | 4 +- .../boards/feather_m0_rfm69/board.c | 3 +- .../boards/feather_m0_rfm9x/board.c | 3 +- .../boards/feather_m0_supersized/board.c | 3 +- .../feather_m0_supersized/mpconfigboard.h | 4 +- .../boards/feather_radiofruit_zigbee/board.c | 3 +- .../feather_radiofruit_zigbee/mpconfigboard.h | 4 +- ports/atmel-samd/boards/fluff_m0/board.c | 3 +- ports/atmel-samd/boards/gemma_m0/board.c | 3 +- .../grandcentral_m4_express/mpconfigboard.h | 6 +- .../boards/hallowing_m0_express/board.c | 16 +- .../hallowing_m0_express/mpconfigboard.h | 6 +- .../boards/hallowing_m4_express/board.c | 6 +- .../boards/kicksat-sprite/mpconfigboard.h | 2 +- ports/atmel-samd/boards/kicksat-sprite/pins.c | 18 +- ports/atmel-samd/boards/meowmeow/board.c | 3 +- .../boards/metro_m0_express/board.c | 3 +- ports/atmel-samd/boards/monster_m4sk/board.c | 6 +- ports/atmel-samd/boards/nfc_copy_cat/board.c | 3 +- ports/atmel-samd/boards/openbook_m4/board.c | 6 +- ports/atmel-samd/boards/pewpew_m4/board.c | 21 +- .../boards/picoplanet/mpconfigboard.h | 10 +- ports/atmel-samd/boards/pirkey_m0/board.c | 3 +- ports/atmel-samd/boards/pybadge/board.c | 18 +- .../atmel-samd/boards/pybadge_airlift/board.c | 6 +- .../atmel-samd/boards/pybadge_airlift/pins.c | 3 +- ports/atmel-samd/boards/pycubed/board.c | 8 +- .../atmel-samd/boards/pycubed/mpconfigboard.h | 4 +- ports/atmel-samd/boards/pycubed_mram/board.c | 8 +- .../boards/pycubed_mram/mpconfigboard.h | 2 +- ports/atmel-samd/boards/pygamer/board.c | 18 +- .../atmel-samd/boards/pygamer_advance/board.c | 6 +- ports/atmel-samd/boards/pyportal/board.c | 8 +- .../boards/pyportal/mpconfigboard.h | 6 +- .../atmel-samd/boards/pyportal_titano/board.c | 58 +- .../boards/pyportal_titano/mpconfigboard.h | 6 +- .../boards/robohatmm1_m4/mpconfigboard.h | 4 +- ports/atmel-samd/boards/robohatmm1_m4/pins.c | 144 +-- ports/atmel-samd/boards/sam32/mpconfigboard.h | 2 +- .../boards/same54_xplained/mpconfigboard.h | 4 +- .../boards/seeeduino_wio_terminal/board.c | 34 +- .../boards/seeeduino_wio_terminal/pins.c | 2 +- ports/atmel-samd/boards/snekboard/board.c | 3 +- .../boards/snekboard/mpconfigboard.h | 12 +- .../boards/sparkfun_lumidrive/board.c | 3 +- .../boards/sparkfun_lumidrive/mpconfigboard.h | 10 +- .../sparkfun_qwiic_micro_no_flash/board.c | 3 +- .../mpconfigboard.h | 12 +- .../sparkfun_qwiic_micro_with_flash/board.c | 3 +- .../mpconfigboard.h | 12 +- .../boards/sparkfun_redboard_turbo/board.c | 3 +- .../sparkfun_redboard_turbo/mpconfigboard.h | 6 +- .../boards/stackrduino_m0_pro/pins.c | 10 +- ports/atmel-samd/boards/uchip/mpconfigboard.h | 2 +- ports/atmel-samd/boards/ugame10/board.c | 16 +- .../winterbloom_big_honking_button/board.c | 3 +- .../mpconfigboard.h | 4 +- .../usermods/_bhb/bhb.c | 38 +- ports/atmel-samd/boards/xinabox_cc03/board.c | 3 +- ports/atmel-samd/boards/xinabox_cs11/board.c | 3 +- ports/atmel-samd/common-hal/_pew/PewPew.c | 8 +- ports/atmel-samd/common-hal/_pew/PewPew.h | 6 +- ports/atmel-samd/common-hal/_pew/__init__.c | 8 +- .../atmel-samd/common-hal/analogio/AnalogIn.c | 10 +- .../atmel-samd/common-hal/analogio/AnalogIn.h | 4 +- .../common-hal/analogio/AnalogOut.c | 40 +- .../atmel-samd/common-hal/audiobusio/I2SOut.c | 71 +- .../common-hal/audiobusio/PDMIn.c.uncrustify | 0 ports/atmel-samd/modules/frozentest.py | 8 +- ports/atmel-samd/tools/gen_pin_name_table.py | 279 +++- ports/atmel-samd/tools/mkcandata.py | 32 +- ports/atmel-samd/tools/mksdiodata.py | 38 +- ports/atmel-samd/tools/update_asf.py | 10 +- ports/cxd56/boards/spresense/board.c | 3 +- ports/cxd56/common-hal/analogio/AnalogIn.c | 4 +- ports/cxd56/common-hal/busio/I2C.c | 2 +- ports/cxd56/common-hal/busio/I2C.h | 2 +- ports/cxd56/common-hal/busio/SPI.c | 2 +- ports/cxd56/common-hal/busio/SPI.h | 2 +- ports/cxd56/common-hal/busio/UART.c | 12 +- ports/cxd56/common-hal/camera/Camera.c | 2 +- ports/cxd56/common-hal/gnss/GNSS.c | 8 +- ports/cxd56/common-hal/microcontroller/Pin.h | 12 +- .../common-hal/microcontroller/Processor.c | 2 +- .../common-hal/microcontroller/__init__.c | 12 +- ports/cxd56/common-hal/os/__init__.c | 4 +- ports/cxd56/common-hal/pulseio/PulseIn.c | 4 +- ports/cxd56/common-hal/pulseio/PulseOut.c | 17 +- ports/cxd56/common-hal/pwmio/PWMOut.c | 10 +- ports/cxd56/common-hal/sdioio/SDCard.c | 13 +- ports/cxd56/common-hal/sdioio/SDCard.h | 2 +- ports/cxd56/common-hal/supervisor/Runtime.c | 4 +- ports/cxd56/fatfs_port.c | 8 +- ports/cxd56/mkspk/clefia.c | 600 ++++----- ports/cxd56/mkspk/clefia.h | 10 +- ports/cxd56/mkspk/elf32.h | 124 +- ports/cxd56/mkspk/mkspk.c | 407 +++--- ports/cxd56/mkspk/mkspk.h | 12 +- ports/cxd56/mphalport.h | 2 +- ports/cxd56/supervisor/port.c | 29 +- ports/cxd56/tools/flash_writer.py | 973 +++++++------- ports/cxd56/tools/xmodem.py | 424 ++++-- ports/esp32s2/background.c | 6 +- ports/esp32s2/bindings/espidf/__init__.c | 12 +- ports/esp32s2/bindings/espidf/__init__.h | 2 +- .../adafruit_feather_esp32s2_nopsram/board.c | 4 +- .../mpconfigboard.h | 2 +- .../board.c | 4 +- .../mpconfigboard.h | 2 +- .../pins.c | 2 +- .../adafruit_magtag_2.9_grayscale/board.c | 14 +- .../mpconfigboard.h | 2 +- .../adafruit_metro_esp32s2/mpconfigboard.h | 2 +- .../boards/electroniccats_bastwifi/board.c | 4 +- .../electroniccats_bastwifi/mpconfigboard.h | 2 +- .../esp32s2/boards/espressif_kaluga_1/board.c | 4 +- .../boards/espressif_kaluga_1/mpconfigboard.h | 2 +- .../boards/espressif_saola_1_wroom/board.c | 4 +- .../espressif_saola_1_wroom/mpconfigboard.h | 2 +- .../boards/espressif_saola_1_wrover/board.c | 4 +- .../espressif_saola_1_wrover/mpconfigboard.h | 2 +- .../boards/franzininho_wifi_wroom/board.c | 4 +- .../franzininho_wifi_wroom/mpconfigboard.h | 2 +- .../boards/franzininho_wifi_wrover/board.c | 4 +- .../franzininho_wifi_wrover/mpconfigboard.h | 2 +- .../boards/lilygo_ttgo_t8_s2_st7789/board.c | 18 +- .../lilygo_ttgo_t8_s2_st7789/mpconfigboard.h | 2 +- .../esp32s2/boards/microdev_micro_s2/board.c | 4 +- .../boards/microdev_micro_s2/mpconfigboard.h | 2 +- .../boards/muselab_nanoesp32_s2/board.c | 4 +- .../muselab_nanoesp32_s2/mpconfigboard.h | 2 +- .../boards/targett_module_clip_wroom/board.c | 4 +- .../targett_module_clip_wroom/mpconfigboard.h | 6 +- .../boards/targett_module_clip_wroom/pins.c | 2 +- .../boards/targett_module_clip_wrover/board.c | 6 +- .../mpconfigboard.h | 6 +- .../boards/targett_module_clip_wrover/pins.c | 2 +- .../boards/unexpectedmaker_feathers2/board.c | 4 +- .../unexpectedmaker_feathers2/mpconfigboard.h | 2 +- .../board.c | 4 +- .../mpconfigboard.h | 2 +- .../boards/unexpectedmaker_tinys2/board.c | 4 +- .../unexpectedmaker_tinys2/mpconfigboard.h | 2 +- ports/esp32s2/common-hal/alarm/SleepMemory.c | 8 +- ports/esp32s2/common-hal/alarm/pin/PinAlarm.c | 16 +- ports/esp32s2/common-hal/alarm/pin/__init__.c | 12 +- .../esp32s2/common-hal/alarm/time/TimeAlarm.c | 6 +- .../common-hal/alarm/touch/TouchAlarm.c | 8 +- ports/esp32s2/common-hal/analogio/AnalogIn.c | 10 +- ports/esp32s2/common-hal/analogio/AnalogIn.h | 2 +- ports/esp32s2/common-hal/analogio/AnalogOut.c | 8 +- ports/esp32s2/common-hal/analogio/AnalogOut.h | 2 +- ports/esp32s2/common-hal/audiobusio/I2SOut.c | 24 +- .../esp32s2/common-hal/audiobusio/__init__.c | 34 +- ports/esp32s2/common-hal/busio/I2C.c | 20 +- ports/esp32s2/common-hal/busio/I2C.h | 4 +- ports/esp32s2/common-hal/busio/SPI.c | 85 +- ports/esp32s2/common-hal/busio/SPI.h | 6 +- ports/esp32s2/common-hal/busio/UART.c | 14 +- ports/esp32s2/common-hal/busio/UART.h | 8 +- ports/esp32s2/common-hal/canio/CAN.c | 167 ++- ports/esp32s2/common-hal/canio/CAN.h | 8 +- ports/esp32s2/common-hal/canio/Listener.c | 7 +- ports/esp32s2/common-hal/canio/Listener.h | 6 +- ports/esp32s2/common-hal/countio/Counter.c | 20 +- ports/esp32s2/common-hal/countio/__init__.c | 2 +- .../common-hal/digitalio/DigitalInOut.c | 26 +- .../common-hal/displayio/ParallelBus.c | 107 +- .../common-hal/displayio/ParallelBus.h | 6 +- ports/esp32s2/common-hal/dualbank/__init__.c | 4 +- ports/esp32s2/common-hal/dualbank/__init__.h | 2 +- .../common-hal/frequencyio/FrequencyIn.c | 24 +- .../esp32s2/common-hal/microcontroller/Pin.c | 16 +- .../esp32s2/common-hal/microcontroller/Pin.h | 4 +- .../common-hal/microcontroller/Processor.c | 14 +- .../common-hal/microcontroller/__init__.c | 7 +- .../common-hal/neopixel_write/__init__.c | 15 +- ports/esp32s2/common-hal/nvm/ByteArray.c | 6 +- ports/esp32s2/common-hal/nvm/ByteArray.h | 2 +- ports/esp32s2/common-hal/os/__init__.c | 4 +- ports/esp32s2/common-hal/ps2io/Ps2.c | 52 +- ports/esp32s2/common-hal/pulseio/PulseIn.c | 42 +- ports/esp32s2/common-hal/pulseio/PulseIn.h | 4 +- ports/esp32s2/common-hal/pulseio/PulseOut.c | 20 +- ports/esp32s2/common-hal/pwmio/PWMOut.c | 36 +- ports/esp32s2/common-hal/pwmio/PWMOut.h | 4 +- .../common-hal/rotaryio/IncrementalEncoder.c | 18 +- ports/esp32s2/common-hal/socketpool/Socket.c | 54 +- ports/esp32s2/common-hal/socketpool/Socket.h | 4 +- .../common-hal/socketpool/SocketPool.c | 8 +- ports/esp32s2/common-hal/ssl/SSLContext.c | 8 +- ports/esp32s2/common-hal/ssl/SSLSocket.c | 36 +- ports/esp32s2/common-hal/ssl/SSLSocket.h | 6 +- ports/esp32s2/common-hal/ssl/__init__.c | 2 +- ports/esp32s2/common-hal/supervisor/Runtime.c | 4 +- ports/esp32s2/common-hal/touchio/TouchIn.c | 8 +- ports/esp32s2/common-hal/touchio/TouchIn.h | 2 +- .../common-hal/watchdog/WatchDogTimer.c | 6 +- .../common-hal/watchdog/WatchDogTimer.h | 6 +- ports/esp32s2/common-hal/wifi/Network.c | 14 +- ports/esp32s2/common-hal/wifi/Radio.c | 12 +- .../esp32s2/common-hal/wifi/ScannedNetworks.c | 20 +- .../esp32s2/common-hal/wifi/ScannedNetworks.h | 2 +- ports/esp32s2/common-hal/wifi/__init__.c | 48 +- ports/esp32s2/common-hal/wifi/__init__.h | 2 +- ports/esp32s2/esp_error.c | 10 +- ports/esp32s2/fatfs_port.c | 2 +- ports/esp32s2/mpconfigport.h | 2 +- ports/esp32s2/mphalport.c | 2 +- ports/esp32s2/mphalport.h | 2 +- ports/esp32s2/peripherals/pcnt.c | 6 +- ports/esp32s2/peripherals/pcnt.h | 2 +- ports/esp32s2/peripherals/pins.c | 14 +- ports/esp32s2/peripherals/pins.h | 4 +- ports/esp32s2/peripherals/timer.c | 8 +- ports/esp32s2/peripherals/timer.h | 4 +- ports/esp32s2/supervisor/internal_flash.c | 30 +- ports/esp32s2/supervisor/port.c | 80 +- ports/esp32s2/supervisor/usb.c | 52 +- ports/esp32s2/tools/decode_backtrace.py | 9 +- ports/litex/background.c | 9 +- ports/litex/boards/fomu/csr.h | 426 +++--- ports/litex/boards/fomu/generated/soc.h | 34 +- ports/litex/boards/fomu/mpconfigboard.h | 4 +- ports/litex/boards/fomu/pins.c | 8 +- .../litex/common-hal/digitalio/DigitalInOut.c | 36 +- ports/litex/common-hal/microcontroller/Pin.c | 12 +- ports/litex/common-hal/microcontroller/Pin.h | 10 +- .../common-hal/microcontroller/__init__.c | 19 +- .../common-hal/neopixel_write/__init__.c | 7 +- ports/litex/common-hal/os/__init__.c | 4 +- ports/litex/common-hal/supervisor/Runtime.c | 4 +- ports/litex/fatfs_port.c | 2 +- ports/litex/hw/common.h | 30 +- ports/litex/irq.h | 65 +- ports/litex/mpconfigport.h | 2 +- ports/litex/mphalport.c | 12 +- ports/litex/mphalport.h | 4 +- ports/litex/supervisor/internal_flash.c | 73 +- ports/litex/supervisor/port.c | 6 +- ports/mimxrt10xx/background.c | 6 +- .../mimxrt10xx/boards/feather_m7_1011/board.c | 4 +- .../boards/feather_m7_1011/flash_config.c | 268 ++-- .../boards/feather_mimxrt1011/board.c | 4 +- .../boards/feather_mimxrt1011/flash_config.c | 268 ++-- .../boards/feather_mimxrt1011/pins.c | 2 +- .../boards/feather_mimxrt1062/board.c | 4 +- .../boards/feather_mimxrt1062/flash_config.c | 268 ++-- .../boards/feather_mimxrt1062/mpconfigboard.h | 6 +- ports/mimxrt10xx/boards/imxrt1010_evk/board.c | 4 +- .../boards/imxrt1010_evk/flash_config.c | 268 ++-- ports/mimxrt10xx/boards/imxrt1020_evk/board.c | 4 +- .../boards/imxrt1020_evk/flash_config.c | 268 ++-- ports/mimxrt10xx/boards/imxrt1060_evk/board.c | 4 +- .../boards/imxrt1060_evk/flash_config.c | 268 ++-- ports/mimxrt10xx/boards/metro_m7_1011/board.c | 4 +- .../boards/metro_m7_1011/flash_config.c | 288 ++--- .../mimxrt10xx/boards/teensy40/flash_config.c | 288 ++--- .../mimxrt10xx/boards/teensy41/flash_config.c | 268 ++-- .../mimxrt10xx/common-hal/analogio/AnalogIn.c | 4 +- .../common-hal/analogio/AnalogOut.c | 2 +- ports/mimxrt10xx/common-hal/busio/I2C.c | 64 +- ports/mimxrt10xx/common-hal/busio/SPI.c | 71 +- ports/mimxrt10xx/common-hal/busio/UART.c | 50 +- ports/mimxrt10xx/common-hal/busio/UART.h | 2 +- .../common-hal/digitalio/DigitalInOut.c | 47 +- .../common-hal/displayio/ParallelBus.c | 10 +- .../common-hal/microcontroller/Pin.c | 24 +- .../common-hal/microcontroller/Pin.h | 2 +- .../common-hal/microcontroller/Processor.c | 2 +- .../common-hal/microcontroller/__init__.c | 12 +- .../common-hal/neopixel_write/__init__.c | 33 +- ports/mimxrt10xx/common-hal/os/__init__.c | 4 +- ports/mimxrt10xx/common-hal/pulseio/PulseIn.c | 36 +- ports/mimxrt10xx/common-hal/pulseio/PulseIn.h | 4 +- .../mimxrt10xx/common-hal/pulseio/PulseOut.c | 42 +- .../mimxrt10xx/common-hal/pulseio/PulseOut.h | 2 +- ports/mimxrt10xx/common-hal/pwmio/PWMOut.c | 73 +- ports/mimxrt10xx/common-hal/rtc/RTC.c | 14 +- .../common-hal/supervisor/Runtime.c | 4 +- ports/mimxrt10xx/fatfs_port.c | 8 +- ports/mimxrt10xx/mpconfigport.h | 6 +- ports/mimxrt10xx/mphalport.c | 6 +- ports/mimxrt10xx/mphalport.h | 2 +- .../mimxrt10xx/MIMXRT1011/clocks.c | 11 +- .../mimxrt10xx/MIMXRT1011/periph.c | 2 +- .../peripherals/mimxrt10xx/MIMXRT1011/pins.c | 2 +- .../mimxrt10xx/MIMXRT1021/clocks.c | 29 +- .../mimxrt10xx/MIMXRT1021/periph.c | 2 +- .../peripherals/mimxrt10xx/MIMXRT1021/pins.c | 2 +- .../mimxrt10xx/MIMXRT1062/clocks.c | 45 +- .../mimxrt10xx/MIMXRT1062/periph.c | 2 +- .../peripherals/mimxrt10xx/MIMXRT1062/pins.c | 2 +- .../peripherals/mimxrt10xx/periph.h | 36 +- .../mimxrt10xx/peripherals/mimxrt10xx/pins.h | 24 +- .../supervisor/flexspi_nor_flash_ops.c | 83 +- ports/mimxrt10xx/supervisor/internal_flash.c | 16 +- ports/mimxrt10xx/supervisor/port.c | 98 +- ports/mimxrt10xx/supervisor/serial.c | 8 +- ports/mimxrt10xx/supervisor/usb.c | 6 +- ports/nrf/background.c | 14 +- ports/nrf/bluetooth/ble_drv.c | 40 +- ports/nrf/bluetooth/ble_drv.h | 6 +- ports/nrf/bluetooth/ble_uart.c | 14 +- ports/nrf/bluetooth/ringbuffer.h | 30 +- .../s140_nrf52_6.1.0_API/include/ble.h | 162 +-- .../s140_nrf52_6.1.0_API/include/ble_err.h | 20 +- .../s140_nrf52_6.1.0_API/include/ble_gap.h | 646 ++++----- .../s140_nrf52_6.1.0_API/include/ble_gatt.h | 24 +- .../s140_nrf52_6.1.0_API/include/ble_gattc.h | 236 ++-- .../s140_nrf52_6.1.0_API/include/ble_gatts.h | 232 ++-- .../s140_nrf52_6.1.0_API/include/ble_l2cap.h | 108 +- .../s140_nrf52_6.1.0_API/include/ble_types.h | 32 +- .../include/nrf52/nrf_mbr.h | 56 +- .../s140_nrf52_6.1.0_API/include/nrf_error.h | 2 +- .../include/nrf_error_sdm.h | 2 +- .../s140_nrf52_6.1.0_API/include/nrf_nvic.h | 345 +++-- .../s140_nrf52_6.1.0_API/include/nrf_sdm.h | 34 +- .../s140_nrf52_6.1.0_API/include/nrf_soc.h | 328 ++--- .../s140_nrf52_6.1.0_API/include/nrf_svc.h | 34 +- .../s140_nrf52_7.0.1_API/include/ble.h | 162 +-- .../s140_nrf52_7.0.1_API/include/ble_err.h | 20 +- .../s140_nrf52_7.0.1_API/include/ble_gap.h | 674 +++++----- .../s140_nrf52_7.0.1_API/include/ble_gatt.h | 24 +- .../s140_nrf52_7.0.1_API/include/ble_gattc.h | 236 ++-- .../s140_nrf52_7.0.1_API/include/ble_gatts.h | 232 ++-- .../s140_nrf52_7.0.1_API/include/ble_l2cap.h | 108 +- .../s140_nrf52_7.0.1_API/include/ble_types.h | 32 +- .../include/nrf52/nrf_mbr.h | 56 +- .../s140_nrf52_7.0.1_API/include/nrf_error.h | 2 +- .../include/nrf_error_sdm.h | 2 +- .../s140_nrf52_7.0.1_API/include/nrf_nvic.h | 345 +++-- .../s140_nrf52_7.0.1_API/include/nrf_sdm.h | 34 +- .../s140_nrf52_7.0.1_API/include/nrf_soc.h | 328 ++--- .../s140_nrf52_7.0.1_API/include/nrf_svc.h | 34 +- ports/nrf/boards/ADM_B_NRF52840_1/board.c | 2 +- ports/nrf/boards/TG-Watch/board.c | 2 +- ports/nrf/boards/arduino_nano_33_ble/board.c | 2 +- ports/nrf/boards/bastble/board.c | 2 +- .../bless_dev_board_multi_sensor/board.c | 2 +- .../circuitplayground_bluefruit/board.c | 12 +- .../nrf/boards/clue_nrf52840_express/board.c | 6 +- ports/nrf/boards/electronut_labs_blip/board.c | 2 +- .../nrf/boards/electronut_labs_papyr/board.c | 2 +- .../boards/feather_bluefruit_sense/board.c | 2 +- .../boards/feather_nrf52840_express/board.c | 2 +- ports/nrf/boards/hiibot_bluefi/board.c | 10 +- .../nrf/boards/hiibot_bluefi/mpconfigboard.h | 40 +- ports/nrf/boards/hiibot_bluefi/pins.c | 2 +- ports/nrf/boards/ikigaisense_vita/board.c | 2 +- .../boards/itsybitsy_nrf52840_express/board.c | 2 +- .../boards/makerdiary_m60_keyboard/board.c | 2 +- .../nrf/boards/makerdiary_m60_keyboard/pins.c | 50 +- .../makerdiary_nrf52840_m2_devkit/board.c | 6 +- .../makerdiary_nrf52840_m2_devkit/pins.c | 180 +-- .../boards/makerdiary_nrf52840_mdk/board.c | 2 +- .../nrf/boards/makerdiary_nrf52840_mdk/pins.c | 96 +- .../board.c | 2 +- .../makerdiary_nrf52840_mdk_usb_dongle/pins.c | 54 +- .../nrf/boards/metro_nrf52840_express/board.c | 2 +- ports/nrf/boards/nice_nano/board.c | 2 +- ports/nrf/boards/nice_nano/mpconfigboard.h | 14 +- ports/nrf/boards/nrf52_prefix.c | 14 +- ports/nrf/boards/ohs2020_badge/board.c | 6 +- ports/nrf/boards/particle_argon/board.c | 2 +- ports/nrf/boards/particle_boron/board.c | 2 +- ports/nrf/boards/particle_xenon/board.c | 2 +- ports/nrf/boards/pca10056/board.c | 2 +- ports/nrf/boards/pca10056/examples/buttons.py | 4 +- ports/nrf/boards/pca10059/board.c | 2 +- ports/nrf/boards/pca10100/board.c | 2 +- ports/nrf/boards/pca10100/mpconfigboard.h | 6 +- ports/nrf/boards/pitaya_go/board.c | 2 +- ports/nrf/boards/pitaya_go/pins.c | 104 +- ports/nrf/boards/raytac_mdbt50q-db-40/board.c | 2 +- ports/nrf/boards/simmel/board.c | 2 +- ports/nrf/boards/simmel/mpconfigboard.h | 6 +- .../boards/sparkfun_nrf52840_micromod/board.c | 2 +- .../nrf/boards/sparkfun_nrf52840_mini/board.c | 2 +- .../nrf/boards/sparkfun_nrf52840_mini/pins.c | 2 +- ports/nrf/boards/teknikio_bluebird/board.c | 2 +- .../boards/teknikio_bluebird/mpconfigboard.h | 2 +- .../tinkeringtech_scoutmakes_azul/board.c | 2 +- ports/nrf/common-hal/_bleio/Adapter.c | 112 +- ports/nrf/common-hal/_bleio/Adapter.h | 12 +- ports/nrf/common-hal/_bleio/Characteristic.c | 12 +- .../common-hal/_bleio/CharacteristicBuffer.c | 22 +- ports/nrf/common-hal/_bleio/Connection.c | 72 +- ports/nrf/common-hal/_bleio/Connection.h | 4 +- ports/nrf/common-hal/_bleio/Descriptor.c | 4 +- ports/nrf/common-hal/_bleio/PacketBuffer.c | 28 +- ports/nrf/common-hal/_bleio/PacketBuffer.h | 2 +- ports/nrf/common-hal/_bleio/Service.c | 20 +- ports/nrf/common-hal/_bleio/UUID.c | 2 +- ports/nrf/common-hal/_bleio/__init__.c | 10 +- ports/nrf/common-hal/_bleio/bonding.c | 50 +- ports/nrf/common-hal/_bleio/bonding.h | 6 +- ports/nrf/common-hal/analogio/AnalogIn.c | 29 +- ports/nrf/common-hal/analogio/AnalogIn.h | 2 +- ports/nrf/common-hal/analogio/AnalogOut.c | 2 +- ports/nrf/common-hal/audiobusio/I2SOut.c | 97 +- ports/nrf/common-hal/audiobusio/PDMIn.c | 30 +- ports/nrf/common-hal/audiopwmio/PWMAudioOut.c | 74 +- ports/nrf/common-hal/busio/I2C.c | 72 +- ports/nrf/common-hal/busio/I2C.h | 2 +- ports/nrf/common-hal/busio/SPI.c | 113 +- ports/nrf/common-hal/busio/SPI.h | 2 +- ports/nrf/common-hal/busio/UART.c | 100 +- ports/nrf/common-hal/digitalio/DigitalInOut.c | 46 +- ports/nrf/common-hal/displayio/ParallelBus.c | 22 +- ports/nrf/common-hal/displayio/ParallelBus.h | 4 +- ports/nrf/common-hal/microcontroller/Pin.c | 24 +- ports/nrf/common-hal/microcontroller/Pin.h | 2 +- .../common-hal/microcontroller/Processor.c | 26 +- .../nrf/common-hal/microcontroller/__init__.c | 134 +- .../nrf/common-hal/neopixel_write/__init__.c | 81 +- ports/nrf/common-hal/nvm/ByteArray.c | 6 +- ports/nrf/common-hal/nvm/ByteArray.h | 2 +- ports/nrf/common-hal/os/__init__.c | 12 +- ports/nrf/common-hal/pulseio/PulseIn.c | 70 +- ports/nrf/common-hal/pulseio/PulseIn.h | 2 +- ports/nrf/common-hal/pulseio/PulseOut.c | 20 +- ports/nrf/common-hal/pwmio/PWMOut.c | 97 +- ports/nrf/common-hal/pwmio/PWMOut.h | 6 +- ports/nrf/common-hal/rgbmatrix/RGBMatrix.c | 6 +- ports/nrf/common-hal/rgbmatrix/RGBMatrix.h | 6 +- .../common-hal/rotaryio/IncrementalEncoder.c | 25 +- ports/nrf/common-hal/rtc/RTC.c | 5 +- ports/nrf/common-hal/supervisor/Runtime.c | 4 +- ports/nrf/common-hal/watchdog/WatchDogTimer.c | 4 +- ports/nrf/common-hal/watchdog/WatchDogTimer.h | 6 +- ports/nrf/device/nrf52/startup_nrf52.c | 106 +- ports/nrf/device/nrf52/startup_nrf52833.c | 116 +- ports/nrf/device/nrf52/startup_nrf52840.c | 120 +- ports/nrf/examples/ubluepy_eddystone.py | 28 +- ports/nrf/examples/ubluepy_scan.py | 8 +- ports/nrf/examples/ubluepy_temp.py | 11 +- ports/nrf/fatfs_port.c | 8 +- ports/nrf/freeze/test.py | 1 + ports/nrf/gccollect.c | 11 +- ports/nrf/ld_defines.c | 54 +- ports/nrf/mpconfigport.h | 34 +- ports/nrf/mphalport.h | 4 +- ports/nrf/nrfx_config.h | 2 +- ports/nrf/nrfx_glue.h | 39 +- ports/nrf/peripherals/nrf/clocks.c | 9 +- ports/nrf/peripherals/nrf/nrf52833/power.c | 6 +- ports/nrf/peripherals/nrf/nrf52840/power.c | 6 +- ports/nrf/peripherals/nrf/nvm.c | 55 +- ports/nrf/peripherals/nrf/nvm.h | 2 +- ports/nrf/peripherals/nrf/pins.h | 10 +- ports/nrf/peripherals/nrf/timers.c | 44 +- ports/nrf/peripherals/nrf/timers.h | 14 +- ports/nrf/sd_mutex.c | 8 +- ports/nrf/sd_mutex.h | 8 +- ports/nrf/supervisor/bluetooth.c | 14 +- ports/nrf/supervisor/internal_flash.c | 16 +- ports/nrf/supervisor/port.c | 62 +- ports/nrf/supervisor/qspi_flash.c | 34 +- ports/nrf/supervisor/serial.c | 12 +- ports/nrf/supervisor/usb.c | 18 +- ports/raspberrypi/audio_dma.c | 92 +- ports/raspberrypi/audio_dma.h | 36 +- ports/raspberrypi/background.c | 6 +- .../bindings/rp2pio/StateMachine.c | 28 +- .../bindings/rp2pio/StateMachine.h | 24 +- ports/raspberrypi/bindings/rp2pio/__init__.c | 2 +- .../boards/raspberry_pi_pico/board.c | 3 +- .../common-hal/analogio/AnalogIn.c | 2 +- .../common-hal/analogio/AnalogIn.h | 2 +- .../common-hal/analogio/AnalogOut.c | 2 +- .../common-hal/audiobusio/I2SOut.c | 31 +- .../raspberrypi/common-hal/audiobusio/PDMIn.c | 54 +- .../common-hal/audiopwmio/PWMAudioOut.c | 24 +- ports/raspberrypi/common-hal/busio/I2C.c | 16 +- ports/raspberrypi/common-hal/busio/I2C.h | 2 +- ports/raspberrypi/common-hal/busio/SPI.c | 26 +- ports/raspberrypi/common-hal/busio/SPI.h | 8 +- ports/raspberrypi/common-hal/busio/UART.c | 26 +- ports/raspberrypi/common-hal/busio/UART.h | 2 +- .../raspberrypi/common-hal/countio/Counter.c | 18 +- .../raspberrypi/common-hal/countio/__init__.c | 2 +- .../common-hal/digitalio/DigitalInOut.c | 34 +- .../common-hal/digitalio/DigitalInOut.h | 2 +- .../common-hal/displayio/ParallelBus.c | 12 +- .../common-hal/microcontroller/Pin.c | 16 +- .../common-hal/microcontroller/Pin.h | 2 +- .../common-hal/microcontroller/__init__.c | 2 +- .../common-hal/neopixel_write/__init__.c | 7 +- ports/raspberrypi/common-hal/nvm/ByteArray.c | 22 +- ports/raspberrypi/common-hal/nvm/ByteArray.h | 2 +- ports/raspberrypi/common-hal/os/__init__.c | 18 +- .../raspberrypi/common-hal/pulseio/PulseIn.c | 106 +- .../raspberrypi/common-hal/pulseio/PulseIn.h | 2 +- .../raspberrypi/common-hal/pulseio/PulseOut.c | 18 +- ports/raspberrypi/common-hal/pwmio/PWMOut.c | 32 +- ports/raspberrypi/common-hal/pwmio/PWMOut.h | 2 +- .../common-hal/rgbmatrix/RGBMatrix.c | 10 +- .../common-hal/rgbmatrix/RGBMatrix.h | 6 +- .../common-hal/rotaryio/IncrementalEncoder.c | 16 +- .../common-hal/rotaryio/IncrementalEncoder.h | 4 +- .../common-hal/rp2pio/StateMachine.c | 94 +- .../common-hal/rp2pio/StateMachine.h | 14 +- .../raspberrypi/common-hal/rp2pio/__init__.c | 4 +- ports/raspberrypi/common-hal/rtc/RTC.c | 38 +- .../common-hal/supervisor/Runtime.c | 4 +- .../common-hal/watchdog/WatchDogTimer.h | 6 +- ports/raspberrypi/fatfs_port.c | 8 +- ports/raspberrypi/mpconfigport.h | 4 +- ports/raspberrypi/mphalport.h | 2 +- ports/raspberrypi/peripherals/pins.c | 8 +- ports/raspberrypi/supervisor/internal_flash.c | 14 +- ports/raspberrypi/supervisor/port.c | 14 +- ports/stm/background.c | 9 +- .../stm/boards/espruino_pico/mpconfigboard.h | 2 +- ports/stm/boards/espruino_wifi/board.c | 2 +- .../stm/boards/espruino_wifi/mpconfigboard.h | 6 +- ports/stm/boards/espruino_wifi/pins.c | 60 +- .../feather_stm32f405_express/mpconfigboard.h | 4 +- ports/stm/boards/meowbit_v121/board.c | 56 +- ports/stm/boards/meowbit_v121/mpconfigboard.h | 4 +- ports/stm/boards/meowbit_v121/pins.c | 2 +- ports/stm/boards/nucleo_f746zg/board.c | 2 +- .../stm/boards/nucleo_f746zg/mpconfigboard.h | 2 +- ports/stm/boards/nucleo_f746zg/pins.c | 132 +- ports/stm/boards/nucleo_f767zi/board.c | 2 +- .../stm/boards/nucleo_f767zi/mpconfigboard.h | 2 +- ports/stm/boards/nucleo_f767zi/pins.c | 274 ++-- ports/stm/boards/nucleo_h743zi_2/board.c | 2 +- .../boards/nucleo_h743zi_2/mpconfigboard.h | 2 +- ports/stm/boards/openmv_h7/board.c | 2 +- ports/stm/boards/openmv_h7/mpconfigboard.h | 2 +- ports/stm/boards/pyb_nano_v2/mpconfigboard.h | 2 +- ports/stm/boards/pyboard_v11/board.c | 2 +- ports/stm/boards/pyboard_v11/mpconfigboard.h | 2 +- .../stm32f411ce_blackpill/mpconfigboard.h | 2 +- ports/stm/boards/stm32f411ce_blackpill/pins.c | 8 +- .../mpconfigboard.h | 2 +- .../stm32f411ce_blackpill_with_flash/pins.c | 8 +- .../stm/boards/stm32f411ve_discovery/board.c | 2 +- .../stm32f411ve_discovery/mpconfigboard.h | 6 +- ports/stm/boards/stm32f411ve_discovery/pins.c | 202 +-- .../stm/boards/stm32f412zg_discovery/board.c | 2 +- .../stm32f412zg_discovery/mpconfigboard.h | 2 +- ports/stm/boards/stm32f412zg_discovery/pins.c | 176 +-- ports/stm/boards/stm32f4_discovery/board.c | 2 +- .../boards/stm32f4_discovery/mpconfigboard.h | 2 +- ports/stm/boards/stm32f4_discovery/pins.c | 204 +-- ports/stm/boards/stm32f746g_discovery/board.c | 2 +- .../stm32f746g_discovery/mpconfigboard.h | 2 +- ports/stm/boards/stm32f746g_discovery/pins.c | 210 +-- ports/stm/boards/system_stm32f4xx.c | 925 +++++++------ ports/stm/boards/system_stm32f7xx.c | 117 +- ports/stm/boards/system_stm32h7xx.c | 380 +++--- ports/stm/boards/thunderpack_v11/board.c | 2 +- .../boards/thunderpack_v11/mpconfigboard.h | 2 +- ports/stm/boards/thunderpack_v12/board.c | 2 +- .../boards/thunderpack_v12/mpconfigboard.h | 2 +- ports/stm/common-hal/analogio/AnalogIn.c | 16 +- ports/stm/common-hal/analogio/AnalogIn.h | 2 +- ports/stm/common-hal/analogio/AnalogOut.c | 19 +- ports/stm/common-hal/analogio/AnalogOut.h | 8 +- ports/stm/common-hal/busio/I2C.c | 54 +- ports/stm/common-hal/busio/SPI.c | 102 +- ports/stm/common-hal/busio/UART.c | 129 +- ports/stm/common-hal/canio/CAN.c | 39 +- ports/stm/common-hal/canio/CAN.h | 12 +- ports/stm/common-hal/canio/Listener.c | 24 +- ports/stm/common-hal/digitalio/DigitalInOut.c | 28 +- ports/stm/common-hal/displayio/ParallelBus.c | 10 +- ports/stm/common-hal/microcontroller/Pin.c | 55 +- ports/stm/common-hal/microcontroller/Pin.h | 2 +- .../common-hal/microcontroller/Processor.c | 20 +- .../stm/common-hal/microcontroller/__init__.c | 16 +- .../stm/common-hal/neopixel_write/__init__.c | 41 +- ports/stm/common-hal/nvm/ByteArray.c | 6 +- ports/stm/common-hal/nvm/ByteArray.h | 2 +- ports/stm/common-hal/os/__init__.c | 22 +- ports/stm/common-hal/pulseio/PulseIn.c | 92 +- ports/stm/common-hal/pulseio/PulseIn.h | 4 +- ports/stm/common-hal/pulseio/PulseOut.c | 42 +- ports/stm/common-hal/pwmio/PWMOut.c | 94 +- ports/stm/common-hal/pwmio/PWMOut.h | 4 +- ports/stm/common-hal/rgbmatrix/RGBMatrix.c | 14 +- ports/stm/common-hal/rgbmatrix/RGBMatrix.h | 6 +- ports/stm/common-hal/sdioio/SDCard.c | 38 +- ports/stm/common-hal/sdioio/SDCard.h | 2 +- ports/stm/common-hal/supervisor/Runtime.c | 4 +- ports/stm/hal_conf/stm32f4xx_hal_conf.h | 18 +- ports/stm/hal_conf/stm32f7xx_hal_conf.h | 18 +- ports/stm/hal_conf/stm32h7xx_hal_conf.h | 20 +- ports/stm/mpconfigport.h | 4 +- ports/stm/mphalport.h | 2 +- ports/stm/packages/LQFP100_f4.c | 204 +-- ports/stm/packages/LQFP100_x7.c | 200 +-- ports/stm/packages/LQFP144.c | 288 ++--- ports/stm/packages/LQFP64.c | 132 +- ports/stm/packages/TFBGA216.c | 334 ++--- ports/stm/packages/UFQFPN48.c | 96 +- ports/stm/peripherals/periph.h | 36 +- ports/stm/peripherals/pins.h | 28 +- ports/stm/peripherals/stm32f4/clocks.c | 12 +- .../peripherals/stm32f4/stm32f401xe/clocks.h | 2 +- .../peripherals/stm32f4/stm32f401xe/gpio.c | 10 +- .../peripherals/stm32f4/stm32f401xe/periph.c | 18 +- .../peripherals/stm32f4/stm32f401xe/periph.h | 16 +- .../peripherals/stm32f4/stm32f401xe/pins.c | 14 +- .../peripherals/stm32f4/stm32f401xe/pins.h | 20 +- .../peripherals/stm32f4/stm32f405xx/clocks.h | 2 +- .../peripherals/stm32f4/stm32f405xx/gpio.c | 14 +- .../peripherals/stm32f4/stm32f405xx/periph.c | 24 +- .../peripherals/stm32f4/stm32f405xx/periph.h | 22 +- .../peripherals/stm32f4/stm32f405xx/pins.c | 2 +- .../peripherals/stm32f4/stm32f407xx/clocks.h | 2 +- .../peripherals/stm32f4/stm32f407xx/gpio.c | 14 +- .../peripherals/stm32f4/stm32f407xx/periph.c | 24 +- .../peripherals/stm32f4/stm32f407xx/periph.h | 22 +- .../peripherals/stm32f4/stm32f407xx/pins.c | 2 +- .../peripherals/stm32f4/stm32f411xe/clocks.h | 2 +- .../peripherals/stm32f4/stm32f411xe/gpio.c | 14 +- .../peripherals/stm32f4/stm32f411xe/periph.c | 16 +- .../peripherals/stm32f4/stm32f411xe/periph.h | 16 +- .../peripherals/stm32f4/stm32f411xe/pins.c | 14 +- .../peripherals/stm32f4/stm32f411xe/pins.h | 20 +- .../peripherals/stm32f4/stm32f412zx/clocks.h | 2 +- .../peripherals/stm32f4/stm32f412zx/gpio.c | 18 +- .../peripherals/stm32f4/stm32f412zx/periph.c | 20 +- .../peripherals/stm32f4/stm32f412zx/periph.h | 16 +- .../peripherals/stm32f4/stm32f412zx/pins.c | 8 +- .../peripherals/stm32f4/stm32f412zx/pins.h | 28 +- ports/stm/peripherals/stm32f7/clocks.c | 10 +- .../peripherals/stm32f7/stm32f746xx/gpio.c | 16 +- .../peripherals/stm32f7/stm32f746xx/periph.c | 20 +- .../peripherals/stm32f7/stm32f746xx/periph.h | 16 +- .../peripherals/stm32f7/stm32f746xx/pins.c | 2 +- .../peripherals/stm32f7/stm32f767xx/gpio.c | 12 +- .../peripherals/stm32f7/stm32f767xx/periph.c | 22 +- .../peripherals/stm32f7/stm32f767xx/periph.h | 16 +- .../peripherals/stm32f7/stm32f767xx/pins.c | 2 +- ports/stm/peripherals/stm32h7/clocks.c | 21 +- .../peripherals/stm32h7/stm32h743xx/gpio.c | 12 +- .../peripherals/stm32h7/stm32h743xx/periph.c | 20 +- .../peripherals/stm32h7/stm32h743xx/periph.h | 16 +- .../peripherals/stm32h7/stm32h743xx/pins.c | 2 +- ports/stm/peripherals/timers.c | 92 +- ports/stm/peripherals/timers.h | 22 +- ports/stm/supervisor/internal_flash.c | 92 +- ports/stm/supervisor/internal_flash.h | 34 +- ports/stm/supervisor/port.c | 71 +- ports/stm/supervisor/qspi_flash.c | 16 +- ports/stm/supervisor/serial.c | 7 +- ports/stm/supervisor/usb.c | 34 +- ports/stm/tools/parse_af_csv.py | 73 +- ports/stm/tools/parse_pins_csv.py | 6 +- ports/unix/alloc.c | 2 +- ports/unix/coverage.c | 12 +- ports/unix/file.c | 12 +- ports/unix/gccollect.c | 38 +- ports/unix/input.c | 8 +- ports/unix/main.c | 89 +- ports/unix/modffi.c | 88 +- ports/unix/modjni.c | 54 +- ports/unix/modmachine.c | 2 +- ports/unix/modos.c | 2 +- ports/unix/modtermios.c | 6 +- ports/unix/modtime.c | 24 +- ports/unix/moduos_vfs.c | 2 +- ports/unix/moduselect.c | 4 +- ports/unix/modusocket.c | 42 +- ports/unix/mpconfigport.h | 4 +- ports/unix/mphalport.h | 10 +- ports/unix/mpthreadport.c | 10 +- ports/unix/unix_mphal.c | 28 +- py/argcheck.c | 54 +- py/asmarm.c | 24 +- py/asmbase.c | 6 +- py/asmbase.h | 4 +- py/asmthumb.c | 4 +- py/asmthumb.h | 80 +- py/asmx64.c | 36 +- py/asmx64.h | 42 +- py/asmx86.c | 45 +- py/asmx86.h | 34 +- py/asmxtensa.c | 2 +- py/bc.c | 30 +- py/bc.h | 6 +- py/binary.c | 234 ++-- py/builtinevex.c | 12 +- py/builtinhelp.c | 32 +- py/builtinimport.c | 104 +- py/circuitpy_mpconfig.h | 22 +- py/compile.c | 439 ++++--- py/emit.h | 2 +- py/emitbc.c | 50 +- py/emitglue.c | 20 +- py/emitinlinethumb.c | 70 +- py/emitinlinextensa.c | 6 +- py/emitnative.c | 112 +- py/enum.c | 6 +- py/enum.h | 20 +- py/formatfloat.c | 17 +- py/frozenmod.c | 2 +- py/frozenmod.h | 4 +- py/gc.c | 165 +-- py/gc.h | 6 +- py/gc_long_lived.c | 26 +- py/genlast.py | 28 +- py/lexer.c | 108 +- py/lexer.h | 14 +- py/makemoduledefs.py | 48 +- py/makeqstrdata.py | 213 +-- py/makeqstrdefs.py | 89 +- py/makeversionhdr.py | 39 +- py/malloc.c | 30 +- py/map.c | 4 +- py/misc.h | 67 +- py/modarray.c | 2 +- py/modbuiltins.c | 50 +- py/modcmath.c | 36 +- py/modcollections.c | 2 +- py/modgc.c | 8 +- py/modio.c | 12 +- py/modmath.c | 32 +- py/modmicropython.c | 30 +- py/modstruct.c | 10 +- py/modsys.c | 8 +- py/modthread.c | 10 +- py/moduerrno.c | 70 +- py/mpconfig.h | 26 +- py/mperrno.h | 2 +- py/mpprint.c | 59 +- py/mpprint.h | 4 +- py/mpstate.h | 4 +- py/mpthread.h | 2 +- py/mpz.c | 130 +- py/mpz.h | 23 +- py/nativeglue.c | 26 +- py/nlr.c | 2 +- py/nlr.h | 8 +- py/nlrthumb.c | 164 +-- py/nlrx64.c | 104 +- py/nlrx86.c | 58 +- py/nlrxtensa.c | 58 +- py/obj.c | 118 +- py/obj.h | 150 ++- py/objarray.c | 76 +- py/objattrtuple.c | 4 +- py/objboundmeth.c | 8 +- py/objcell.c | 4 +- py/objclosure.c | 4 +- py/objcomplex.c | 32 +- py/objdeque.c | 2 +- py/objdict.c | 21 +- py/objenumerate.c | 8 +- py/objexcept.c | 112 +- py/objexcept.h | 16 +- py/objfloat.c | 78 +- py/objfun.c | 26 +- py/objgenerator.c | 14 +- py/objgetitemiter.c | 4 +- py/objint.c | 58 +- py/objint.h | 10 +- py/objint_longlong.c | 24 +- py/objint_mpz.c | 90 +- py/objlist.c | 68 +- py/objmodule.c | 158 +-- py/objnamedtuple.c | 36 +- py/objobject.c | 4 +- py/objproperty.c | 8 +- py/objrange.c | 21 +- py/objset.c | 31 +- py/objslice.c | 10 +- py/objstr.c | 275 ++-- py/objstr.h | 16 +- py/objstringio.c | 8 +- py/objstrunicode.c | 23 +- py/objtuple.c | 17 +- py/objtuple.h | 2 +- py/objtype.c | 83 +- py/parse.c | 122 +- py/parse.h | 2 +- py/parsenum.c | 58 +- py/parsenumbase.c | 4 +- py/persistentcode.c | 36 +- py/proto.c | 6 +- py/proto.h | 4 +- py/pystack.c | 2 +- py/pystack.h | 14 +- py/qstr.c | 18 +- py/qstr.h | 6 +- py/qstrdefs.h | 2 + py/reader.c | 10 +- py/reload.c | 6 +- py/reload.h | 4 +- py/repl.c | 35 +- py/ringbuf.c | 14 +- py/ringbuf.h | 4 +- py/runtime.c | 190 +-- py/runtime.h | 20 +- py/runtime0.h | 16 +- py/scope.c | 2 +- py/sequence.c | 12 +- py/showbc.c | 42 +- py/stackctrl.c | 16 +- py/stackctrl.h | 2 +- py/stream.c | 14 +- py/stream.h | 8 +- py/unicode.c | 4 +- py/vm.c | 554 ++++---- py/vmentrytable.h | 156 +-- py/vstr.c | 18 +- shared-bindings/_bleio/Adapter.c | 16 +- shared-bindings/_bleio/Adapter.h | 6 +- shared-bindings/_bleio/Address.c | 8 +- shared-bindings/_bleio/Attribute.c | 2 +- shared-bindings/_bleio/Characteristic.c | 20 +- shared-bindings/_bleio/Characteristic.h | 2 +- shared-bindings/_bleio/CharacteristicBuffer.c | 2 +- shared-bindings/_bleio/Connection.c | 6 +- shared-bindings/_bleio/Descriptor.c | 18 +- shared-bindings/_bleio/Descriptor.h | 2 +- shared-bindings/_bleio/PacketBuffer.c | 2 +- shared-bindings/_bleio/PacketBuffer.h | 2 +- shared-bindings/_bleio/ScanEntry.c | 2 +- shared-bindings/_bleio/ScanEntry.h | 2 +- shared-bindings/_bleio/Service.c | 2 +- shared-bindings/_bleio/Service.h | 4 +- shared-bindings/_bleio/UUID.c | 56 +- shared-bindings/_bleio/UUID.h | 2 +- shared-bindings/_bleio/__init__.c | 28 +- shared-bindings/_bleio/__init__.h | 26 +- shared-bindings/_eve/__init__.c | 150 +-- shared-bindings/_pew/PewPew.c | 10 +- shared-bindings/_pew/__init__.c | 4 +- shared-bindings/_pixelbuf/PixelBuf.c | 36 +- shared-bindings/_pixelbuf/PixelBuf.h | 6 +- shared-bindings/_pixelbuf/__init__.c | 6 +- shared-bindings/_pixelbuf/__init__.h | 2 +- shared-bindings/_stage/Layer.c | 8 +- shared-bindings/_stage/Text.c | 4 +- shared-bindings/_stage/__init__.c | 4 +- .../adafruit_bus_device/I2CDevice.c | 12 +- .../adafruit_bus_device/I2CDevice.h | 2 +- .../adafruit_bus_device/SPIDevice.c | 10 +- .../adafruit_bus_device/__init__.c | 6 +- shared-bindings/aesio/__init__.h | 36 +- shared-bindings/aesio/aes.c | 284 ++-- shared-bindings/alarm/SleepMemory.c | 23 +- shared-bindings/alarm/SleepMemory.h | 4 +- shared-bindings/alarm/__init__.c | 10 +- shared-bindings/alarm/pin/PinAlarm.c | 2 +- shared-bindings/alarm/time/TimeAlarm.c | 10 +- shared-bindings/alarm/touch/TouchAlarm.c | 2 +- shared-bindings/analogio/AnalogIn.c | 10 +- shared-bindings/analogio/AnalogIn.h | 10 +- shared-bindings/analogio/AnalogOut.c | 20 +- shared-bindings/analogio/AnalogOut.h | 2 +- shared-bindings/analogio/__init__.c | 2 +- shared-bindings/audiobusio/I2SOut.c | 12 +- shared-bindings/audiobusio/I2SOut.h | 20 +- shared-bindings/audiobusio/PDMIn.c | 14 +- shared-bindings/audiobusio/PDMIn.h | 16 +- shared-bindings/audiobusio/__init__.c | 2 +- shared-bindings/audiocore/RawSample.c | 8 +- shared-bindings/audiocore/RawSample.h | 16 +- shared-bindings/audiocore/WaveFile.c | 4 +- shared-bindings/audiocore/WaveFile.h | 16 +- shared-bindings/audiocore/__init__.c | 4 +- shared-bindings/audioio/AudioOut.c | 2 +- shared-bindings/audioio/AudioOut.h | 20 +- shared-bindings/audioio/__init__.c | 2 +- shared-bindings/audiomixer/Mixer.c | 10 +- shared-bindings/audiomixer/Mixer.h | 26 +- shared-bindings/audiomixer/MixerVoice.c | 4 +- shared-bindings/audiomixer/MixerVoice.h | 12 +- shared-bindings/audiomixer/__init__.c | 2 +- shared-bindings/audiomp3/MP3Decoder.c | 4 +- shared-bindings/audiomp3/MP3Decoder.h | 20 +- shared-bindings/audiomp3/__init__.c | 2 +- shared-bindings/audiopwmio/PWMAudioOut.c | 2 +- shared-bindings/audiopwmio/PWMAudioOut.h | 20 +- shared-bindings/audiopwmio/__init__.c | 2 +- shared-bindings/bitbangio/I2C.c | 22 +- shared-bindings/bitbangio/I2C.h | 18 +- shared-bindings/bitbangio/OneWire.c | 4 +- shared-bindings/bitbangio/OneWire.h | 14 +- shared-bindings/bitbangio/SPI.c | 20 +- shared-bindings/bitbangio/SPI.h | 4 +- shared-bindings/bitbangio/__init__.c | 2 +- shared-bindings/bitmaptools/__init__.c | 78 +- shared-bindings/bitmaptools/__init__.h | 28 +- shared-bindings/bitops/__init__.c | 2 +- shared-bindings/board/__init__.c | 2 +- shared-bindings/busio/I2C.c | 28 +- shared-bindings/busio/I2C.h | 14 +- shared-bindings/busio/OneWire.c | 4 +- shared-bindings/busio/OneWire.h | 14 +- shared-bindings/busio/SPI.c | 28 +- shared-bindings/busio/SPI.h | 10 +- shared-bindings/busio/UART.c | 20 +- shared-bindings/busio/UART.h | 10 +- shared-bindings/busio/__init__.c | 2 +- shared-bindings/camera/Camera.c | 8 +- shared-bindings/camera/__init__.c | 2 +- shared-bindings/canio/CAN.c | 6 +- shared-bindings/canio/Listener.c | 2 +- shared-bindings/canio/Match.c | 4 +- shared-bindings/canio/Message.c | 4 +- .../canio/RemoteTransmissionRequest.c | 2 +- shared-bindings/canio/__init__.c | 2 +- shared-bindings/countio/Counter.c | 16 +- shared-bindings/countio/Counter.h | 14 +- shared-bindings/countio/__init__.c | 2 +- shared-bindings/digitalio/DigitalInOut.c | 4 +- shared-bindings/digitalio/DigitalInOut.h | 24 +- shared-bindings/digitalio/__init__.c | 2 +- shared-bindings/displayio/Bitmap.c | 42 +- shared-bindings/displayio/Bitmap.h | 8 +- shared-bindings/displayio/ColorConverter.c | 2 +- shared-bindings/displayio/ColorConverter.h | 12 +- shared-bindings/displayio/Display.c | 60 +- shared-bindings/displayio/Display.h | 36 +- shared-bindings/displayio/EPaperDisplay.c | 11 +- shared-bindings/displayio/EPaperDisplay.h | 32 +- shared-bindings/displayio/FourWire.c | 6 +- shared-bindings/displayio/FourWire.h | 8 +- shared-bindings/displayio/Group.c | 21 +- shared-bindings/displayio/Group.h | 34 +- shared-bindings/displayio/I2CDisplay.c | 6 +- shared-bindings/displayio/I2CDisplay.h | 6 +- shared-bindings/displayio/OnDiskBitmap.c | 2 +- shared-bindings/displayio/OnDiskBitmap.h | 2 +- shared-bindings/displayio/Palette.c | 10 +- shared-bindings/displayio/Palette.h | 12 +- shared-bindings/displayio/ParallelBus.c | 6 +- shared-bindings/displayio/ParallelBus.h | 8 +- shared-bindings/displayio/Shape.c | 4 +- shared-bindings/displayio/Shape.h | 2 +- shared-bindings/displayio/TileGrid.c | 14 +- shared-bindings/displayio/TileGrid.h | 10 +- shared-bindings/displayio/__init__.c | 2 +- shared-bindings/dualbank/__init__.c | 2 +- shared-bindings/fontio/BuiltinFont.c | 2 +- shared-bindings/fontio/__init__.c | 2 +- .../framebufferio/FramebufferDisplay.c | 38 +- .../framebufferio/FramebufferDisplay.h | 36 +- shared-bindings/framebufferio/__init__.c | 2 +- shared-bindings/frequencyio/FrequencyIn.c | 8 +- shared-bindings/frequencyio/__init__.c | 2 +- shared-bindings/gamepad/GamePad.c | 8 +- shared-bindings/gamepad/__init__.c | 4 +- shared-bindings/gamepadshift/GamePadShift.c | 12 +- shared-bindings/gamepadshift/GamePadShift.h | 6 +- shared-bindings/gamepadshift/__init__.c | 2 +- shared-bindings/gnss/GNSS.c | 8 +- shared-bindings/gnss/__init__.c | 2 +- shared-bindings/i2cperipheral/I2CPeripheral.c | 22 +- shared-bindings/i2cperipheral/I2CPeripheral.h | 6 +- shared-bindings/i2cperipheral/__init__.c | 4 +- shared-bindings/ipaddress/IPv4Address.c | 14 +- shared-bindings/ipaddress/IPv4Address.h | 4 +- shared-bindings/ipaddress/__init__.c | 10 +- shared-bindings/ipaddress/__init__.h | 2 +- shared-bindings/math/__init__.c | 34 +- .../memorymonitor/AllocationAlarm.c | 2 +- .../memorymonitor/AllocationAlarm.h | 8 +- .../memorymonitor/AllocationSize.c | 11 +- .../memorymonitor/AllocationSize.h | 14 +- shared-bindings/memorymonitor/__init__.c | 4 +- shared-bindings/memorymonitor/__init__.h | 18 +- shared-bindings/microcontroller/Pin.c | 12 +- shared-bindings/microcontroller/Pin.h | 12 +- shared-bindings/microcontroller/Processor.c | 4 +- shared-bindings/microcontroller/RunMode.c | 2 +- shared-bindings/microcontroller/__init__.c | 8 +- shared-bindings/msgpack/ExtType.c | 2 +- shared-bindings/msgpack/__init__.c | 4 +- shared-bindings/multiterminal/__init__.c | 2 +- shared-bindings/neopixel_write/__init__.c | 4 +- shared-bindings/neopixel_write/__init__.h | 2 +- shared-bindings/network/__init__.c | 2 +- shared-bindings/nvm/ByteArray.c | 23 +- shared-bindings/nvm/ByteArray.h | 4 +- shared-bindings/nvm/__init__.c | 2 +- shared-bindings/os/__init__.c | 6 +- shared-bindings/os/__init__.h | 18 +- shared-bindings/ps2io/Ps2.c | 15 +- shared-bindings/ps2io/Ps2.h | 16 +- shared-bindings/ps2io/__init__.c | 2 +- shared-bindings/pulseio/PulseIn.c | 13 +- shared-bindings/pulseio/PulseIn.h | 24 +- shared-bindings/pulseio/PulseOut.c | 6 +- shared-bindings/pulseio/PulseOut.h | 18 +- shared-bindings/pulseio/__init__.c | 2 +- shared-bindings/pwmio/PWMOut.c | 10 +- shared-bindings/pwmio/PWMOut.h | 18 +- shared-bindings/pwmio/__init__.c | 2 +- shared-bindings/random/__init__.c | 4 +- shared-bindings/rgbmatrix/RGBMatrix.c | 46 +- shared-bindings/rgbmatrix/RGBMatrix.h | 18 +- shared-bindings/rgbmatrix/__init__.c | 2 +- shared-bindings/rotaryio/IncrementalEncoder.c | 6 +- shared-bindings/rotaryio/IncrementalEncoder.h | 12 +- shared-bindings/rotaryio/__init__.c | 2 +- shared-bindings/rtc/RTC.c | 2 +- shared-bindings/rtc/__init__.c | 2 +- shared-bindings/sdcardio/SDCard.c | 12 +- shared-bindings/sdcardio/__init__.c | 2 +- shared-bindings/sdioio/SDCard.c | 20 +- shared-bindings/sdioio/SDCard.h | 14 +- shared-bindings/sdioio/__init__.c | 2 +- .../sharpdisplay/SharpMemoryFramebuffer.c | 10 +- shared-bindings/sharpdisplay/__init__.c | 2 +- shared-bindings/socket/__init__.c | 16 +- shared-bindings/socketpool/Socket.c | 14 +- shared-bindings/socketpool/Socket.h | 30 +- shared-bindings/socketpool/SocketPool.c | 4 +- shared-bindings/socketpool/SocketPool.h | 8 +- shared-bindings/socketpool/__init__.c | 2 +- shared-bindings/ssl/SSLContext.c | 4 +- shared-bindings/ssl/SSLContext.h | 6 +- shared-bindings/ssl/SSLSocket.c | 10 +- shared-bindings/ssl/SSLSocket.h | 20 +- shared-bindings/ssl/__init__.c | 2 +- shared-bindings/ssl/__init__.h | 2 +- shared-bindings/storage/__init__.c | 2 +- shared-bindings/storage/__init__.h | 8 +- shared-bindings/struct/__init__.c | 6 +- shared-bindings/struct/__init__.h | 4 +- shared-bindings/supervisor/Runtime.c | 6 +- shared-bindings/supervisor/Runtime.h | 6 +- shared-bindings/supervisor/__init__.c | 18 +- shared-bindings/supervisor/__init__.h | 2 +- shared-bindings/terminalio/Terminal.c | 2 +- shared-bindings/terminalio/Terminal.h | 4 +- shared-bindings/terminalio/__init__.c | 4 +- shared-bindings/time/__init__.c | 16 +- shared-bindings/touchio/TouchIn.c | 6 +- shared-bindings/touchio/TouchIn.h | 6 +- shared-bindings/touchio/__init__.c | 2 +- shared-bindings/uheap/__init__.c | 2 +- shared-bindings/usb_cdc/Serial.c | 2 +- shared-bindings/usb_cdc/__init__.c | 2 +- shared-bindings/usb_hid/Device.c | 4 +- shared-bindings/usb_hid/Device.h | 2 +- shared-bindings/usb_hid/__init__.c | 2 +- shared-bindings/usb_midi/PortIn.c | 2 +- shared-bindings/usb_midi/PortOut.c | 2 +- shared-bindings/usb_midi/PortOut.h | 2 +- shared-bindings/usb_midi/__init__.c | 2 +- shared-bindings/ustack/__init__.c | 2 +- shared-bindings/vectorio/Circle.c | 2 +- shared-bindings/vectorio/Polygon.c | 2 +- shared-bindings/vectorio/Rectangle.c | 2 +- shared-bindings/vectorio/VectorShape.c | 4 +- shared-bindings/vectorio/VectorShape.h | 4 +- shared-bindings/vectorio/__init__.c | 2 +- shared-bindings/watchdog/WatchDogMode.c | 5 +- shared-bindings/watchdog/WatchDogTimer.c | 2 +- shared-bindings/watchdog/__init__.c | 4 +- shared-bindings/wifi/Radio.c | 4 +- shared-bindings/wifi/Radio.h | 2 +- shared-bindings/wifi/__init__.c | 2 +- shared-bindings/wiznet/__init__.c | 6 +- shared-bindings/wiznet/wiznet5k.c | 14 +- shared-module/_bleio/Characteristic.h | 18 +- shared-module/_bleio/ScanEntry.c | 6 +- shared-module/_bleio/ScanEntry.h | 2 +- shared-module/_bleio/ScanResults.c | 36 +- shared-module/_bleio/ScanResults.h | 28 +- shared-module/_eve/__init__.c | 22 +- shared-module/_pixelbuf/PixelBuf.c | 55 +- shared-module/_stage/Layer.c | 2 +- shared-module/_stage/Text.c | 2 +- shared-module/_stage/__init__.c | 20 +- shared-module/_stage/__init__.h | 8 +- shared-module/adafruit_bus_device/I2CDevice.c | 5 +- shared-module/adafruit_bus_device/SPIDevice.c | 7 +- shared-module/aesio/__init__.c | 74 +- shared-module/aesio/aes.c | 702 +++++----- shared-module/aesio/aes.h | 50 +- shared-module/audiocore/RawSample.c | 50 +- shared-module/audiocore/RawSample.h | 24 +- shared-module/audiocore/WaveFile.c | 58 +- shared-module/audiocore/WaveFile.h | 28 +- shared-module/audiocore/__init__.c | 30 +- shared-module/audiocore/__init__.h | 22 +- shared-module/audiomixer/Mixer.c | 106 +- shared-module/audiomixer/Mixer.h | 26 +- shared-module/audiomixer/MixerVoice.c | 24 +- shared-module/audiomixer/MixerVoice.h | 6 +- shared-module/audiomp3/MP3Decoder.c | 113 +- shared-module/audiomp3/MP3Decoder.h | 30 +- shared-module/bitbangio/I2C.c | 12 +- shared-module/bitbangio/OneWire.c | 16 +- shared-module/bitbangio/SPI.c | 8 +- shared-module/bitbangio/SPI.h | 10 +- shared-module/bitmaptools/__init__.c | 146 ++- shared-module/bitops/__init__.c | 120 +- shared-module/board/__init__.c | 60 +- shared-module/busio/I2C.c | 6 +- shared-module/busio/OneWire.c | 16 +- shared-module/canio/Message.c | 24 +- shared-module/canio/Message.h | 4 +- .../canio/RemoteTransmissionRequest.c | 21 +- shared-module/displayio/Bitmap.c | 54 +- shared-module/displayio/Bitmap.h | 4 +- shared-module/displayio/ColorConverter.c | 47 +- shared-module/displayio/ColorConverter.h | 6 +- shared-module/displayio/Display.c | 84 +- shared-module/displayio/Display.h | 8 +- shared-module/displayio/EPaperDisplay.c | 74 +- shared-module/displayio/EPaperDisplay.h | 10 +- shared-module/displayio/FourWire.c | 22 +- shared-module/displayio/FourWire.h | 2 +- shared-module/displayio/Group.c | 88 +- shared-module/displayio/Group.h | 20 +- shared-module/displayio/I2CDisplay.c | 18 +- shared-module/displayio/I2CDisplay.h | 2 +- shared-module/displayio/OnDiskBitmap.c | 26 +- shared-module/displayio/OnDiskBitmap.h | 4 +- shared-module/displayio/Palette.c | 18 +- shared-module/displayio/Palette.h | 4 +- shared-module/displayio/Shape.c | 10 +- shared-module/displayio/Shape.h | 4 +- shared-module/displayio/TileGrid.c | 72 +- shared-module/displayio/TileGrid.h | 37 +- shared-module/displayio/__init__.c | 134 +- shared-module/displayio/__init__.h | 12 +- shared-module/displayio/area.h | 36 +- shared-module/displayio/display_core.c | 44 +- shared-module/displayio/display_core.h | 42 +- shared-module/fontio/BuiltinFont.c | 4 +- shared-module/fontio/BuiltinFont.h | 4 +- .../framebufferio/FramebufferDisplay.c | 70 +- .../framebufferio/FramebufferDisplay.h | 10 +- shared-module/gamepad/GamePad.c | 2 +- shared-module/gamepad/GamePad.h | 2 +- shared-module/gamepad/__init__.c | 4 +- shared-module/gamepadshift/GamePadShift.c | 10 +- shared-module/gamepadshift/GamePadShift.h | 6 +- shared-module/gamepadshift/__init__.c | 2 +- shared-module/ipaddress/IPv4Address.c | 4 +- shared-module/ipaddress/__init__.c | 4 +- shared-module/memorymonitor/AllocationAlarm.c | 14 +- shared-module/memorymonitor/AllocationAlarm.h | 4 +- shared-module/memorymonitor/AllocationSize.c | 18 +- shared-module/memorymonitor/AllocationSize.h | 4 +- shared-module/msgpack/__init__.c | 93 +- shared-module/network/__init__.c | 18 +- shared-module/os/__init__.c | 24 +- shared-module/random/__init__.c | 21 +- shared-module/rgbmatrix/RGBMatrix.c | 48 +- shared-module/rgbmatrix/allocator.h | 2 +- shared-module/sdcardio/SDCard.c | 32 +- .../sharpdisplay/SharpMemoryFramebuffer.c | 21 +- .../sharpdisplay/SharpMemoryFramebuffer.h | 6 +- shared-module/storage/__init__.c | 8 +- shared-module/struct/__init__.c | 88 +- shared-module/terminalio/Terminal.c | 6 +- shared-module/terminalio/Terminal.h | 4 +- shared-module/touchio/TouchIn.c | 14 +- shared-module/uheap/__init__.c | 28 +- shared-module/usb_cdc/__init__.c | 3 +- shared-module/usb_hid/Device.c | 24 +- shared-module/usb_hid/Device.h | 8 +- shared-module/usb_midi/__init__.c | 10 +- shared-module/ustack/__init__.c | 7 +- shared-module/vectorio/Circle.c | 14 +- shared-module/vectorio/Polygon.c | 64 +- shared-module/vectorio/VectorShape.c | 44 +- shared-module/vectorio/VectorShape.h | 2 +- shared-module/wiznet/wiznet5k.c | 38 +- supervisor/linker.h | 6 +- supervisor/memory.h | 12 +- supervisor/port.h | 2 +- supervisor/serial.h | 6 +- supervisor/shared/background_callback.c | 17 +- supervisor/shared/bluetooth.c | 108 +- supervisor/shared/board.c | 2 +- supervisor/shared/board.h | 2 +- supervisor/shared/display.c | 26 +- supervisor/shared/external_flash/devices.h | 994 +++++++------- .../shared/external_flash/external_flash.c | 86 +- .../external_flash_root_pointers.h | 2 +- supervisor/shared/external_flash/qspi_flash.c | 2 +- supervisor/shared/external_flash/qspi_flash.h | 2 +- supervisor/shared/external_flash/spi_flash.c | 21 +- supervisor/shared/filesystem.c | 8 +- supervisor/shared/flash.c | 2 +- supervisor/shared/memory.c | 132 +- supervisor/shared/micropython.c | 2 +- supervisor/shared/rgb_led_colors.h | 2 +- supervisor/shared/rgb_led_status.c | 278 ++-- supervisor/shared/rgb_led_status.h | 10 +- supervisor/shared/safe_mode.c | 18 +- supervisor/shared/safe_mode.h | 30 +- supervisor/shared/serial.c | 68 +- supervisor/shared/stack.c | 10 +- supervisor/shared/stack.h | 2 +- supervisor/shared/tick.c | 12 +- supervisor/shared/translate.c | 28 +- supervisor/shared/translate.h | 8 +- supervisor/shared/usb/tusb_config.h | 20 +- supervisor/shared/usb/usb.c | 113 +- supervisor/shared/usb/usb_desc.c | 14 +- supervisor/shared/usb/usb_msc_flash.c | 68 +- supervisor/spi_flash_api.h | 12 +- supervisor/stub/filesystem.c | 6 +- supervisor/stub/safe_mode.c | 4 +- supervisor/stub/serial.c | 4 +- supervisor/stub/stack.c | 2 +- tests/bench/arrayop-1-list_inplace.py | 4 +- tests/bench/arrayop-2-list_map.py | 4 +- tests/bench/arrayop-3-bytearray_inplace.py | 4 +- tests/bench/arrayop-4-bytearray_map.py | 4 +- tests/bench/bench.py | 1 + tests/bench/bytealloc-1-bytes_n.py | 2 + tests/bench/bytealloc-2-repeat.py | 2 + tests/bench/bytebuf-1-inplace.py | 4 +- tests/bench/bytebuf-2-join_map_bytes.py | 6 +- tests/bench/bytebuf-3-bytarray_map.py | 4 +- tests/bench/from_iter-1-list_bound.py | 4 +- tests/bench/from_iter-2-list_unbound.py | 4 +- tests/bench/from_iter-3-tuple_bound.py | 4 +- tests/bench/from_iter-4-tuple_unbound.py | 4 +- tests/bench/from_iter-5-bytes_bound.py | 4 +- tests/bench/from_iter-6-bytes_unbound.py | 4 +- tests/bench/from_iter-7-bytearray_bound.py | 4 +- tests/bench/from_iter-8-bytearray_unbound.py | 4 +- tests/bench/func_args-1.1-pos_1.py | 3 + tests/bench/func_args-1.2-pos_3.py | 3 + tests/bench/func_args-2-pos_default_2_of_3.py | 3 + tests/bench/func_args-3.1-kw_1.py | 3 + tests/bench/func_args-3.2-kw_3.py | 3 + tests/bench/func_builtin-1-enum_pos.py | 4 +- tests/bench/func_builtin-2-enum_kw.py | 4 +- tests/bench/funcall-1-inline.py | 2 + tests/bench/funcall-2-funcall.py | 3 + tests/bench/funcall-3-funcall-local.py | 3 + tests/bench/loop_count-1-range.py | 2 + tests/bench/loop_count-2-range_iter.py | 2 + tests/bench/loop_count-3-while_up.py | 2 + tests/bench/loop_count-4-while_down_gt.py | 2 + tests/bench/loop_count-5-while_down_ne.py | 2 + .../loop_count-5.1-while_down_ne_localvar.py | 2 + tests/bench/var-1-constant.py | 2 + tests/bench/var-2-global.py | 2 + tests/bench/var-3-local.py | 1 + tests/bench/var-4-arg.py | 3 +- tests/bench/var-5-class-attr.py | 3 + tests/bench/var-6-instance-attr.py | 4 +- tests/bench/var-6.1-instance-attr-5.py | 4 +- tests/bench/var-7-instance-meth.py | 4 +- tests/bench/var-8-namedtuple-1st.py | 2 + tests/bench/var-8.1-namedtuple-5th.py | 2 + .../audiobusio/i2s_sample_loop.py | 3 +- .../audiobusio/pdmin_rms.py | 7 +- .../audiopwmio/single_buffer_loop.py | 7 +- tests/circuitpython-manual/busio/uart_echo.py | 6 +- .../socketpool/client/cpy-client.py | 4 +- .../socketpool/client/host-server.py | 2 +- .../socketpool/datagram/ntp.py | 2 +- .../socketpool/server/cpy-server.py | 10 +- .../socketpool/server/host-client.py | 8 +- tests/circuitpython/nvm_not_present.py | 3 +- tests/circuitpython/nvm_present.py | 8 +- tests/cmdline/cmd_parsetree.py | 8 +- tests/cmdline/cmd_showbc.py | 1 + tests/cpydiff/core_class_delnotimpl.py | 6 +- tests/cpydiff/core_class_mro.py | 4 + tests/cpydiff/core_class_supermultiple.py | 7 +- tests/cpydiff/core_function_userattr.py | 3 + tests/cpydiff/core_generator_noexit.py | 10 +- tests/cpydiff/core_import_prereg.py | 3 +- tests/cpydiff/core_import_split_ns_pkgs.py | 1 + tests/cpydiff/core_locals.py | 3 + tests/cpydiff/core_locals_eval.py | 2 + tests/cpydiff/modules/foo.py | 2 +- tests/cpydiff/modules_array_containment.py | 3 +- tests/cpydiff/modules_array_deletion.py | 3 +- tests/cpydiff/modules_array_subscrstep.py | 3 +- tests/cpydiff/modules_deque.py | 1 + tests/cpydiff/modules_json_nonserializable.py | 5 +- tests/cpydiff/modules_struct_fewargs.py | 7 +- tests/cpydiff/modules_struct_manyargs.py | 7 +- tests/cpydiff/modules_sys_stdassign.py | 1 + tests/cpydiff/syntax_spaces.py | 12 +- tests/cpydiff/types_bytes_keywords.py | 2 +- tests/cpydiff/types_bytes_subscrstep.py | 2 +- tests/cpydiff/types_exception_subclassinit.py | 3 + tests/cpydiff/types_float_rounding.py | 2 +- tests/cpydiff/types_int_subclassconv.py | 5 +- tests/cpydiff/types_str_endswith.py | 2 +- tests/cpydiff/types_str_formatsubscr.py | 2 +- tests/cpydiff/types_str_keywords.py | 2 +- tests/cpydiff/types_str_ljust_rjust.py | 2 +- tests/cpydiff/types_str_rsplitnone.py | 2 +- tests/cpydiff/types_str_subclassequality.py | 7 +- tests/cpydiff/types_str_subscrstep.py | 2 +- tests/extmod/btree1.py | 2 +- tests/extmod/framebuf1.py | 26 +- tests/extmod/framebuf16.py | 26 +- tests/extmod/framebuf2.py | 4 +- tests/extmod/framebuf4.py | 38 +- tests/extmod/framebuf8.py | 6 +- tests/extmod/framebuf_subclass.py | 4 +- tests/extmod/machine_pinbase.py | 2 +- tests/extmod/machine_pulse.py | 2 - tests/extmod/machine_signal.py | 1 + tests/extmod/time_ms_us.py | 1 + tests/extmod/ubinascii_a2b_base64.py | 44 +- tests/extmod/ubinascii_b2a_base64.py | 26 +- tests/extmod/ubinascii_crc32.py | 14 +- tests/extmod/ubinascii_hexlify.py | 10 +- tests/extmod/ubinascii_micropython.py | 4 +- tests/extmod/ubinascii_unhexlify.py | 18 +- tests/extmod/uctypes_32bit_intbig.py | 12 +- tests/extmod/uctypes_array_assign_le.py | 6 +- .../extmod/uctypes_array_assign_native_le.py | 5 +- .../uctypes_array_assign_native_le_intbig.py | 5 +- tests/extmod/uctypes_byteat.py | 2 +- tests/extmod/uctypes_error.py | 12 +- tests/extmod/uctypes_le.py | 19 +- tests/extmod/uctypes_le_float.py | 8 +- tests/extmod/uctypes_native_float.py | 9 +- tests/extmod/uctypes_native_le.py | 20 +- tests/extmod/uctypes_print.py | 4 +- tests/extmod/uctypes_ptr_le.py | 3 +- tests/extmod/uctypes_ptr_native_le.py | 3 +- tests/extmod/uctypes_sizeof.py | 11 +- tests/extmod/uctypes_sizeof_float.py | 4 +- tests/extmod/uctypes_sizeof_native.py | 28 +- tests/extmod/uhashlib_sha1.py | 8 +- tests/extmod/uhashlib_sha256.py | 18 +- tests/extmod/uheapq1.py | 4 +- tests/extmod/ujson_dump.py | 8 +- tests/extmod/ujson_dump_iobase.py | 11 +- tests/extmod/ujson_dumps.py | 10 +- tests/extmod/ujson_dumps_extra.py | 2 +- tests/extmod/ujson_load.py | 4 +- tests/extmod/ujson_load_readinto.py | 8 +- tests/extmod/ujson_loads.py | 44 +- tests/extmod/ujson_loads_float.py | 16 +- tests/extmod/umsgpack_pack.py | 8 +- tests/extmod/urandom_basic.py | 2 +- tests/extmod/urandom_extra.py | 24 +- tests/extmod/ure1.py | 18 +- tests/extmod/ure_debug.py | 2 +- tests/extmod/ure_error.py | 18 +- tests/extmod/ure_group.py | 12 +- tests/extmod/ure_groups.py | 12 +- tests/extmod/ure_namedclass.py | 12 +- tests/extmod/ure_span.py | 13 +- tests/extmod/ure_split_notimpl.py | 4 +- tests/extmod/ure_sub.py | 35 +- tests/extmod/ure_sub_unmatched.py | 6 +- tests/extmod/ussl_basic.py | 16 +- tests/extmod/utimeq1.py | 14 +- tests/extmod/uzlib_decompio.py | 6 +- tests/extmod/uzlib_decompio_gz.py | 26 +- tests/extmod/uzlib_decompress.py | 37 +- tests/extmod/vfs_basic.py | 127 +- tests/extmod/vfs_fat_fileio1.py | 44 +- tests/extmod/vfs_fat_fileio2.py | 12 +- tests/extmod/vfs_fat_more.py | 74 +- tests/extmod/vfs_fat_oldproto.py | 5 +- tests/extmod/vfs_fat_ramdisk.py | 12 +- tests/extmod/vfs_userfs.py | 28 +- tests/extmod/websocket_basic.py | 16 +- tests/feature_check/byteorder.py | 1 + tests/feature_check/coverage.py | 4 +- tests/feature_check/float.py | 4 +- tests/feature_check/reverse_ops.py | 2 +- tests/float/array_construct.py | 4 +- tests/float/builtin_float_hash.py | 20 +- tests/float/builtin_float_pow.py | 6 +- tests/float/builtin_float_round.py | 16 +- tests/float/builtin_float_round_intbig.py | 2 +- tests/float/bytearray_construct.py | 2 +- tests/float/bytes_construct.py | 2 +- tests/float/cmath_fun.py | 34 +- tests/float/cmath_fun_special.py | 15 +- tests/float/complex1.py | 37 +- tests/float/complex1_intbig.py | 3 +- tests/float/float1.py | 10 +- tests/float/float2int_doubleprec_intbig.py | 81 +- tests/float/float2int_fp30_intbig.py | 75 +- tests/float/float2int_intbig.py | 74 +- tests/float/float_array.py | 14 +- tests/float/float_compare.py | 2 + tests/float/float_divmod.py | 4 +- tests/float/float_divmod_relaxed.py | 4 +- tests/float/float_format.py | 14 +- tests/float/float_parse.py | 36 +- tests/float/float_parse_doubleprec.py | 24 +- tests/float/float_struct.py | 6 +- tests/float/int_power.py | 2 +- tests/float/math_domain.py | 56 +- tests/float/math_domain_special.py | 39 +- tests/float/math_fun.py | 71 +- tests/float/math_fun_bool.py | 3 +- tests/float/math_fun_int.py | 2 +- tests/float/math_fun_intbig.py | 2 +- tests/float/math_fun_special.py | 31 +- tests/float/python36.py | 8 +- tests/float/string_format.py | 15 +- tests/float/string_format2.py | 168 ++- tests/float/string_format_fp30.py | 23 +- tests/float/string_format_modulo.py | 40 +- tests/float/string_format_modulo2.py | 14 +- tests/float/string_format_modulo2_intbig.py | 12 +- tests/float/string_format_modulo3.py | 4 +- tests/float/true_value.py | 2 +- tests/import/builtin_import.py | 8 +- tests/import/gen_context.py | 2 + tests/import/import1a.py | 1 + tests/import/import1b.py | 1 + tests/import/import2a.py | 2 + tests/import/import3a.py | 1 + tests/import/import_file.py | 1 + tests/import/import_pkg1.py | 1 + tests/import/import_pkg3.py | 1 + tests/import/mpy_invalid.py | 22 +- tests/import/pkg3/mod2.py | 1 + tests/import/pkg6/__init__.py | 3 +- tests/import/pkg6/x/__init__.py | 3 +- tests/import/pkg6/x/y.py | 2 +- tests/import/pkg7/mod1.py | 4 +- tests/import/pkg7/mod2.py | 4 +- tests/import/pkg7/subpkg1/subpkg2/mod3.py | 3 +- tests/import/pkg8/mod.py | 2 +- tests/import/try_module.py | 5 +- tests/inlineasm/asmargs.py | 15 + tests/inlineasm/asmbcc.py | 2 + tests/inlineasm/asmbitops.py | 7 +- tests/inlineasm/asmblbx.py | 2 + tests/inlineasm/asmconst.py | 7 +- tests/inlineasm/asmdiv.py | 6 +- tests/inlineasm/asmfpaddsub.py | 3 +- tests/inlineasm/asmfpcmp.py | 9 +- tests/inlineasm/asmfpldrstr.py | 5 +- tests/inlineasm/asmfpmuldiv.py | 3 +- tests/inlineasm/asmfpsqrt.py | 3 +- tests/inlineasm/asmit.py | 6 + tests/inlineasm/asmpushpop.py | 1 + tests/inlineasm/asmrettype.py | 12 + tests/inlineasm/asmshift.py | 17 + tests/inlineasm/asmspecialregs.py | 2 + tests/inlineasm/asmsum.py | 6 +- tests/io/argv.py | 1 + tests/io/buffered_writer.py | 2 +- tests/io/builtin_print_file.py | 8 +- tests/io/file1.py | 26 +- tests/io/file_readinto.py | 4 +- tests/io/file_readline.py | 4 +- tests/io/file_seek.py | 4 +- tests/io/file_with.py | 2 +- tests/io/iobase.py | 7 +- tests/io/resource_stream.py | 2 +- tests/io/stringio1.py | 4 +- tests/io/write_ext.py | 2 +- tests/jni/list.py | 1 + tests/jni/object.py | 1 + tests/jni/system_out.py | 1 + tests/micropython/const.py | 6 +- tests/micropython/const2.py | 22 +- tests/micropython/const_error.py | 2 + tests/micropython/const_intbig.py | 4 +- tests/micropython/decorator.py | 4 +- tests/micropython/decorator_error.py | 2 + tests/micropython/emg_exc.py | 3 + tests/micropython/extreme_exc.py | 93 +- tests/micropython/heap_lock.py | 4 +- tests/micropython/heapalloc.py | 27 +- tests/micropython/heapalloc_bytesio2.py | 1 + tests/micropython/heapalloc_exc_raise.py | 2 + tests/micropython/heapalloc_inst_call.py | 5 + tests/micropython/heapalloc_iter.py | 17 +- tests/micropython/heapalloc_super.py | 17 +- tests/micropython/heapalloc_traceback.py | 5 +- tests/micropython/kbd_intr.py | 2 +- tests/micropython/meminfo.py | 4 +- tests/micropython/memstats.py | 4 +- tests/micropython/native_closure.py | 11 + tests/micropython/native_const_intbig.py | 2 + tests/micropython/native_misc.py | 9 + tests/micropython/opt_level.py | 8 +- tests/micropython/schedule.py | 17 +- tests/micropython/stack_use.py | 6 +- tests/micropython/viper_addr.py | 19 +- tests/micropython/viper_args.py | 31 +- tests/micropython/viper_binop_arith.py | 52 +- tests/micropython/viper_binop_comp.py | 3 +- tests/micropython/viper_binop_comp_imm.py | 1 + tests/micropython/viper_binop_divmod.py | 12 +- tests/micropython/viper_binop_multi_comp.py | 3 +- tests/micropython/viper_cond.py | 6 + tests/micropython/viper_error.py | 20 +- tests/micropython/viper_import.py | 5 + tests/micropython/viper_misc.py | 59 +- tests/micropython/viper_misc_intbig.py | 3 + tests/micropython/viper_ptr16_load.py | 17 +- tests/micropython/viper_ptr16_store.py | 17 +- tests/micropython/viper_ptr32_load.py | 17 +- tests/micropython/viper_ptr32_store.py | 17 +- tests/micropython/viper_ptr8_load.py | 17 +- tests/micropython/viper_ptr8_store.py | 17 +- tests/micropython/viper_subscr.py | 7 +- tests/misc/features.py | 232 ++-- tests/misc/non_compliant.py | 76 +- tests/misc/non_compliant_lexer.py | 24 +- tests/misc/print_exception.py | 24 +- tests/misc/rge_sm.py | 71 +- tests/misc/sys_exc_info.py | 5 +- tests/net_hosted/accept_nonblock.py | 4 +- tests/net_hosted/accept_timeout.py | 6 +- tests/net_hosted/connect_nonblock.py | 4 +- tests/net_hosted/connect_poll.py | 2 +- tests/net_hosted/ssl_getpeercert.py | 2 +- tests/net_inet/test_tls_sites.py | 7 +- tests/pyb/adc.py | 23 +- tests/pyb/can.py | 161 +-- tests/pyb/dac.py | 4 +- tests/pyb/extint.py | 2 +- tests/pyb/irq.py | 4 +- tests/pyb/modtime.py | 53 +- tests/pyb/pin.py | 8 +- tests/pyb/pyb1.py | 4 +- tests/pyb/pyb_f405.py | 4 +- tests/pyb/pyb_f411.py | 4 +- tests/pyb/rtc.py | 17 +- tests/pyb/timer_callback.py | 5 + tests/pyb/uart.py | 8 +- tests/pybnative/for.py | 4 + tests/pybnative/while.py | 2 + tests/run-tests-exp.py | 16 +- tests/skip_if.py | 18 +- tests/stress/dict_copy.py | 2 +- tests/stress/gc_trace.py | 4 +- tests/stress/recursion.py | 1 + tests/stress/recursive_gen.py | 8 +- tests/thread/mutate_bytearray.py | 3 +- tests/thread/mutate_dict.py | 3 +- tests/thread/mutate_instance.py | 17 +- tests/thread/mutate_list.py | 1 + tests/thread/mutate_set.py | 1 + tests/thread/stress_aes.py | 309 ++++- tests/thread/stress_create.py | 4 +- tests/thread/stress_heap.py | 3 + tests/thread/stress_recurse.py | 7 +- tests/thread/thread_exc1.py | 5 +- tests/thread/thread_exc2.py | 4 +- tests/thread/thread_exit1.py | 4 +- tests/thread/thread_exit2.py | 4 +- tests/thread/thread_gc1.py | 2 + tests/thread/thread_ident1.py | 8 +- tests/thread/thread_lock1.py | 4 +- tests/thread/thread_lock2.py | 6 +- tests/thread/thread_lock3.py | 4 +- tests/thread/thread_lock4.py | 3 + tests/thread/thread_qstr1.py | 6 +- tests/thread/thread_shared1.py | 3 + tests/thread/thread_shared2.py | 3 + tests/thread/thread_sleep1.py | 6 +- tests/thread/thread_stacksize1.py | 7 +- tests/thread/thread_start1.py | 5 +- tests/thread/thread_start2.py | 10 +- tests/unicode/file2.py | 16 +- tests/unicode/unicode.py | 32 +- tests/unicode/unicode_id.py | 5 + tests/unicode/unicode_ord.py | 2 +- tests/unicode/unicode_str_format.py | 4 +- tests/unicode/unicode_str_modulo.py | 2 +- tests/unicode/unicode_subscr.py | 2 +- tests/unix/extra_coverage.py | 51 +- tests/unix/ffi_callback.py | 7 +- tests/unix/ffi_float.py | 13 +- tests/unix/ffi_float2.py | 7 +- tests/wipy/adc.py | 38 +- tests/wipy/modwipy.py | 10 +- tests/wipy/os.py | 158 +-- tests/wipy/pin.py | 110 +- tests/wipy/pin_irq.py | 38 +- tests/wipy/reset/reset.py | 8 +- tests/wipy/rtc.py | 28 +- tests/wipy/sd.py | 18 +- tests/wipy/skipped/rtc_irq.py | 18 +- tests/wipy/time.py | 58 +- tests/wipy/timer.py | 25 +- tests/wipy/uart.py | 100 +- tests/wipy/uart_irq.py | 67 +- tests/wipy/wdt.py | 4 +- tests/wipy/wlan/machine.py | 14 +- tests/wipy/wlan/server.py | 18 +- tests/wipy/wlan/wlan.py | 76 +- tools/analyze_heap_dump.py | 320 +++-- tools/analyze_mpy.py | 403 +++--- tools/build_board_info.py | 15 +- tools/build_memory_info.py | 20 +- tools/build_release_files.py | 64 +- tools/chart_code_size.py | 85 +- tools/ci_check_duplicate_usb_vid_pid.py | 42 +- tools/ci_new_boards_check.py | 14 +- tools/codeformat.py | 5 +- tools/convert_release_notes.py | 6 +- tools/cpboard.py | 44 +- tools/dfu.py | 183 +-- tools/extract_pyi.py | 74 +- tools/file2h.py | 12 +- tools/fixup_translations.py | 8 +- tools/gc_activity.py | 40 +- tools/gc_activity_between_collects.py | 55 +- tools/gen_display_resources.py | 81 +- tools/gen_ld_files.py | 34 +- tools/gen_usb_descriptor.py | 145 +-- tools/gendoc.py | 245 ++-- tools/hid_report_descriptors.py | 648 +++++++--- tools/insert-usb-ids.py | 16 +- tools/make-frozen.py | 11 +- tools/mpconfig_category_reader.py | 2 +- tools/mpy-tool.py | 567 ++++---- tools/mpy_cross_all.py | 21 +- tools/preprocess_frozen_modules.py | 37 +- tools/print_status.py | 14 +- tools/pyboard.py | 185 ++- tools/pydfu.py | 234 ++-- tools/tinytest-codegen.py | 111 +- tools/upip.py | 64 +- tools/upip_utarfile.py | 39 +- 1763 files changed, 28843 insertions(+), 25506 deletions(-) mode change 100755 => 100644 lib/utils/pyexec.c mode change 100755 => 100644 ports/atmel-samd/boards/circuitbrains_basic_m0/pins.c mode change 100755 => 100644 ports/atmel-samd/boards/feather_radiofruit_zigbee/board.c mode change 100755 => 100644 ports/atmel-samd/boards/feather_radiofruit_zigbee/mpconfigboard.h mode change 100755 => 100644 ports/atmel-samd/boards/sparkfun_lumidrive/board.c mode change 100755 => 100644 ports/atmel-samd/boards/sparkfun_lumidrive/mpconfigboard.h mode change 100755 => 100644 ports/atmel-samd/boards/sparkfun_redboard_turbo/board.c mode change 100755 => 100644 ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.h create mode 100644 ports/atmel-samd/common-hal/audiobusio/PDMIn.c.uncrustify mode change 100755 => 100644 ports/cxd56/common-hal/supervisor/Runtime.c mode change 100755 => 100644 ports/esp32s2/peripherals/pins.c mode change 100755 => 100644 ports/mimxrt10xx/common-hal/supervisor/Runtime.c mode change 100755 => 100644 ports/nrf/common-hal/supervisor/Runtime.c mode change 100755 => 100644 ports/raspberrypi/common-hal/supervisor/Runtime.c mode change 100755 => 100644 ports/stm/common-hal/supervisor/Runtime.c mode change 100755 => 100644 py/gc.c mode change 100755 => 100644 py/gc_long_lived.c mode change 100755 => 100644 py/mpconfig.h mode change 100755 => 100644 py/qstr.c mode change 100755 => 100644 shared-bindings/supervisor/Runtime.c mode change 100755 => 100644 shared-bindings/supervisor/Runtime.h mode change 100755 => 100644 shared-bindings/supervisor/__init__.h mode change 100755 => 100644 supervisor/linker.h mode change 100755 => 100644 supervisor/memory.h mode change 100755 => 100644 supervisor/shared/memory.c mode change 100755 => 100644 supervisor/shared/stack.c mode change 100755 => 100644 supervisor/shared/stack.h diff --git a/devices/ble_hci/common-hal/_bleio/Adapter.c b/devices/ble_hci/common-hal/_bleio/Adapter.c index 753a886486..7f0b088c4e 100644 --- a/devices/ble_hci/common-hal/_bleio/Adapter.c +++ b/devices/ble_hci/common-hal/_bleio/Adapter.c @@ -51,7 +51,7 @@ #define MSEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000) / (RESOLUTION)) #define SEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000000) / (RESOLUTION)) -#define UNITS_TO_SEC(TIME, RESOLUTION) (((TIME) * (RESOLUTION)) / 1000000) +#define UNITS_TO_SEC(TIME, RESOLUTION) (((TIME)*(RESOLUTION)) / 1000000) // 0.625 msecs (625 usecs) #define ADV_INTERVAL_UNIT_FLOAT_SECS (0.000625) // Microseconds is the base unit. The macros above know that. @@ -63,7 +63,7 @@ // TODO make this settable from Python. #define DEFAULT_TX_POWER 0 // 0 dBm -#define MAX_ANONYMOUS_ADV_TIMEOUT_SECS (60*15) +#define MAX_ANONYMOUS_ADV_TIMEOUT_SECS (60 * 15) #define MAX_LIMITED_DISCOVERABLE_ADV_TIMEOUT_SECS (180) #define BLE_MIN_CONN_INTERVAL MSEC_TO_UNITS(15, UNIT_0_625_MS) @@ -289,7 +289,7 @@ STATIC void bleio_adapter_hci_init(bleio_adapter_obj_t *self) { // Get version information. if (hci_read_local_version(&self->hci_version, &self->hci_revision, &self->lmp_version, - &self->manufacturer, &self->lmp_subversion) != HCI_OK) { + &self->manufacturer, &self->lmp_subversion) != HCI_OK) { mp_raise_bleio_BluetoothError(translate("Could not read HCI version")); } // Get supported features. @@ -414,11 +414,11 @@ bool common_hal_bleio_adapter_set_address(bleio_adapter_obj_t *self, bleio_addre return hci_le_set_random_address(bufinfo.buf) == HCI_OK; } -mp_obj_str_t* common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) { +mp_obj_str_t *common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) { return self->name; } -void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char* name) { +void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char *name) { self->name = mp_obj_new_str(name, strlen(name)); mp_buffer_info_t bufinfo; mp_get_buffer_raise(self->name, &bufinfo, MP_BUFFER_READ); @@ -459,7 +459,7 @@ void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char* na // return true; // } -mp_obj_t common_hal_bleio_adapter_start_scan(bleio_adapter_obj_t *self, uint8_t* prefixes, size_t prefix_length, bool extended, mp_int_t buffer_size, mp_float_t timeout, mp_float_t interval, mp_float_t window, mp_int_t minimum_rssi, bool active) { +mp_obj_t common_hal_bleio_adapter_start_scan(bleio_adapter_obj_t *self, uint8_t *prefixes, size_t prefix_length, bool extended, mp_int_t buffer_size, mp_float_t timeout, mp_float_t interval, mp_float_t window, mp_int_t minimum_rssi, bool active) { // TODO mp_raise_NotImplementedError(NULL); check_enabled(self); @@ -704,7 +704,7 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, uint8_t handle[1] = { 0 }; uint16_t duration_10msec[1] = { timeout * 100 }; - uint8_t max_ext_adv_evts[1] = { 0 }; + uint8_t max_ext_adv_evts[1] = { 0 }; hci_check_error( hci_le_set_extended_advertising_enable( BT_HCI_LE_ADV_ENABLE, @@ -789,11 +789,11 @@ void common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool } else { if (timeout > MAX_LIMITED_DISCOVERABLE_ADV_TIMEOUT_SECS) { mp_raise_bleio_BluetoothError(translate("Timeout is too long: Maximum timeout length is %d seconds"), - MAX_LIMITED_DISCOVERABLE_ADV_TIMEOUT_SECS); + MAX_LIMITED_DISCOVERABLE_ADV_TIMEOUT_SECS); } } - const uint32_t result =_common_hal_bleio_adapter_start_advertising( + const uint32_t result = _common_hal_bleio_adapter_start_advertising( self, connectable, anonymous, timeout, interval, advertising_data_bufinfo->buf, advertising_data_bufinfo->len, @@ -820,11 +820,11 @@ void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self) { hci_check_error(result); } - //TODO startup CircuitPython advertising again. + // TODO startup CircuitPython advertising again. } // Note that something stopped advertising, such as a connection happening. -//Don't ask the adapter to stop. +// Don't ask the adapter to stop. void bleio_adapter_advertising_was_stopped(bleio_adapter_obj_t *self) { self->now_advertising = false; self->extended_advertising = false; @@ -876,14 +876,14 @@ void common_hal_bleio_adapter_erase_bonding(bleio_adapter_obj_t *self) { mp_raise_NotImplementedError(NULL); check_enabled(self); - //FIX bonding_erase_storage(); + // FIX bonding_erase_storage(); } uint16_t bleio_adapter_add_attribute(bleio_adapter_obj_t *adapter, mp_obj_t *attribute) { check_enabled(adapter); // The handle is the index of this attribute in the attributes list. - uint16_t handle = (uint16_t) adapter->attributes->len; + uint16_t handle = (uint16_t)adapter->attributes->len; mp_obj_list_append(adapter->attributes, attribute); if (MP_OBJ_IS_TYPE(attribute, &bleio_service_type)) { @@ -896,7 +896,7 @@ uint16_t bleio_adapter_add_attribute(bleio_adapter_obj_t *adapter, mp_obj_t *att return handle; } -mp_obj_t* bleio_adapter_get_attribute(bleio_adapter_obj_t *adapter, uint16_t handle) { +mp_obj_t *bleio_adapter_get_attribute(bleio_adapter_obj_t *adapter, uint16_t handle) { check_enabled(adapter); if (handle == 0 || handle >= adapter->attributes->len) { @@ -912,12 +912,12 @@ uint16_t bleio_adapter_max_attribute_handle(bleio_adapter_obj_t *adapter) { } -void bleio_adapter_gc_collect(bleio_adapter_obj_t* adapter) { - gc_collect_root((void**)adapter, sizeof(bleio_adapter_obj_t) / sizeof(size_t)); - gc_collect_root((void**)bleio_connections, sizeof(bleio_connections) / sizeof(size_t)); +void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter) { + gc_collect_root((void **)adapter, sizeof(bleio_adapter_obj_t) / sizeof(size_t)); + gc_collect_root((void **)bleio_connections, sizeof(bleio_connections) / sizeof(size_t)); } -void bleio_adapter_reset(bleio_adapter_obj_t* adapter) { +void bleio_adapter_reset(bleio_adapter_obj_t *adapter) { if (!common_hal_bleio_adapter_get_enabled(adapter)) { return; @@ -939,7 +939,7 @@ void bleio_adapter_reset(bleio_adapter_obj_t* adapter) { } -void bleio_adapter_background(bleio_adapter_obj_t* adapter) { +void bleio_adapter_background(bleio_adapter_obj_t *adapter) { if (!common_hal_bleio_adapter_get_enabled(adapter)) { return; } diff --git a/devices/ble_hci/common-hal/_bleio/Adapter.h b/devices/ble_hci/common-hal/_bleio/Adapter.h index bec1329f28..48d4f2e6a2 100644 --- a/devices/ble_hci/common-hal/_bleio/Adapter.h +++ b/devices/ble_hci/common-hal/_bleio/Adapter.h @@ -49,7 +49,7 @@ typedef struct _bleio_adapter_obj_t { bleio_scanresults_obj_t *scan_results; mp_obj_t name; mp_obj_tuple_t *connection_objs; - busio_uart_obj_t* hci_uart; + busio_uart_obj_t *hci_uart; digitalio_digitalinout_obj_t *rts_digitalinout; digitalio_digitalinout_obj_t *cts_digitalinout; bool allocated; // True when in use. @@ -72,7 +72,7 @@ typedef struct _bleio_adapter_obj_t { // Generic services characteristics. bleio_characteristic_obj_t *device_name_characteristic; bleio_characteristic_obj_t *appearance_characteristic; - bleio_characteristic_obj_t * service_changed_characteristic; + bleio_characteristic_obj_t *service_changed_characteristic; uint16_t max_acl_buffer_len; uint16_t max_acl_num_buffers; @@ -90,10 +90,10 @@ typedef struct _bleio_adapter_obj_t { uint16_t bleio_adapter_add_attribute(bleio_adapter_obj_t *adapter, mp_obj_t *attribute); void bleio_adapter_advertising_was_stopped(bleio_adapter_obj_t *self); -mp_obj_t* bleio_adapter_get_attribute(bleio_adapter_obj_t *adapter, uint16_t handle); +mp_obj_t *bleio_adapter_get_attribute(bleio_adapter_obj_t *adapter, uint16_t handle); uint16_t bleio_adapter_max_attribute_handle(bleio_adapter_obj_t *adapter); -void bleio_adapter_background(bleio_adapter_obj_t* adapter); -void bleio_adapter_gc_collect(bleio_adapter_obj_t* adapter); -void bleio_adapter_reset(bleio_adapter_obj_t* adapter); +void bleio_adapter_background(bleio_adapter_obj_t *adapter); +void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter); +void bleio_adapter_reset(bleio_adapter_obj_t *adapter); #endif // MICROPY_INCLUDED_BLE_HCI_COMMON_HAL_ADAPTER_H diff --git a/devices/ble_hci/common-hal/_bleio/Characteristic.c b/devices/ble_hci/common-hal/_bleio/Characteristic.c index 393b80459a..7255661576 100644 --- a/devices/ble_hci/common-hal/_bleio/Characteristic.c +++ b/devices/ble_hci/common-hal/_bleio/Characteristic.c @@ -78,16 +78,16 @@ bleio_service_obj_t *common_hal_bleio_characteristic_get_service(bleio_character return self->service; } -size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t* buf, size_t len) { +size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t *buf, size_t len) { // Do GATT operations only if this characteristic has been added to a registered service. if (self->handle != BLE_GATT_HANDLE_INVALID) { - //FIX uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); + // FIX uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); if (common_hal_bleio_service_get_is_remote(self->service)) { - //FIX read remote chars - //uint8_t rsp[MAX(len, 512)]; - //FIX improve att_read_req to write into our requested buffer. + // FIX read remote chars + // uint8_t rsp[MAX(len, 512)]; + // FIX improve att_read_req to write into our requested buffer. // return att_read_req(conn_handle, self->handle, rsp); - return 0; //FIX + return 0; // FIX } else { mp_buffer_info_t bufinfo; if (!mp_get_buffer(self->value, &bufinfo, MP_BUFFER_READ)) { @@ -113,13 +113,13 @@ void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, // Do GATT operations only if this characteristic has been added to a registered service. if (self->handle != BLE_GATT_HANDLE_INVALID) { if (common_hal_bleio_service_get_is_remote(self->service)) { - //FIX uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); + // FIX uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); if (self->props & CHAR_PROP_WRITE) { - //FIX writing remote chars - //uint8_t rsp[sizeof(bt_att_error_rsp)]; - //att_write_req(conn_handle, self->handle, bufinfo->buf, bufinfo->len, rsp); + // FIX writing remote chars + // uint8_t rsp[sizeof(bt_att_error_rsp)]; + // att_write_req(conn_handle, self->handle, bufinfo->buf, bufinfo->len, rsp); } else if (self->props & CHAR_PROP_WRITE_NO_RESPONSE) { - //att_write_cmd(conn_handle, self->handle, bufinfo->buff, bufinfo->len); + // att_write_cmd(conn_handle, self->handle, bufinfo->buff, bufinfo->len); } else { mp_raise_bleio_BluetoothError(translate("Characteristic not writable")); } @@ -172,7 +172,7 @@ void common_hal_bleio_characteristic_add_descriptor(bleio_characteristic_obj_t * self->service->end_handle = descriptor->handle; mp_obj_list_append(MP_OBJ_FROM_PTR(self->descriptor_list), - MP_OBJ_FROM_PTR(descriptor)); + MP_OBJ_FROM_PTR(descriptor)); } void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, bool notify, bool indicate) { @@ -191,8 +191,8 @@ void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, (notify ? CCCD_NOTIFY : 0) | (indicate ? CCCD_INDICATE : 0); - //FIX do remote - (void) cccd_value; + // FIX do remote + (void)cccd_value; // uint8_t rsp[sizeof(bt_att_error_rsp)]; // if (att_write_req(conn_handle, self->cccd->handle, &cccd_value, sizeof(cccd_value)) == 0) { // mp_raise_bleio_BluetoothError(translate("Could not write CCCD")); diff --git a/devices/ble_hci/common-hal/_bleio/CharacteristicBuffer.c b/devices/ble_hci/common-hal/_bleio/CharacteristicBuffer.c index e8cd518808..8be1abef1f 100644 --- a/devices/ble_hci/common-hal/_bleio/CharacteristicBuffer.c +++ b/devices/ble_hci/common-hal/_bleio/CharacteristicBuffer.c @@ -47,9 +47,9 @@ void bleio_characteristic_buffer_update(bleio_characteristic_buffer_obj_t *self, // Assumes that timeout and buffer_size have been validated before call. void common_hal_bleio_characteristic_buffer_construct(bleio_characteristic_buffer_obj_t *self, - bleio_characteristic_obj_t *characteristic, - mp_float_t timeout, - size_t buffer_size) { + bleio_characteristic_obj_t *characteristic, + mp_float_t timeout, + size_t buffer_size) { self->characteristic = characteristic; self->timeout_ms = timeout * 1000; @@ -64,10 +64,10 @@ uint32_t common_hal_bleio_characteristic_buffer_read(bleio_characteristic_buffer uint64_t start_ticks = supervisor_ticks_ms64(); // Wait for all bytes received or timeout - while ( (ringbuf_num_filled(&self->ringbuf) < len) && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms) ) { + while ((ringbuf_num_filled(&self->ringbuf) < len) && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms)) { RUN_BACKGROUND_TASKS; // Allow user to break out of a timeout with a KeyboardInterrupt. - if ( mp_hal_is_interrupted() ) { + if (mp_hal_is_interrupted()) { return 0; } } @@ -97,8 +97,8 @@ void common_hal_bleio_characteristic_buffer_deinit(bleio_characteristic_buffer_o bool common_hal_bleio_characteristic_buffer_connected(bleio_characteristic_buffer_obj_t *self) { return self->characteristic != NULL && - self->characteristic->service != NULL && - (!self->characteristic->service->is_remote || - (self->characteristic->service->connection != MP_OBJ_NULL && - common_hal_bleio_connection_get_connected(self->characteristic->service->connection))); + self->characteristic->service != NULL && + (!self->characteristic->service->is_remote || + (self->characteristic->service->connection != MP_OBJ_NULL && + common_hal_bleio_connection_get_connected(self->characteristic->service->connection))); } diff --git a/devices/ble_hci/common-hal/_bleio/Connection.c b/devices/ble_hci/common-hal/_bleio/Connection.c index ba4eb477d9..a27c243f44 100644 --- a/devices/ble_hci/common-hal/_bleio/Connection.c +++ b/devices/ble_hci/common-hal/_bleio/Connection.c @@ -73,8 +73,8 @@ static volatile bool m_discovery_in_process; static volatile bool m_discovery_successful; -//FIX static bleio_service_obj_t *m_char_discovery_service; -//FIX static bleio_characteristic_obj_t *m_desc_discovery_characteristic; +// FIX static bleio_service_obj_t *m_char_discovery_service; +// FIX static bleio_characteristic_obj_t *m_desc_discovery_characteristic; // bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { // bleio_connection_internal_t *self = (bleio_connection_internal_t*)self_in; @@ -326,7 +326,7 @@ void bleio_connection_clear(bleio_connection_internal_t *self) { self->conn_handle = BLE_CONN_HANDLE_INVALID; self->pair_status = PAIR_NOT_PAIRED; self->is_central = false; - //FIX bonding_clear_keys(&self->bonding_keys); + // FIX bonding_clear_keys(&self->bonding_keys); } bool common_hal_bleio_connection_get_paired(bleio_connection_obj_t *self) { @@ -350,7 +350,7 @@ void common_hal_bleio_connection_disconnect(bleio_connection_internal_t *self) { void common_hal_bleio_connection_pair(bleio_connection_internal_t *self, bool bond) { self->pair_status = PAIR_WAITING; - //FIX check_nrf_error(sd_ble_gap_authenticate(self->conn_handle, &pairing_sec_params)); + // FIX check_nrf_error(sd_ble_gap_authenticate(self->conn_handle, &pairing_sec_params)); while (self->pair_status == PAIR_WAITING && !mp_hal_is_interrupted()) { RUN_BACKGROUND_TASKS; @@ -358,14 +358,14 @@ void common_hal_bleio_connection_pair(bleio_connection_internal_t *self, bool bo if (mp_hal_is_interrupted()) { return; } - //FIX check_sec_status(self->sec_status); + // FIX check_sec_status(self->sec_status); } mp_float_t common_hal_bleio_connection_get_connection_interval(bleio_connection_internal_t *self) { while (self->conn_params_updating && !mp_hal_is_interrupted()) { RUN_BACKGROUND_TASKS; } - //FIX return 1.25f * self->conn_params.min_conn_interval; + // FIX return 1.25f * self->conn_params.min_conn_interval; return 0.0f; } @@ -729,14 +729,14 @@ void common_hal_bleio_connection_set_connection_interval(bleio_connection_intern // } mp_obj_tuple_t *common_hal_bleio_connection_discover_remote_services(bleio_connection_obj_t *self, mp_obj_t service_uuids_whitelist) { - //FIX discover_remote_services(self->connection, service_uuids_whitelist); + // FIX discover_remote_services(self->connection, service_uuids_whitelist); bleio_connection_ensure_connected(self); // Convert to a tuple and then clear the list so the callee will take ownership. - mp_obj_tuple_t *services_tuple = - mp_obj_new_tuple(self->connection->remote_service_list->len, - self->connection->remote_service_list->items); - mp_obj_list_clear(MP_OBJ_FROM_PTR(self->connection->remote_service_list)); - return services_tuple; + mp_obj_tuple_t *services_tuple = + mp_obj_new_tuple(self->connection->remote_service_list->len, + self->connection->remote_service_list->items); + mp_obj_list_clear(MP_OBJ_FROM_PTR(self->connection->remote_service_list)); + return services_tuple; } uint16_t bleio_connection_get_conn_handle(bleio_connection_obj_t *self) { @@ -746,7 +746,7 @@ uint16_t bleio_connection_get_conn_handle(bleio_connection_obj_t *self) { return self->connection->conn_handle; } -mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t* internal) { +mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t *internal) { if (internal->connection_obj != mp_const_none) { return internal->connection_obj; } diff --git a/devices/ble_hci/common-hal/_bleio/Connection.h b/devices/ble_hci/common-hal/_bleio/Connection.h index 0b1f26a213..2933bb87a5 100644 --- a/devices/ble_hci/common-hal/_bleio/Connection.h +++ b/devices/ble_hci/common-hal/_bleio/Connection.h @@ -60,7 +60,7 @@ typedef struct { volatile pair_status_t pair_status; uint8_t sec_status; // Internal security status. mp_obj_t connection_obj; - //REMOVE ble_gap_conn_params_t conn_params; + // REMOVE ble_gap_conn_params_t conn_params; volatile bool conn_params_updating; uint16_t mtu; // Request that CCCD values for this connection be saved, using sys_attr values. @@ -70,20 +70,20 @@ typedef struct { // Time of setting do_bond_ccds: we delay a bit to consolidate multiple CCCD changes // into one write. Time is currently in ticks_ms. uint64_t do_bond_cccds_request_time; - //FIX from att.c + // FIX from att.c uint8_t role; bt_addr_le_t addr; } bleio_connection_internal_t; typedef struct { mp_obj_base_t base; - bleio_connection_internal_t* connection; + bleio_connection_internal_t *connection; // The HCI disconnect reason. uint8_t disconnect_reason; } bleio_connection_obj_t; uint16_t bleio_connection_get_conn_handle(bleio_connection_obj_t *self); -mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t* connection); +mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t *connection); bleio_connection_internal_t *bleio_conn_handle_to_connection(uint16_t conn_handle); #endif // MICROPY_INCLUDED_BLE_HCI_COMMON_HAL_CONNECTION_H diff --git a/devices/ble_hci/common-hal/_bleio/Descriptor.c b/devices/ble_hci/common-hal/_bleio/Descriptor.c index 645273e285..444d57fb3d 100644 --- a/devices/ble_hci/common-hal/_bleio/Descriptor.c +++ b/devices/ble_hci/common-hal/_bleio/Descriptor.c @@ -44,7 +44,7 @@ void common_hal_bleio_descriptor_construct(bleio_descriptor_obj_t *self, bleio_c const mp_int_t max_length_max = fixed_length ? BLE_GATTS_FIX_ATTR_LEN_MAX : BLE_GATTS_VAR_ATTR_LEN_MAX; if (max_length < 0 || max_length > max_length_max) { mp_raise_ValueError_varg(translate("max_length must be 0-%d when fixed_length is %s"), - max_length_max, fixed_length ? "True" : "False"); + max_length_max, fixed_length ? "True" : "False"); } self->max_length = max_length; self->fixed_length = fixed_length; @@ -60,14 +60,14 @@ bleio_characteristic_obj_t *common_hal_bleio_descriptor_get_characteristic(bleio return self->characteristic; } -size_t common_hal_bleio_descriptor_get_value(bleio_descriptor_obj_t *self, uint8_t* buf, size_t len) { +size_t common_hal_bleio_descriptor_get_value(bleio_descriptor_obj_t *self, uint8_t *buf, size_t len) { // Do GATT operations only if this descriptor has been registered if (self->handle != BLE_GATT_HANDLE_INVALID) { if (common_hal_bleio_service_get_is_remote(self->characteristic->service)) { - //uint16_t conn_handle = bleio_connection_get_conn_handle(self->characteristic->service->connection); - //FIX have att_read_req fill in a buffer - //uint8_t rsp[MAX(len, 512)]; - //return att_read_req(conn_handle, self->handle, rsp, len); + // uint16_t conn_handle = bleio_connection_get_conn_handle(self->characteristic->service->connection); + // FIX have att_read_req fill in a buffer + // uint8_t rsp[MAX(len, 512)]; + // return att_read_req(conn_handle, self->handle, rsp, len); return 0; } else { mp_buffer_info_t bufinfo; @@ -96,7 +96,7 @@ void common_hal_bleio_descriptor_set_value(bleio_descriptor_obj_t *self, mp_buff // Do GATT operations only if this descriptor has been registered. if (self->handle != BLE_GATT_HANDLE_INVALID) { if (common_hal_bleio_service_get_is_remote(self->characteristic->service)) { - //FIX + // FIX // uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); // att_write_req(conn_handle, self->handle, bufinfo->buf, bufinfo->len, rsp); } else { diff --git a/devices/ble_hci/common-hal/_bleio/Descriptor.h b/devices/ble_hci/common-hal/_bleio/Descriptor.h index 097a49f8ec..ffa0c172aa 100644 --- a/devices/ble_hci/common-hal/_bleio/Descriptor.h +++ b/devices/ble_hci/common-hal/_bleio/Descriptor.h @@ -47,7 +47,7 @@ typedef struct _bleio_descriptor_obj { uint16_t handle; bleio_attribute_security_mode_t read_perm; bleio_attribute_security_mode_t write_perm; - struct _bleio_descriptor_obj* next; + struct _bleio_descriptor_obj *next; } bleio_descriptor_obj_t; #endif // MICROPY_INCLUDED_BLE_HCI_COMMON_HAL_DESCRIPTOR_H diff --git a/devices/ble_hci/common-hal/_bleio/PacketBuffer.c b/devices/ble_hci/common-hal/_bleio/PacketBuffer.c index 98912ba902..9d8a21601d 100644 --- a/devices/ble_hci/common-hal/_bleio/PacketBuffer.c +++ b/devices/ble_hci/common-hal/_bleio/PacketBuffer.c @@ -45,13 +45,13 @@ STATIC void write_to_ringbuf(bleio_packet_buffer_obj_t *self, uint8_t *data, uin // Make room for the new value by dropping the oldest packets first. while (ringbuf_capacity(&self->ringbuf) - ringbuf_num_filled(&self->ringbuf) < len + sizeof(uint16_t)) { uint16_t packet_length; - ringbuf_get_n(&self->ringbuf, (uint8_t*) &packet_length, sizeof(uint16_t)); + ringbuf_get_n(&self->ringbuf, (uint8_t *)&packet_length, sizeof(uint16_t)); for (uint16_t i = 0; i < packet_length; i++) { ringbuf_get(&self->ringbuf); } // set an overflow flag? } - ringbuf_put_n(&self->ringbuf, (uint8_t*) &len, sizeof(uint16_t)); + ringbuf_put_n(&self->ringbuf, (uint8_t *)&len, sizeof(uint16_t)); ringbuf_put_n(&self->ringbuf, data, len); } @@ -80,8 +80,8 @@ void bleio_packet_buffer_update(bleio_packet_buffer_obj_t *self, mp_buffer_info_ } void common_hal_bleio_packet_buffer_construct( - bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, - size_t buffer_size) { + bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, + size_t buffer_size) { self->characteristic = characteristic; self->client = self->characteristic->service->is_remote; @@ -128,7 +128,7 @@ mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self // Copy received data. // Get packet length, which is in first two bytes of packet. uint16_t packet_length; - ringbuf_get_n(&self->ringbuf, (uint8_t*) &packet_length, sizeof(uint16_t)); + ringbuf_get_n(&self->ringbuf, (uint8_t *)&packet_length, sizeof(uint16_t)); mp_int_t ret; if (packet_length > len) { @@ -136,7 +136,7 @@ mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self ret = len - packet_length; // Discard the packet if it's too large. Don't fill data. while (packet_length--) { - (void) ringbuf_get(&self->ringbuf); + (void)ringbuf_get(&self->ringbuf); } } else { // Read as much as possible, but might be shorter than len. @@ -147,7 +147,7 @@ mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self return ret; } -mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len, uint8_t* header, size_t header_len) { +mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len, uint8_t *header, size_t header_len) { if (self->outgoing[0] == NULL) { mp_raise_bleio_BluetoothError(translate("Writes not supported on Characteristic")); } @@ -174,7 +174,7 @@ mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, u size_t num_bytes_written = 0; - uint8_t* pending = self->outgoing[self->pending_index]; + uint8_t *pending = self->outgoing[self->pending_index]; if (self->pending_size == 0) { memcpy(pending, header, header_len); @@ -213,7 +213,7 @@ mp_int_t common_hal_bleio_packet_buffer_get_incoming_packet_length(bleio_packet_ bleio_connection_internal_t *connection = bleio_conn_handle_to_connection(self->conn_handle); if (connection) { return MIN(common_hal_bleio_connection_get_max_packet_length(connection), - self->characteristic->max_length); + self->characteristic->max_length); } } // There's no current connection, so we don't know the MTU, and @@ -244,7 +244,7 @@ mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_ bleio_connection_internal_t *connection = bleio_conn_handle_to_connection(self->conn_handle); if (connection) { return MIN(common_hal_bleio_connection_get_max_packet_length(connection), - self->characteristic->max_length); + self->characteristic->max_length); } } // There's no current connection, so we don't know the MTU, and diff --git a/devices/ble_hci/common-hal/_bleio/PacketBuffer.h b/devices/ble_hci/common-hal/_bleio/PacketBuffer.h index 074c03dc69..7f351929d5 100644 --- a/devices/ble_hci/common-hal/_bleio/PacketBuffer.h +++ b/devices/ble_hci/common-hal/_bleio/PacketBuffer.h @@ -37,7 +37,7 @@ typedef struct { ringbuf_t ringbuf; // Two outgoing buffers to alternate between. One will be queued for transmission by the SD and // the other is waiting to be queued and can be extended. - uint8_t* outgoing[2]; + uint8_t *outgoing[2]; volatile uint16_t pending_size; // We remember the conn_handle so we can do a NOTIFY/INDICATE to a client. // We can find out the conn_handle on a Characteristic write or a CCCD write (but not a read). diff --git a/devices/ble_hci/common-hal/_bleio/Service.c b/devices/ble_hci/common-hal/_bleio/Service.c index 5803f5309d..0bf00566f2 100644 --- a/devices/ble_hci/common-hal/_bleio/Service.c +++ b/devices/ble_hci/common-hal/_bleio/Service.c @@ -32,7 +32,7 @@ #include "shared-bindings/_bleio/Service.h" #include "shared-bindings/_bleio/Adapter.h" -uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary, mp_obj_list_t * characteristic_list) { +uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary, mp_obj_list_t *characteristic_list) { self->uuid = uuid; self->characteristic_list = characteristic_list; self->is_remote = false; @@ -52,7 +52,7 @@ uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uu void common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary) { if (_common_hal_bleio_service_construct(self, uuid, is_secondary, - mp_obj_new_list(0, NULL)) != 0) { + mp_obj_new_list(0, NULL)) != 0) { mp_raise_RuntimeError(translate("Failed to add service")); } } @@ -83,8 +83,8 @@ bool common_hal_bleio_service_get_is_secondary(bleio_service_obj_t *self) { } void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, - bleio_characteristic_obj_t *characteristic, - mp_buffer_info_t *initial_value_bufinfo) { + bleio_characteristic_obj_t *characteristic, + mp_buffer_info_t *initial_value_bufinfo) { if (self->handle != common_hal_bleio_adapter_obj.last_added_service_handle) { mp_raise_bleio_BluetoothError( diff --git a/devices/ble_hci/common-hal/_bleio/Service.h b/devices/ble_hci/common-hal/_bleio/Service.h index 11e7d1c960..dce6f13144 100644 --- a/devices/ble_hci/common-hal/_bleio/Service.h +++ b/devices/ble_hci/common-hal/_bleio/Service.h @@ -46,7 +46,7 @@ typedef struct bleio_service_obj { // Range of attribute handles of this service. uint16_t start_handle; uint16_t end_handle; - struct bleio_service_obj* next; + struct bleio_service_obj *next; } bleio_service_obj_t; void bleio_service_from_connection(bleio_service_obj_t *self, mp_obj_t connection); diff --git a/devices/ble_hci/common-hal/_bleio/UUID.c b/devices/ble_hci/common-hal/_bleio/UUID.c index a50efc3b1e..f12d1e78fb 100644 --- a/devices/ble_hci/common-hal/_bleio/UUID.c +++ b/devices/ble_hci/common-hal/_bleio/UUID.c @@ -60,7 +60,7 @@ void common_hal_bleio_uuid_get_uuid128(bleio_uuid_obj_t *self, uint8_t uuid128[1 memcpy(uuid128, self->uuid128, 16); } -void common_hal_bleio_uuid_pack_into(bleio_uuid_obj_t *self, uint8_t* buf) { +void common_hal_bleio_uuid_pack_into(bleio_uuid_obj_t *self, uint8_t *buf) { if (self->size == 16) { buf[0] = self->uuid16 & 0xff; buf[1] = self->uuid16 >> 8; diff --git a/devices/ble_hci/common-hal/_bleio/UUID.h b/devices/ble_hci/common-hal/_bleio/UUID.h index 1a0ab91c44..59e09f7476 100644 --- a/devices/ble_hci/common-hal/_bleio/UUID.h +++ b/devices/ble_hci/common-hal/_bleio/UUID.h @@ -33,17 +33,17 @@ // Types returned by attribute table lookups. These are UUIDs. typedef enum { - BLE_UUID_UNKNOWN = 0x0000, - BLE_UUID_SERVICE_PRIMARY = 0x2800, - BLE_UUID_SERVICE_SECONDARY = 0x2801, - BLE_UUID_SERVICE_INCLUDE = 0x2802, // not yet implemented by us - BLE_UUID_CHARACTERISTIC = 0x2803, - BLE_UUID_CHAR_EXTENDED_PROPS = 0x2900, // not yet implemented by us - BLE_UUID_CHAR_USER_DESC = 0x2901, // not yet implemented by us - BLE_UUID_CCCD = 0x2902, - BLE_UUID_SCCD = 0x2903, // not yet implemented by us - BLE_UUID_CHAR_PRESENTATION_FMT = 0x2904, // not yet implemented by us - BLE_UUID_CHAR_AGGREGATE_FMT = 0x2905, // not yet implemented by us + BLE_UUID_UNKNOWN = 0x0000, + BLE_UUID_SERVICE_PRIMARY = 0x2800, + BLE_UUID_SERVICE_SECONDARY = 0x2801, + BLE_UUID_SERVICE_INCLUDE = 0x2802,// not yet implemented by us + BLE_UUID_CHARACTERISTIC = 0x2803, + BLE_UUID_CHAR_EXTENDED_PROPS = 0x2900,// not yet implemented by us + BLE_UUID_CHAR_USER_DESC = 0x2901,// not yet implemented by us + BLE_UUID_CCCD = 0x2902, + BLE_UUID_SCCD = 0x2903,// not yet implemented by us + BLE_UUID_CHAR_PRESENTATION_FMT = 0x2904, // not yet implemented by us + BLE_UUID_CHAR_AGGREGATE_FMT = 0x2905,// not yet implemented by us } ble_standard_uuid; typedef struct { diff --git a/devices/ble_hci/common-hal/_bleio/__init__.c b/devices/ble_hci/common-hal/_bleio/__init__.c index 8d6d764155..5b592de83a 100644 --- a/devices/ble_hci/common-hal/_bleio/__init__.c +++ b/devices/ble_hci/common-hal/_bleio/__init__.c @@ -78,7 +78,7 @@ void bleio_reset() { bleio_set_adapter(mp_const_none); - //FIX bonding_reset(); + // FIX bonding_reset(); supervisor_start_bluetooth(); } diff --git a/devices/ble_hci/common-hal/_bleio/__init__.h b/devices/ble_hci/common-hal/_bleio/__init__.h index cd9940bf06..18bf71834f 100644 --- a/devices/ble_hci/common-hal/_bleio/__init__.h +++ b/devices/ble_hci/common-hal/_bleio/__init__.h @@ -47,7 +47,7 @@ typedef struct { // 20 bytes max (23 - 3). #define GATT_MAX_DATA_LENGTH (BT_ATT_DEFAULT_LE_MTU - 3) -//FIX +// FIX #define BLE_GATT_HANDLE_INVALID 0x0000 #define BLE_CONN_HANDLE_INVALID 0xFFFF #define BLE_GATTS_FIX_ATTR_LEN_MAX (510) /**< Maximum length for fixed length Attribute Values. */ diff --git a/devices/ble_hci/common-hal/_bleio/att.c b/devices/ble_hci/common-hal/_bleio/att.c index 4573d5e9ff..5a3eb94737 100644 --- a/devices/ble_hci/common-hal/_bleio/att.c +++ b/devices/ble_hci/common-hal/_bleio/att.c @@ -24,8 +24,8 @@ #include "att.h" // Zephyr include files to define HCI communication values and structs. -//#include "hci_include/hci.h" -//#include "hci_include/hci_err.h" +// #include "hci_include/hci.h" +// #include "hci_include/hci_err.h" #include "hci_include/l2cap_internal.h" #include "py/obj.h" @@ -44,7 +44,7 @@ STATIC unsigned long timeout = 5000; STATIC volatile bool confirm; STATIC uint16_t long_write_handle = BLE_GATT_HANDLE_INVALID; -STATIC uint8_t* long_write_value = NULL; +STATIC uint8_t *long_write_value = NULL; STATIC uint16_t long_write_value_length = 0; // When we send a request, fill this struct with info about the expected response. @@ -52,7 +52,7 @@ STATIC uint16_t long_write_value_length = 0; STATIC struct { uint16_t conn_handle; // Expected handle. uint8_t opcode; // Expected RSP opcode. - uint8_t* buffer; // Pointer to response packet + uint8_t *buffer; // Pointer to response packet uint8_t length; // Length of response packet. } expected_rsp; @@ -88,7 +88,7 @@ STATIC uint8_t bleio_properties_to_ble_spec_properties(uint8_t bleio_properties) return ble_spec_properties; } -//FIX not currently used; reenable when used. +// FIX not currently used; reenable when used. #if 0 STATIC uint8_t ble_spec_properties_to_bleio_properties(uint8_t ble_spec_properties) { uint8_t bleio_properties = 0; @@ -120,20 +120,19 @@ STATIC void send_error(uint16_t conn_handle, uint8_t opcode, uint16_t handle, ui struct bt_att_hdr h; struct bt_att_error_rsp r; } rsp = { { - .code = BT_ATT_OP_ERROR_RSP, - }, { - .request = opcode, - } - }; + .code = BT_ATT_OP_ERROR_RSP, + }, { + .request = opcode, + }}; - hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, sizeof(rsp), (uint8_t *) &rsp); + hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, sizeof(rsp), (uint8_t *)&rsp); } -STATIC void send_req(uint16_t conn_handle, size_t request_length, uint8_t* request_buffer) { +STATIC void send_req(uint16_t conn_handle, size_t request_length, uint8_t *request_buffer) { hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, request_length, request_buffer); } -STATIC int send_req_wait_for_rsp(uint16_t conn_handle, size_t request_length, uint8_t* request_buffer, uint8_t response_buffer[]) { +STATIC int send_req_wait_for_rsp(uint16_t conn_handle, size_t request_length, uint8_t *request_buffer, uint8_t response_buffer[]) { // We expect a particular kind of response after this request. expected_rsp.conn_handle = conn_handle; // The response opcode is the request opcode + 1. @@ -192,9 +191,9 @@ void bleio_att_reset(void) { } bool att_connect_to_address(bt_addr_le_t *addr) { - //FIX + // FIX if (hci_le_create_conn(0x0060, 0x0030, 0x00, addr, 0x00, - 0x0006, 0x000c, 0x0000, 0x00c8, 0x0004, 0x0006) != 0) { + 0x0006, 0x000c, 0x0000, 0x00c8, 0x0004, 0x0006) != 0) { return false; } @@ -229,7 +228,7 @@ bool att_disconnect(uint16_t conn_handle) { return !att_handle_is_connected(conn_handle); } -//FIX +// FIX // STATIC bool discover_services(uint16_t conn_handle, BLERemoteDevice* device, const char* serviceUuidFilter) { // uint16_t reqStart_handle = 0x0001; // uint16_t reqEnd_handle = 0xffff; @@ -406,7 +405,7 @@ bool att_disconnect(uint16_t conn_handle) { // return true; // } -bool att_discover_attributes(bt_addr_le_t *addr, const char* service_uuid_filter) { +bool att_discover_attributes(bt_addr_le_t *addr, const char *service_uuid_filter) { uint16_t conn_handle = att_conn_handle(addr); if (conn_handle == 0xffff) { return false; @@ -418,7 +417,7 @@ bool att_discover_attributes(bt_addr_le_t *addr, const char* service_uuid_filter } // find the device entry for the peeer - //FIX BLERemoteDevice* device = NULL; + // FIX BLERemoteDevice* device = NULL; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { // if (bleio_connections[i].conn_handle == conn_handle) { @@ -454,7 +453,7 @@ bool att_discover_attributes(bt_addr_le_t *addr, const char* service_uuid_filter } // discover services - //FIX + // FIX // if (!att_discover_services(conn_handle, device, service_uuid_filter)) { // return false; // } @@ -481,10 +480,10 @@ void att_set_timeout(unsigned long timeout_in) { } void att_add_connection(uint16_t handle, uint8_t role, bt_addr_le_t *peer_addr, uint16_t interval, uint16_t latency, uint16_t supervision_timeout, uint8_t master_clock_accuracy) { - (void) interval; - (void) latency; - (void) supervision_timeout; - (void) master_clock_accuracy; + (void)interval; + (void)latency; + (void)supervision_timeout; + (void)master_clock_accuracy; int peer_index = -1; @@ -508,7 +507,7 @@ void att_add_connection(uint16_t handle, uint8_t role, bt_addr_le_t *peer_addr, void att_remove_connection(uint16_t conn_handle, uint8_t reason) { - (void) reason; + (void)reason; int peer_index = -1; int peer_count = 0; @@ -580,7 +579,7 @@ bool att_is_connected(void) { } bool att_address_is_connected(bt_addr_le_t *addr) { - return (att_conn_handle(addr) != 0xffff); + return att_conn_handle(addr) != 0xffff; } bool att_handle_is_connected(uint16_t handle) { @@ -624,10 +623,10 @@ bool att_disconnect_all(void) { bleio_connections[i].mtu = BT_ATT_DEFAULT_LE_MTU; } - return (num_disconnects > 0); + return num_disconnects > 0; } -bool att_notify(uint16_t handle, const uint8_t* value, int length) { +bool att_notify(uint16_t handle, const uint8_t *value, int length) { int num_notifications = 0; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { @@ -643,20 +642,21 @@ bool att_notify(uint16_t handle, const uint8_t* value, int length) { size_t allowed_length = MIN((uint16_t)(bleio_connections[i].mtu - sizeof(notify_t)), (uint16_t)length); uint8_t notify_bytes[sizeof(notify_t) + allowed_length]; - notify_t *notify = (notify_t *) notify_bytes; - notify->hdr.code = BT_ATT_OP_NOTIFY;; + notify_t *notify = (notify_t *)notify_bytes; + notify->hdr.code = BT_ATT_OP_NOTIFY; + ; notify->ntf.handle = handle; memcpy(notify->ntf.value, value, allowed_length); hci_send_acl_pkt(bleio_connections[i].conn_handle, BT_L2CAP_CID_ATT, - sizeof(notify_bytes), notify_bytes); + sizeof(notify_bytes), notify_bytes); num_notifications++; } - return (num_notifications > 0); + return num_notifications > 0; } -bool att_indicate(uint16_t handle, const uint8_t* value, int length) { +bool att_indicate(uint16_t handle, const uint8_t *value, int length) { int num_indications = 0; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { @@ -672,15 +672,16 @@ bool att_indicate(uint16_t handle, const uint8_t* value, int length) { size_t allowed_length = MIN((uint16_t)(bleio_connections[i].mtu - sizeof(indicate_t)), (uint16_t)length); uint8_t indicate_bytes[sizeof(indicate_t) + allowed_length]; - indicate_t *indicate = (indicate_t *) indicate_bytes; - indicate->hdr.code = BT_ATT_OP_INDICATE;; + indicate_t *indicate = (indicate_t *)indicate_bytes; + indicate->hdr.code = BT_ATT_OP_INDICATE; + ; indicate->ind.handle = handle; memcpy(indicate->ind.value, value, allowed_length); confirm = false; hci_send_acl_pkt(bleio_connections[i].conn_handle, BT_L2CAP_CID_ATT, - sizeof(indicate_bytes), indicate_bytes); + sizeof(indicate_bytes), indicate_bytes); while (!confirm) { // RUN_BACKGROUND_TASKS includes hci_poll_for_incoming_pkt(); @@ -694,11 +695,11 @@ bool att_indicate(uint16_t handle, const uint8_t* value, int length) { num_indications++; } - return (num_indications > 0); + return num_indications > 0; } STATIC void process_error(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { - struct bt_att_error_rsp *rsp = (struct bt_att_error_rsp *) data; + struct bt_att_error_rsp *rsp = (struct bt_att_error_rsp *)data; if (dlen != sizeof(struct bt_att_error_rsp)) { // Incorrect size; ignore. @@ -714,7 +715,7 @@ STATIC void process_error(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { } STATIC void process_mtu_req(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { - struct bt_att_exchange_mtu_req *req = (struct bt_att_exchange_mtu_req *) data; + struct bt_att_exchange_mtu_req *req = (struct bt_att_exchange_mtu_req *)data; if (dlen != sizeof(struct bt_att_exchange_mtu_req)) { send_error(conn_handle, BT_ATT_OP_MTU_REQ, BLE_GATT_HANDLE_INVALID, BT_ATT_ERR_INVALID_PDU); @@ -738,17 +739,16 @@ STATIC void process_mtu_req(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) struct bt_att_hdr h; struct bt_att_exchange_mtu_rsp r; } rsp = { { - .code = BT_ATT_OP_MTU_RSP, - }, { - .mtu = mtu, - } - }; + .code = BT_ATT_OP_MTU_RSP, + }, { + .mtu = mtu, + }}; - hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, sizeof(rsp), (uint8_t *) &rsp); + hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, sizeof(rsp), (uint8_t *)&rsp); } STATIC void process_mtu_rsp(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { - struct bt_att_exchange_mtu_rsp *rsp = (struct bt_att_exchange_mtu_rsp *) data; + struct bt_att_exchange_mtu_rsp *rsp = (struct bt_att_exchange_mtu_rsp *)data; if (dlen != sizeof(struct bt_att_exchange_mtu_rsp)) { return; @@ -765,7 +765,7 @@ STATIC void process_mtu_rsp(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) } STATIC void process_find_info_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, uint8_t data[]) { - struct bt_att_find_info_req *req = (struct bt_att_find_info_req *) data; + struct bt_att_find_info_req *req = (struct bt_att_find_info_req *)data; if (dlen != sizeof(struct bt_att_find_info_req)) { send_error(conn_handle, BT_ATT_OP_FIND_INFO_REQ, req->start_handle, BT_ATT_ERR_INVALID_PDU); @@ -778,7 +778,7 @@ STATIC void process_find_info_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl } rsp_t; uint8_t rsp_bytes[mtu]; - rsp_t *rsp = (rsp_t *) rsp_bytes; + rsp_t *rsp = (rsp_t *)rsp_bytes; rsp->h.code = BT_ATT_OP_FIND_INFO_RSP; // Keeps track of total length of the response. @@ -832,20 +832,20 @@ STATIC void process_find_info_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl } if (sizeof_uuid == 2) { - struct bt_att_info_16 *info_16 = (struct bt_att_info_16 *) &rsp_bytes[rsp_length]; + struct bt_att_info_16 *info_16 = (struct bt_att_info_16 *)&rsp_bytes[rsp_length]; info_16->handle = handle; info_16->uuid = common_hal_bleio_uuid_get_uuid16(uuid); rsp_length += sizeof(struct bt_att_info_16); } else { - struct bt_att_info_128 *info_128 = (struct bt_att_info_128 *) &rsp_bytes[rsp_length]; + struct bt_att_info_128 *info_128 = (struct bt_att_info_128 *)&rsp_bytes[rsp_length]; info_128->handle = handle; common_hal_bleio_uuid_get_uuid128(uuid, info_128->uuid); rsp_length += sizeof(struct bt_att_info_128); } - no_data =false; + no_data = false; } // end for @@ -861,14 +861,13 @@ int att_find_info_req(uint16_t conn_handle, uint16_t start_handle, uint16_t end_ struct bt_att_hdr h; struct bt_att_find_info_req r; } req = { { - .code = BT_ATT_OP_FIND_INFO_REQ, - }, { - .start_handle = start_handle, - .end_handle = end_handle, - } - }; + .code = BT_ATT_OP_FIND_INFO_REQ, + }, { + .start_handle = start_handle, + .end_handle = end_handle, + }}; - return send_req_wait_for_rsp(conn_handle, sizeof(req), (uint8_t *) &req, response_buffer); + return send_req_wait_for_rsp(conn_handle, sizeof(req), (uint8_t *)&req, response_buffer); } STATIC void process_find_info_rsp(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { @@ -880,7 +879,7 @@ STATIC void process_find_info_rsp(uint16_t conn_handle, uint8_t dlen, uint8_t da } STATIC void process_find_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, uint8_t data[]) { - struct bt_att_find_type_req *req = (struct bt_att_find_type_req *) data; + struct bt_att_find_type_req *req = (struct bt_att_find_type_req *)data; if (dlen < sizeof(struct bt_att_find_type_req)) { send_error(conn_handle, BT_ATT_OP_FIND_TYPE_RSP, req->start_handle, BT_ATT_ERR_INVALID_PDU); @@ -893,7 +892,7 @@ STATIC void process_find_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl response[0] = BT_ATT_OP_FIND_TYPE_RSP; response_length = 1; - //FIX + // FIX // if (find_type_req->type == BLE_UUID_SERVICE_PRIMARY) { // for (uint16_t i = (find_type_req->start_handle - 1); i < GATT.attributeCount() && i <= (find_type_req->end_handle - 1); i++) { // BLELocalAttribute* attribute = GATT.attribute(i); @@ -926,7 +925,7 @@ STATIC void process_find_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl } void process_read_group_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, uint8_t data[]) { - struct bt_att_read_group_req *req = (struct bt_att_read_group_req *) data; + struct bt_att_read_group_req *req = (struct bt_att_read_group_req *)data; uint16_t type_uuid = req->uuid[0] | (req->uuid[1] << 8); // We only support returning services for BT_ATT_OP_READ_GROUP_REQ, which is typically used @@ -944,7 +943,7 @@ void process_read_group_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, ui } rsp_t; uint8_t rsp_bytes[mtu]; - rsp_t *rsp = (rsp_t *) rsp_bytes; + rsp_t *rsp = (rsp_t *)rsp_bytes; rsp->h.code = BT_ATT_OP_READ_GROUP_RSP; rsp->r.len = 0; @@ -991,7 +990,7 @@ void process_read_group_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, ui // There may be multiple chunks in this transmission. rsp->r.len = data_length; - struct bt_att_group_data *group_data = (struct bt_att_group_data *) &rsp_bytes[rsp_length]; + struct bt_att_group_data *group_data = (struct bt_att_group_data *)&rsp_bytes[rsp_length]; group_data->start_handle = service->start_handle; group_data->end_handle = service->end_handle; @@ -1017,7 +1016,7 @@ int att_read_group_req(uint16_t conn_handle, uint16_t start_handle, uint16_t end } req_t; uint8_t req_bytes[sizeof(req_t) + sizeof(uuid)]; - req_t *req = (req_t *) req_bytes; + req_t *req = (req_t *)req_bytes; req->h.code = BT_ATT_OP_READ_GROUP_REQ; req->r.start_handle = start_handle; @@ -1047,7 +1046,7 @@ STATIC void process_read_or_read_blob_req(uint16_t conn_handle, uint16_t mtu, ui return; } - struct bt_att_read_req *req = (struct bt_att_read_req *) data; + struct bt_att_read_req *req = (struct bt_att_read_req *)data; handle = req->handle; response_opcode = BT_ATT_OP_READ_RSP; @@ -1057,7 +1056,7 @@ STATIC void process_read_or_read_blob_req(uint16_t conn_handle, uint16_t mtu, ui return; } - struct bt_att_read_blob_req *req = (struct bt_att_read_blob_req *) data; + struct bt_att_read_blob_req *req = (struct bt_att_read_blob_req *)data; handle = req->handle; offset = req->offset; response_opcode = BT_ATT_OP_READ_BLOB_RSP; @@ -1077,7 +1076,7 @@ STATIC void process_read_or_read_blob_req(uint16_t conn_handle, uint16_t mtu, ui } rsp_t; uint8_t rsp_bytes[mtu]; - rsp_t *rsp = (rsp_t *) rsp_bytes; + rsp_t *rsp = (rsp_t *)rsp_bytes; rsp->h.code = response_opcode; // Keeps track of total length of the response. @@ -1105,7 +1104,7 @@ STATIC void process_read_or_read_blob_req(uint16_t conn_handle, uint16_t mtu, ui return; } - characteristic_declaration_t *char_decl = (characteristic_declaration_t *) rsp->r.value; + characteristic_declaration_t *char_decl = (characteristic_declaration_t *)rsp->r.value; // Convert from the bleio properties bit values to the BLE spec properties bit values. // They are not the same :(. @@ -1160,7 +1159,7 @@ STATIC void process_read_rsp(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) } STATIC void process_read_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, uint8_t data[]) { - struct bt_att_read_type_req *req = (struct bt_att_read_type_req *) data; + struct bt_att_read_type_req *req = (struct bt_att_read_type_req *)data; uint16_t type_uuid = req->uuid[0] | (req->uuid[1] << 8); if (dlen != sizeof(struct bt_att_read_type_req) + sizeof(type_uuid)) { @@ -1174,7 +1173,7 @@ STATIC void process_read_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl } rsp_t; uint8_t rsp_bytes[mtu]; - rsp_t *rsp = (rsp_t *) rsp_bytes; + rsp_t *rsp = (rsp_t *)rsp_bytes; rsp->h.code = BT_ATT_OP_READ_TYPE_RSP; rsp->r.len = 0; @@ -1233,11 +1232,11 @@ STATIC void process_read_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl // There may be multiple chunks in this transmission. rsp->r.len = data_length; - struct bt_att_data *att_data = (struct bt_att_data *) &rsp_bytes[rsp_length]; + struct bt_att_data *att_data = (struct bt_att_data *)&rsp_bytes[rsp_length]; att_data->handle = characteristic->decl_handle; - characteristic_declaration_t *char_decl = (characteristic_declaration_t *) att_data->value; + characteristic_declaration_t *char_decl = (characteristic_declaration_t *)att_data->value; // Convert from the bleio properties bit values to the BLE spec properties bit values. // They are not the same :(. @@ -1255,7 +1254,7 @@ STATIC void process_read_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl // See if request is for a descriptor value with a 16-bit UUID, such as the CCCD. bleio_descriptor_obj_t *descriptor = MP_OBJ_TO_PTR(attribute_obj); if (bleio_uuid_get_uuid16_or_unknown(descriptor->uuid) == type_uuid) { - struct bt_att_data *att_data = (struct bt_att_data *) &rsp_bytes[rsp_length]; + struct bt_att_data *att_data = (struct bt_att_data *)&rsp_bytes[rsp_length]; att_data->handle = handle; @@ -1277,7 +1276,7 @@ STATIC void process_read_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl bleio_characteristic_obj_t *characteristic = MP_OBJ_TO_PTR(attribute_obj); if (bleio_uuid_get_uuid16_or_unknown(characteristic->uuid) == type_uuid) { - struct bt_att_data *att_data = (struct bt_att_data *) &rsp_bytes[rsp_length]; + struct bt_att_data *att_data = (struct bt_att_data *)&rsp_bytes[rsp_length]; att_data->handle = handle; @@ -1299,7 +1298,7 @@ STATIC void process_read_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl if (no_data) { send_error(conn_handle, BT_ATT_OP_READ_TYPE_REQ, - req->start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); + req->start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); } else { hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, rsp_length, rsp_bytes); } @@ -1312,7 +1311,7 @@ int att_read_type_req(uint16_t conn_handle, uint16_t start_handle, uint16_t end_ } req_t; uint8_t req_bytes[sizeof(req_t) + sizeof(type)]; - req_t *req = (req_t *) req_bytes; + req_t *req = (req_t *)req_bytes; req->h.code = BT_ATT_OP_READ_TYPE_REQ; req->r.start_handle = start_handle; @@ -1334,7 +1333,7 @@ STATIC void process_read_type_rsp(uint16_t conn_handle, uint8_t dlen, uint8_t da // Handles BT_ATT_OP_WRITE_REQ or BT_ATT_OP_WRITE_ STATIC void process_write_req_or_cmd(uint16_t conn_handle, uint16_t mtu, uint8_t op, uint8_t dlen, uint8_t data[]) { // struct bt_att_write_cmd is identical, so don't bother to split code paths based on opcode. - struct bt_att_write_req *req = (struct bt_att_write_req *) data; + struct bt_att_write_req *req = (struct bt_att_write_req *)data; bool with_response = (op == BT_ATT_OP_WRITE_REQ); @@ -1397,7 +1396,7 @@ STATIC void process_write_req_or_cmd(uint16_t conn_handle, uint16_t mtu, uint8_t .code = BT_ATT_OP_WRITE_RSP, }; - hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, sizeof(rsp), (uint8_t *) &rsp); + hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, sizeof(rsp), (uint8_t *)&rsp); } } @@ -1410,7 +1409,7 @@ STATIC void process_write_rsp(uint16_t conn_handle, uint8_t dlen, uint8_t data[] } STATIC void process_prepare_write_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, uint8_t data[]) { - struct bt_att_prepare_write_req *req = (struct bt_att_prepare_write_req *) data; + struct bt_att_prepare_write_req *req = (struct bt_att_prepare_write_req *)data; if (dlen < sizeof(struct bt_att_prepare_write_req)) { send_error(conn_handle, BT_ATT_OP_PREPARE_WRITE_REQ, BLE_GATT_HANDLE_INVALID, BT_ATT_ERR_INVALID_PDU); @@ -1419,7 +1418,7 @@ STATIC void process_prepare_write_req(uint16_t conn_handle, uint16_t mtu, uint8_ uint16_t handle = req->handle; uint16_t offset = req->offset; - (void) offset; + (void)offset; if (handle > bleio_adapter_max_attribute_handle(&common_hal_bleio_adapter_obj)) { send_error(conn_handle, BT_ATT_OP_PREPARE_WRITE_REQ, handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); @@ -1433,7 +1432,7 @@ STATIC void process_prepare_write_req(uint16_t conn_handle, uint16_t mtu, uint8_ return; } - bleio_characteristic_obj_t* characteristic = MP_OBJ_TO_PTR(attribute); + bleio_characteristic_obj_t *characteristic = MP_OBJ_TO_PTR(attribute); if (handle != characteristic->handle) { send_error(conn_handle, BT_ATT_OP_PREPARE_WRITE_REQ, handle, BT_ATT_ERR_ATTRIBUTE_NOT_LONG); @@ -1445,7 +1444,7 @@ STATIC void process_prepare_write_req(uint16_t conn_handle, uint16_t mtu, uint8_ return; } - //FIX if (long_write_handle == BLE_GATT_HANDLE_INVALID) + // FIX if (long_write_handle == BLE_GATT_HANDLE_INVALID) // int valueSize = characteristic->valueSize(); // long_write_value = (uint8_t*)realloc(long_write_value, valueSize); @@ -1480,7 +1479,7 @@ STATIC void process_prepare_write_req(uint16_t conn_handle, uint16_t mtu, uint8_ } STATIC void process_exec_write_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, uint8_t data[]) { - struct bt_att_exec_write_req *req = (struct bt_att_exec_write_req *) data; + struct bt_att_exec_write_req *req = (struct bt_att_exec_write_req *)data; if (dlen != sizeof(struct bt_att_exec_write_req)) { send_error(conn_handle, BT_ATT_OP_EXEC_WRITE_REQ, BLE_GATT_HANDLE_INVALID, BT_ATT_ERR_INVALID_PDU); @@ -1488,11 +1487,11 @@ STATIC void process_exec_write_req(uint16_t conn_handle, uint16_t mtu, uint8_t d } if (long_write_handle && (req->flags & 0x01)) { - //FIX BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)GATT.attribute(long_write_handle - 1); + // FIX BLELocalCharacteristic* characteristic = (BLELocalCharacteristic*)GATT.attribute(long_write_handle - 1); for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { if (bleio_connections[i].conn_handle == conn_handle) { - //FIX characteristic->writeValue(BLEDevice(bleio_connections[i].address_type, bleio_connections[i].address), long_write_value, long_write_value_length); + // FIX characteristic->writeValue(BLEDevice(bleio_connections[i].address_type, bleio_connections[i].address), long_write_value, long_write_value_length); break; } } @@ -1516,16 +1515,16 @@ STATIC void process_notify_or_indicate(uint16_t conn_handle, uint8_t opcode, uin } // struct bt_att_notify and bt_att_indicate are identical. - //FIXunused struct bt_att_notify *req = (struct bt_att_notify *) data; + // FIXunused struct bt_att_notify *req = (struct bt_att_notify *) data; - //FIXunused uint8_t handle = req->handle; + // FIXunused uint8_t handle = req->handle; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { if (bleio_connections[i].conn_handle != conn_handle) { continue; } - //FIX BLERemoteDevice* device = bleio_connections[i].device; + // FIX BLERemoteDevice* device = bleio_connections[i].device; // if (!device) { // break; @@ -1562,9 +1561,9 @@ STATIC void process_notify_or_indicate(uint16_t conn_handle, uint8_t opcode, uin } STATIC void process_confirm(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { - (void) conn_handle; - (void) dlen; - (void) data; + (void)conn_handle; + (void)dlen; + (void)data; confirm = true; } @@ -1574,7 +1573,7 @@ bool att_exchange_mtu(uint16_t conn_handle) { struct bt_att_exchange_mtu_req req = { .mtu = max_mtu, }; - return send_req_wait_for_rsp(conn_handle, sizeof(req), (uint8_t *) &req, response_buffer); + return send_req_wait_for_rsp(conn_handle, sizeof(req), (uint8_t *)&req, response_buffer); } int att_read_req(uint16_t conn_handle, uint16_t handle, uint8_t response_buffer[]) { @@ -1582,23 +1581,22 @@ int att_read_req(uint16_t conn_handle, uint16_t handle, uint8_t response_buffer[ struct bt_att_hdr h; struct bt_att_read_req r; } req = { { - .code = BT_ATT_OP_READ_REQ, - }, { - .handle = handle, - } - }; + .code = BT_ATT_OP_READ_REQ, + }, { + .handle = handle, + }}; - return send_req_wait_for_rsp(conn_handle, sizeof(req), (uint8_t *) &req, response_buffer); + return send_req_wait_for_rsp(conn_handle, sizeof(req), (uint8_t *)&req, response_buffer); } -int att_write_req(uint16_t conn_handle, uint16_t handle, const uint8_t* data, uint8_t data_len, uint8_t response_buffer[]) { +int att_write_req(uint16_t conn_handle, uint16_t handle, const uint8_t *data, uint8_t data_len, uint8_t response_buffer[]) { typedef struct __packed { struct bt_att_hdr h; struct bt_att_write_req r; } req_t; uint8_t req_bytes[sizeof(req_t) + data_len]; - req_t *req = (req_t *) req_bytes; + req_t *req = (req_t *)req_bytes; req->h.code = BT_ATT_OP_WRITE_REQ; req->r.handle = handle; memcpy(req->r.value, data, data_len); @@ -1606,14 +1604,14 @@ int att_write_req(uint16_t conn_handle, uint16_t handle, const uint8_t* data, ui return send_req_wait_for_rsp(conn_handle, sizeof(req_bytes), req_bytes, response_buffer); } -void att_write_cmd(uint16_t conn_handle, uint16_t handle, const uint8_t* data, uint8_t data_len) { +void att_write_cmd(uint16_t conn_handle, uint16_t handle, const uint8_t *data, uint8_t data_len) { typedef struct __packed { struct bt_att_hdr h; struct bt_att_write_cmd r; } cmd_t; uint8_t cmd_bytes[sizeof(cmd_t) + data_len]; - cmd_t *cmd = (cmd_t *) cmd_bytes; + cmd_t *cmd = (cmd_t *)cmd_bytes; cmd->h.code = BT_ATT_OP_WRITE_CMD; cmd->r.handle = handle; memcpy(cmd->r.value, data, data_len); @@ -1715,7 +1713,7 @@ void att_process_data(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { } } -//FIX Do we need all of these? +// FIX Do we need all of these? void check_att_err(uint8_t err) { const compressed_string_t *msg = NULL; switch (err) { diff --git a/devices/ble_hci/common-hal/_bleio/att.h b/devices/ble_hci/common-hal/_bleio/att.h index b34b74dc37..e8fdd53fd1 100644 --- a/devices/ble_hci/common-hal/_bleio/att.h +++ b/devices/ble_hci/common-hal/_bleio/att.h @@ -32,19 +32,19 @@ void bleio_att_reset(void); -//FIX void att_set_event_handler(BLEDeviceEvent event, BLEDeviceEventHandler eventHandler); +// FIX void att_set_event_handler(BLEDeviceEvent event, BLEDeviceEventHandler eventHandler); bool att_address_is_connected(bt_addr_le_t *addr); bool att_connect_to_address(bt_addr_le_t *addr); bool att_disconnect(uint16_t conn_handle); bool att_disconnect_all(void); -bool att_discover_attributes(bt_addr_le_t *addr, const char* service_uuid_filter); +bool att_discover_attributes(bt_addr_le_t *addr, const char *service_uuid_filter); bool att_exchange_mtu(uint16_t conn_handle); bool att_handle_is_connected(uint16_t handle); -bool att_indicate(uint16_t handle, const uint8_t* value, int length); +bool att_indicate(uint16_t handle, const uint8_t *value, int length); bool att_is_connected(void); -bool att_notify(uint16_t handle, const uint8_t* value, int length); +bool att_notify(uint16_t handle, const uint8_t *value, int length); int att_read_req(uint16_t conn_handle, uint16_t handle, uint8_t response_buffer[]); -int att_write_req(uint16_t conn_handle, uint16_t handle, const uint8_t* data, uint8_t data_len, uint8_t response_buffer[]); +int att_write_req(uint16_t conn_handle, uint16_t handle, const uint8_t *data, uint8_t data_len, uint8_t response_buffer[]); uint16_t att_conn_handle(bt_addr_le_t *addr); uint16_t att_mtu(uint16_t handle); void att_add_connection(uint16_t handle, uint8_t role, bt_addr_le_t *peer_addr, uint16_t interval, uint16_t latency, uint16_t supervision_timeout, uint8_t master_clock_accuracy); @@ -52,6 +52,6 @@ void att_process_data(uint16_t conn_handle, uint8_t dlen, uint8_t data[]); void att_remove_connection(uint16_t conn_handle, uint8_t reason); void att_set_max_mtu(uint16_t max_mtu); void att_set_timeout(unsigned long timeout); -void att_write_cmd(uint16_t conn_handle, uint16_t handle, const uint8_t* data, uint8_t data_len); +void att_write_cmd(uint16_t conn_handle, uint16_t handle, const uint8_t *data, uint8_t data_len); #endif // MICROPY_INCLUDED_DEVICES_BLE_HCI_COMMON_HAL_BLEIO_ATT_H diff --git a/devices/ble_hci/common-hal/_bleio/hci.c b/devices/ble_hci/common-hal/_bleio/hci.c index e261a98475..ec1663589d 100644 --- a/devices/ble_hci/common-hal/_bleio/hci.c +++ b/devices/ble_hci/common-hal/_bleio/hci.c @@ -27,7 +27,7 @@ #include -#include "py/mphal.h" //***************************** +#include "py/mphal.h" // ***************************** #include "supervisor/shared/tick.h" #include "shared-bindings/_bleio/__init__.h" #include "common-hal/_bleio/Adapter.h" @@ -63,8 +63,8 @@ typedef struct __attribute__ ((packed)) { typedef struct __attribute__ ((packed)) { uint8_t pkt_type; uint16_t handle : 12; - uint8_t pb: 2; // Packet boundary flag: ACL_DATA_PB values. - uint8_t bc: 2; // Broadcast flag: always 0b00 for BLE. + uint8_t pb : 2; // Packet boundary flag: ACL_DATA_PB values. + uint8_t bc : 2; // Broadcast flag: always 0b00 for BLE. uint16_t data_len; // length of data[] in this packet. uint8_t data[]; } h4_hci_acl_pkt_t; @@ -89,7 +89,7 @@ typedef struct __attribute__ ((packed)) { ////////////////////////////////////////////////////////////////////// // Static storage: -//FIX size +// FIX size #define RX_BUFFER_SIZE (3 + 255) #define ACL_DATA_BUFFER_SIZE (255) @@ -107,7 +107,7 @@ STATIC bool cmd_response_received; STATIC uint16_t cmd_response_opcode; STATIC uint8_t cmd_response_status; STATIC size_t cmd_response_len; -STATIC uint8_t* cmd_response_data; +STATIC uint8_t *cmd_response_data; STATIC volatile bool hci_poll_in_progress = false; @@ -119,7 +119,7 @@ STATIC volatile bool hci_poll_in_progress = false; #endif // HCI_DEBUG STATIC void process_acl_data_pkt(uint8_t pkt_len, uint8_t pkt_data[]) { - h4_hci_acl_pkt_t *pkt = (h4_hci_acl_pkt_t*) pkt_data; + h4_hci_acl_pkt_t *pkt = (h4_hci_acl_pkt_t *)pkt_data; if (pkt->pb != ACL_DATA_PB_MIDDLE) { // This is the start of a fragmented acl_data packet or is a full packet. @@ -132,7 +132,7 @@ STATIC void process_acl_data_pkt(uint8_t pkt_len, uint8_t pkt_data[]) { acl_data_len += pkt->data_len; } - acl_data_t *acl = (acl_data_t *) &acl_data_buffer; + acl_data_t *acl = (acl_data_t *)&acl_data_buffer; if (acl_data_len != sizeof(acl) + acl->acl_data_len) { // We don't have the full packet yet. return; @@ -167,18 +167,17 @@ STATIC void process_num_comp_pkts(uint16_t handle, uint16_t num_pkts) { } } -STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) -{ - h4_hci_evt_pkt_t *pkt = (h4_hci_evt_pkt_t*) pkt_data; +STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) { + h4_hci_evt_pkt_t *pkt = (h4_hci_evt_pkt_t *)pkt_data; switch (pkt->evt) { case BT_HCI_EVT_DISCONN_COMPLETE: { struct bt_hci_evt_disconn_complete *disconn_complete = - (struct bt_hci_evt_disconn_complete*) pkt->params; - (void) disconn_complete; + (struct bt_hci_evt_disconn_complete *)pkt->params; + (void)disconn_complete; att_remove_connection(disconn_complete->handle, disconn_complete->reason); - //FIX L2CAPSignaling.removeConnection(disconn_complete->handle, disconn_complete->reason); + // FIX L2CAPSignaling.removeConnection(disconn_complete->handle, disconn_complete->reason); break; } @@ -188,7 +187,7 @@ STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) struct bt_hci_evt_cc_status cc_status; } __packed; - struct cmd_complete_with_status *evt = (struct cmd_complete_with_status *) pkt->params; + struct cmd_complete_with_status *evt = (struct cmd_complete_with_status *)pkt->params; num_command_packets_allowed = evt->cmd_complete.ncmd; @@ -197,7 +196,7 @@ STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) cmd_response_status = evt->cc_status.status; // All the bytes following cmd_complete, -including- the status byte, which is // included in all the _bt_hci_rp_* structs. - cmd_response_data = (uint8_t *) &evt->cc_status; + cmd_response_data = (uint8_t *)&evt->cc_status; // Includes status byte. cmd_response_len = pkt->param_len - sizeof_field(struct cmd_complete_with_status, cmd_complete); @@ -205,7 +204,7 @@ STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) } case BT_HCI_EVT_CMD_STATUS: { - struct bt_hci_evt_cmd_status *evt = (struct bt_hci_evt_cmd_status *) pkt->params; + struct bt_hci_evt_cmd_status *evt = (struct bt_hci_evt_cmd_status *)pkt->params; num_command_packets_allowed = evt->ncmd; @@ -220,7 +219,7 @@ STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) case BT_HCI_EVT_NUM_COMPLETED_PACKETS: { struct bt_hci_evt_num_completed_packets *evt = - (struct bt_hci_evt_num_completed_packets *) pkt->params; + (struct bt_hci_evt_num_completed_packets *)pkt->params; // Start at zero-th pair: (conn handle, num completed packets). struct bt_hci_handle_count *handle_and_count = &(evt->h[0]); @@ -232,8 +231,8 @@ STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) } case BT_HCI_EVT_LE_META_EVENT: { - struct bt_hci_evt_le_meta_event *meta_evt = (struct bt_hci_evt_le_meta_event *) pkt->params; - uint8_t *le_evt = pkt->params + sizeof (struct bt_hci_evt_le_meta_event); + struct bt_hci_evt_le_meta_event *meta_evt = (struct bt_hci_evt_le_meta_event *)pkt->params; + uint8_t *le_evt = pkt->params + sizeof (struct bt_hci_evt_le_meta_event); if (meta_evt->subevent == BT_HCI_EVT_LE_CONN_COMPLETE) { // Advertising stops when connection occurs. @@ -243,7 +242,7 @@ STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) bleio_adapter_advertising_was_stopped(&common_hal_bleio_adapter_obj); struct bt_hci_evt_le_conn_complete *le_conn_complete = - (struct bt_hci_evt_le_conn_complete *) le_evt; + (struct bt_hci_evt_le_conn_complete *)le_evt; if (le_conn_complete->status == BT_HCI_ERR_SUCCESS) { att_add_connection( @@ -258,9 +257,9 @@ STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) } } else if (meta_evt->subevent == BT_HCI_EVT_LE_ADVERTISING_REPORT) { struct bt_hci_evt_le_advertising_info *le_advertising_info = - (struct bt_hci_evt_le_advertising_info *) le_evt; + (struct bt_hci_evt_le_advertising_info *)le_evt; if (le_advertising_info->evt_type == BT_HCI_ADV_DIRECT_IND) { - //FIX + // FIX // last byte is RSSI // GAP.handleLeAdvertisingReport(leAdvertisingReport->type, // leAdvertisingReport->peerBdaddrType, @@ -275,9 +274,9 @@ STATIC void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) } default: -#if HCI_DEBUG + #if HCI_DEBUG mp_printf(&mp_plat_print, "process_evt_pkt: Unknown event: %02x\n"); -#endif + #endif break; } } @@ -333,7 +332,7 @@ hci_result_t hci_poll_for_incoming_pkt(void) { case H4_ACL: if (rx_idx >= sizeof(h4_hci_acl_pkt_t)) { const size_t total_len = - sizeof(h4_hci_acl_pkt_t) + ((h4_hci_acl_pkt_t *) rx_buffer)->data_len; + sizeof(h4_hci_acl_pkt_t) + ((h4_hci_acl_pkt_t *)rx_buffer)->data_len; if (rx_idx == total_len) { packet_is_complete = true; } @@ -346,7 +345,7 @@ hci_result_t hci_poll_for_incoming_pkt(void) { case H4_EVT: if (rx_idx >= sizeof(h4_hci_evt_pkt_t)) { const size_t total_len = - sizeof(h4_hci_evt_pkt_t) + ((h4_hci_evt_pkt_t *) rx_buffer)->param_len; + sizeof(h4_hci_evt_pkt_t) + ((h4_hci_evt_pkt_t *)rx_buffer)->param_len; if (rx_idx == total_len) { packet_is_complete = true; } @@ -374,23 +373,23 @@ hci_result_t hci_poll_for_incoming_pkt(void) { switch (rx_buffer[0]) { case H4_ACL: -#if HCI_DEBUG + #if HCI_DEBUG dump_acl_pkt(false, pkt_len, rx_buffer); -#endif + #endif process_acl_data_pkt(pkt_len, rx_buffer); break; case H4_EVT: -#if HCI_DEBUG + #if HCI_DEBUG dump_evt_pkt(false, pkt_len, rx_buffer); -#endif + #endif process_evt_pkt(pkt_len, rx_buffer); break; default: -#if HCI_DEBUG + #if HCI_DEBUG mp_printf(&mp_plat_print, "Unknown HCI packet type: %d\n", rx_buffer[0]); -#endif + #endif break; } @@ -425,21 +424,21 @@ STATIC hci_result_t write_pkt(uint8_t *buffer, size_t len) { return HCI_OK; } -STATIC hci_result_t send_command(uint16_t opcode, uint8_t params_len, void* params) { +STATIC hci_result_t send_command(uint16_t opcode, uint8_t params_len, void *params) { uint8_t cmd_pkt_len = sizeof(h4_hci_cmd_pkt_t) + params_len; uint8_t tx_buffer[cmd_pkt_len]; // cmd header is at the beginning of tx_buffer - h4_hci_cmd_pkt_t *cmd_pkt = (h4_hci_cmd_pkt_t *) tx_buffer; + h4_hci_cmd_pkt_t *cmd_pkt = (h4_hci_cmd_pkt_t *)tx_buffer; cmd_pkt->pkt_type = H4_CMD; cmd_pkt->opcode = opcode; cmd_pkt->param_len = params_len; memcpy(cmd_pkt->params, params, params_len); -#if HCI_DEBUG - dump_cmd_pkt(true, sizeof(tx_buffer), tx_buffer); -#endif + #if HCI_DEBUG + dump_cmd_pkt(true, sizeof(tx_buffer), tx_buffer); + #endif int result = write_pkt(tx_buffer, cmd_pkt_len); if (result != HCI_OK) { @@ -478,8 +477,8 @@ hci_result_t hci_send_acl_pkt(uint16_t handle, uint8_t cid, uint16_t data_len, u const size_t buf_len = sizeof(h4_hci_acl_pkt_t) + sizeof(acl_data_t) + data_len; uint8_t tx_buffer[buf_len]; - h4_hci_acl_pkt_t *acl_pkt = (h4_hci_acl_pkt_t *) tx_buffer; - acl_data_t *acl_data = (acl_data_t *) acl_pkt->data; + h4_hci_acl_pkt_t *acl_pkt = (h4_hci_acl_pkt_t *)tx_buffer; + acl_data_t *acl_data = (acl_data_t *)acl_pkt->data; acl_pkt->pkt_type = H4_ACL; acl_pkt->handle = handle; acl_pkt->pb = ACL_DATA_PB_FIRST_FLUSH; @@ -490,9 +489,9 @@ hci_result_t hci_send_acl_pkt(uint16_t handle, uint8_t cid, uint16_t data_len, u memcpy(&acl_data->acl_data, data, data_len); -#if HCI_DEBUG - dump_acl_pkt(true, buf_len, tx_buffer); -#endif + #if HCI_DEBUG + dump_acl_pkt(true, buf_len, tx_buffer); + #endif pending_pkt++; @@ -512,7 +511,7 @@ hci_result_t hci_read_local_version(uint8_t *hci_version, uint16_t *hci_revision hci_result_t result = send_command(BT_HCI_OP_READ_LOCAL_VERSION_INFO, 0, NULL); if (result == HCI_OK) { struct bt_hci_rp_read_local_version_info *response = - (struct bt_hci_rp_read_local_version_info *) cmd_response_data; + (struct bt_hci_rp_read_local_version_info *)cmd_response_data; *hci_version = response->hci_version; *hci_revision = response->hci_revision; *lmp_version = response->lmp_version; @@ -526,7 +525,7 @@ hci_result_t hci_read_local_version(uint8_t *hci_version, uint16_t *hci_revision hci_result_t hci_read_bd_addr(bt_addr_t *addr) { int result = send_command(BT_HCI_OP_READ_BD_ADDR, 0, NULL); if (result == HCI_OK) { - struct bt_hci_rp_read_bd_addr *response = (struct bt_hci_rp_read_bd_addr *) cmd_response_data; + struct bt_hci_rp_read_bd_addr *response = (struct bt_hci_rp_read_bd_addr *)cmd_response_data; memcpy(addr->val, response->bdaddr.val, sizeof_field(bt_addr_t, val)); } @@ -536,7 +535,7 @@ hci_result_t hci_read_bd_addr(bt_addr_t *addr) { hci_result_t hci_read_rssi(uint16_t handle, int *rssi) { int result = send_command(BT_HCI_OP_READ_RSSI, sizeof(handle), &handle); if (result == HCI_OK) { - struct bt_hci_rp_read_rssi *response = (struct bt_hci_rp_read_rssi *) cmd_response_data; + struct bt_hci_rp_read_rssi *response = (struct bt_hci_rp_read_rssi *)cmd_response_data; *rssi = response->rssi; } @@ -551,7 +550,7 @@ hci_result_t hci_le_read_buffer_size(uint16_t *le_max_len, uint8_t *le_max_num) int result = send_command(BT_HCI_OP_LE_READ_BUFFER_SIZE, 0, NULL); if (result == HCI_OK) { struct bt_hci_rp_le_read_buffer_size *response = - (struct bt_hci_rp_le_read_buffer_size *) cmd_response_data; + (struct bt_hci_rp_le_read_buffer_size *)cmd_response_data; *le_max_len = response->le_max_len; *le_max_num = response->le_max_num; } @@ -563,7 +562,7 @@ hci_result_t hci_read_buffer_size(uint16_t *acl_max_len, uint8_t *sco_max_len, u int result = send_command(BT_HCI_OP_READ_BUFFER_SIZE, 0, NULL); if (result == HCI_OK) { struct bt_hci_rp_read_buffer_size *response = - (struct bt_hci_rp_read_buffer_size *) cmd_response_data; + (struct bt_hci_rp_read_buffer_size *)cmd_response_data; *acl_max_len = response->acl_max_len; *sco_max_len = response->sco_max_len; *acl_max_num = response->acl_max_num; @@ -608,10 +607,10 @@ hci_result_t hci_le_set_extended_advertising_parameters(uint8_t handle, uint16_t .scan_req_notify_enable = scan_req_notify_enable, }; // Assumes little-endian. - memcpy(params.prim_min_interval, (void *) &prim_min_interval, - sizeof_field(struct bt_hci_cp_le_set_ext_adv_param, prim_min_interval)); - memcpy(params.prim_max_interval, (void *) &prim_max_interval, - sizeof_field(struct bt_hci_cp_le_set_ext_adv_param, prim_max_interval)); + memcpy(params.prim_min_interval, (void *)&prim_min_interval, + sizeof_field(struct bt_hci_cp_le_set_ext_adv_param, prim_min_interval)); + memcpy(params.prim_max_interval, (void *)&prim_max_interval, + sizeof_field(struct bt_hci_cp_le_set_ext_adv_param, prim_max_interval)); memcpy(params.peer_addr.a.val, peer_addr->a.val, sizeof_field(bt_addr_le_t, a.val)); return send_command(BT_HCI_OP_LE_SET_EXT_ADV_PARAM, sizeof(params), ¶ms); } @@ -620,7 +619,7 @@ hci_result_t hci_le_read_maximum_advertising_data_length(uint16_t *max_adv_data_ int result = send_command(BT_HCI_OP_LE_READ_MAX_ADV_DATA_LEN, 0, NULL); if (result == HCI_OK) { struct bt_hci_rp_le_read_max_adv_data_len *response = - (struct bt_hci_rp_le_read_max_adv_data_len *) cmd_response_data; + (struct bt_hci_rp_le_read_max_adv_data_len *)cmd_response_data; *max_adv_data_len = response->max_adv_data_len; } @@ -631,9 +630,9 @@ hci_result_t hci_le_read_local_supported_features(uint8_t features[8]) { int result = send_command(BT_HCI_OP_LE_READ_LOCAL_FEATURES, 0, NULL); if (result == HCI_OK) { struct bt_hci_rp_le_read_local_features *response = - (struct bt_hci_rp_le_read_local_features *) cmd_response_data; + (struct bt_hci_rp_le_read_local_features *)cmd_response_data; memcpy(features, response->features, - sizeof_field(struct bt_hci_rp_le_read_local_features, features)); + sizeof_field(struct bt_hci_rp_le_read_local_features, features)); } return result; @@ -685,7 +684,7 @@ hci_result_t hci_le_set_advertising_enable(uint8_t enable) { hci_result_t hci_le_set_extended_advertising_enable(uint8_t enable, uint8_t set_num, uint8_t handle[], uint16_t duration[], uint8_t max_ext_adv_evts[]) { uint8_t params[sizeof(struct bt_hci_cp_le_set_ext_adv_enable) + set_num * (sizeof(struct bt_hci_ext_adv_set))]; - struct bt_hci_cp_le_set_ext_adv_enable *params_p = (struct bt_hci_cp_le_set_ext_adv_enable *) ¶ms; + struct bt_hci_cp_le_set_ext_adv_enable *params_p = (struct bt_hci_cp_le_set_ext_adv_enable *)¶ms; params_p->enable = enable; params_p->set_num = set_num; for (size_t i = 0; i < set_num; i++) { diff --git a/devices/ble_hci/common-hal/_bleio/hci_debug.c b/devices/ble_hci/common-hal/_bleio/hci_debug.c index 9cdd38981e..5e57142c3c 100644 --- a/devices/ble_hci/common-hal/_bleio/hci_debug.c +++ b/devices/ble_hci/common-hal/_bleio/hci_debug.c @@ -26,248 +26,462 @@ // This file is #include'd in hci.c when HCI_DEBUG is non-zero. -STATIC const char* att_opcode_name(uint16_t opcode) { +STATIC const char *att_opcode_name(uint16_t opcode) { switch (opcode) { - case BT_ATT_OP_ERROR_RSP: return "ERROR_RSP"; - case BT_ATT_OP_MTU_REQ: return "MTU_REQ"; - case BT_ATT_OP_MTU_RSP: return "MTU_RSP"; - case BT_ATT_OP_FIND_INFO_REQ: return "FIND_INFO_REQ"; - case BT_ATT_OP_FIND_INFO_RSP: return "FIND_INFO_RSP"; - case BT_ATT_OP_FIND_TYPE_REQ: return "FIND_TYPE_REQ"; - case BT_ATT_OP_FIND_TYPE_RSP: return "FIND_TYPE_RSP"; - case BT_ATT_OP_READ_TYPE_REQ: return "READ_TYPE_REQ"; - case BT_ATT_OP_READ_TYPE_RSP: return "READ_TYPE_RSP"; - case BT_ATT_OP_READ_REQ: return "READ_REQ"; - case BT_ATT_OP_READ_RSP: return "READ_RSP"; - case BT_ATT_OP_READ_BLOB_REQ: return "READ_BLOB_REQ"; - case BT_ATT_OP_READ_BLOB_RSP: return "READ_BLOB_RSP"; - case BT_ATT_OP_READ_MULT_REQ: return "READ_MULT_REQ"; - case BT_ATT_OP_READ_MULT_RSP: return "READ_MULT_RSP"; - case BT_ATT_OP_READ_GROUP_REQ: return "READ_GROUP_REQ"; - case BT_ATT_OP_READ_GROUP_RSP: return "READ_GROUP_RSP"; - case BT_ATT_OP_WRITE_REQ: return "WRITE_REQ"; - case BT_ATT_OP_WRITE_RSP: return "WRITE_RSP"; - case BT_ATT_OP_PREPARE_WRITE_REQ: return "PREPARE_WRITE_REQ"; - case BT_ATT_OP_PREPARE_WRITE_RSP: return "PREPARE_WRITE_RSP"; - case BT_ATT_OP_EXEC_WRITE_REQ: return "EXEC_WRITE_REQ"; - case BT_ATT_OP_EXEC_WRITE_RSP: return "EXEC_WRITE_RSP"; - case BT_ATT_OP_NOTIFY: return "NOTIFY"; - case BT_ATT_OP_INDICATE: return "INDICATE"; - case BT_ATT_OP_CONFIRM: return "CONFIRM"; - case BT_ATT_OP_READ_MULT_VL_REQ: return "READ_MULT_VL_REQ"; - case BT_ATT_OP_READ_MULT_VL_RSP: return "READ_MULT_VL_RSP"; - case BT_ATT_OP_NOTIFY_MULT: return "NOTIFY_MULT"; - case BT_ATT_OP_WRITE_CMD: return "WRITE_CMD"; - case BT_ATT_OP_SIGNED_WRITE_CMD: return "SIGNED_WRITE_CMD"; - default: return ""; + case BT_ATT_OP_ERROR_RSP: + return "ERROR_RSP"; + case BT_ATT_OP_MTU_REQ: + return "MTU_REQ"; + case BT_ATT_OP_MTU_RSP: + return "MTU_RSP"; + case BT_ATT_OP_FIND_INFO_REQ: + return "FIND_INFO_REQ"; + case BT_ATT_OP_FIND_INFO_RSP: + return "FIND_INFO_RSP"; + case BT_ATT_OP_FIND_TYPE_REQ: + return "FIND_TYPE_REQ"; + case BT_ATT_OP_FIND_TYPE_RSP: + return "FIND_TYPE_RSP"; + case BT_ATT_OP_READ_TYPE_REQ: + return "READ_TYPE_REQ"; + case BT_ATT_OP_READ_TYPE_RSP: + return "READ_TYPE_RSP"; + case BT_ATT_OP_READ_REQ: + return "READ_REQ"; + case BT_ATT_OP_READ_RSP: + return "READ_RSP"; + case BT_ATT_OP_READ_BLOB_REQ: + return "READ_BLOB_REQ"; + case BT_ATT_OP_READ_BLOB_RSP: + return "READ_BLOB_RSP"; + case BT_ATT_OP_READ_MULT_REQ: + return "READ_MULT_REQ"; + case BT_ATT_OP_READ_MULT_RSP: + return "READ_MULT_RSP"; + case BT_ATT_OP_READ_GROUP_REQ: + return "READ_GROUP_REQ"; + case BT_ATT_OP_READ_GROUP_RSP: + return "READ_GROUP_RSP"; + case BT_ATT_OP_WRITE_REQ: + return "WRITE_REQ"; + case BT_ATT_OP_WRITE_RSP: + return "WRITE_RSP"; + case BT_ATT_OP_PREPARE_WRITE_REQ: + return "PREPARE_WRITE_REQ"; + case BT_ATT_OP_PREPARE_WRITE_RSP: + return "PREPARE_WRITE_RSP"; + case BT_ATT_OP_EXEC_WRITE_REQ: + return "EXEC_WRITE_REQ"; + case BT_ATT_OP_EXEC_WRITE_RSP: + return "EXEC_WRITE_RSP"; + case BT_ATT_OP_NOTIFY: + return "NOTIFY"; + case BT_ATT_OP_INDICATE: + return "INDICATE"; + case BT_ATT_OP_CONFIRM: + return "CONFIRM"; + case BT_ATT_OP_READ_MULT_VL_REQ: + return "READ_MULT_VL_REQ"; + case BT_ATT_OP_READ_MULT_VL_RSP: + return "READ_MULT_VL_RSP"; + case BT_ATT_OP_NOTIFY_MULT: + return "NOTIFY_MULT"; + case BT_ATT_OP_WRITE_CMD: + return "WRITE_CMD"; + case BT_ATT_OP_SIGNED_WRITE_CMD: + return "SIGNED_WRITE_CMD"; + default: + return ""; } } -STATIC const char* hci_evt_name(uint8_t evt) { +STATIC const char *hci_evt_name(uint8_t evt) { switch (evt) { - case BT_HCI_EVT_UNKNOWN: return "UNKNOWN"; - case BT_HCI_EVT_VENDOR: return "VENDOR"; - case BT_HCI_EVT_INQUIRY_COMPLETE: return "INQUIRY_COMPLETE"; - case BT_HCI_EVT_CONN_COMPLETE: return "CONN_COMPLETE"; - case BT_HCI_EVT_CONN_REQUEST: return "CONN_REQUEST"; - case BT_HCI_EVT_DISCONN_COMPLETE: return "DISCONN_COMPLETE"; - case BT_HCI_EVT_AUTH_COMPLETE: return "AUTH_COMPLETE"; - case BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE: return "REMOTE_NAME_REQ_COMPLETE"; - case BT_HCI_EVT_ENCRYPT_CHANGE: return "ENCRYPT_CHANGE"; - case BT_HCI_EVT_REMOTE_FEATURES: return "REMOTE_FEATURES"; - case BT_HCI_EVT_REMOTE_VERSION_INFO: return "REMOTE_VERSION_INFO"; - case BT_HCI_EVT_CMD_COMPLETE: return "CMD_COMPLETE"; - case BT_HCI_EVT_CMD_STATUS: return "CMD_STATUS"; - case BT_HCI_EVT_ROLE_CHANGE: return "ROLE_CHANGE"; - case BT_HCI_EVT_NUM_COMPLETED_PACKETS: return "NUM_COMPLETED_PACKETS"; - case BT_HCI_EVT_PIN_CODE_REQ: return "PIN_CODE_REQ"; - case BT_HCI_EVT_LINK_KEY_REQ: return "LINK_KEY_REQ"; - case BT_HCI_EVT_LINK_KEY_NOTIFY: return "LINK_KEY_NOTIFY"; - case BT_HCI_EVT_DATA_BUF_OVERFLOW: return "DATA_BUF_OVERFLOW"; - case BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI: return "INQUIRY_RESULT_WITH_RSSI"; - case BT_HCI_EVT_REMOTE_EXT_FEATURES: return "REMOTE_EXT_FEATURES"; - case BT_HCI_EVT_SYNC_CONN_COMPLETE: return "SYNC_CONN_COMPLETE"; - case BT_HCI_EVT_EXTENDED_INQUIRY_RESULT: return "EXTENDED_INQUIRY_RESULT"; - case BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE: return "ENCRYPT_KEY_REFRESH_COMPLETE"; - case BT_HCI_EVT_IO_CAPA_REQ: return "IO_CAPA_REQ"; - case BT_HCI_EVT_IO_CAPA_RESP: return "IO_CAPA_RESP"; - case BT_HCI_EVT_USER_CONFIRM_REQ: return "USER_CONFIRM_REQ"; - case BT_HCI_EVT_USER_PASSKEY_REQ: return "USER_PASSKEY_REQ"; - case BT_HCI_EVT_SSP_COMPLETE: return "SSP_COMPLETE"; - case BT_HCI_EVT_USER_PASSKEY_NOTIFY: return "USER_PASSKEY_NOTIFY"; - case BT_HCI_EVT_LE_META_EVENT: return "LE_META_EVENT"; - case BT_HCI_EVT_AUTH_PAYLOAD_TIMEOUT_EXP: return "AUTH_PAYLOAD_TIMEOUT_EXP"; - default: return ""; + case BT_HCI_EVT_UNKNOWN: + return "UNKNOWN"; + case BT_HCI_EVT_VENDOR: + return "VENDOR"; + case BT_HCI_EVT_INQUIRY_COMPLETE: + return "INQUIRY_COMPLETE"; + case BT_HCI_EVT_CONN_COMPLETE: + return "CONN_COMPLETE"; + case BT_HCI_EVT_CONN_REQUEST: + return "CONN_REQUEST"; + case BT_HCI_EVT_DISCONN_COMPLETE: + return "DISCONN_COMPLETE"; + case BT_HCI_EVT_AUTH_COMPLETE: + return "AUTH_COMPLETE"; + case BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE: + return "REMOTE_NAME_REQ_COMPLETE"; + case BT_HCI_EVT_ENCRYPT_CHANGE: + return "ENCRYPT_CHANGE"; + case BT_HCI_EVT_REMOTE_FEATURES: + return "REMOTE_FEATURES"; + case BT_HCI_EVT_REMOTE_VERSION_INFO: + return "REMOTE_VERSION_INFO"; + case BT_HCI_EVT_CMD_COMPLETE: + return "CMD_COMPLETE"; + case BT_HCI_EVT_CMD_STATUS: + return "CMD_STATUS"; + case BT_HCI_EVT_ROLE_CHANGE: + return "ROLE_CHANGE"; + case BT_HCI_EVT_NUM_COMPLETED_PACKETS: + return "NUM_COMPLETED_PACKETS"; + case BT_HCI_EVT_PIN_CODE_REQ: + return "PIN_CODE_REQ"; + case BT_HCI_EVT_LINK_KEY_REQ: + return "LINK_KEY_REQ"; + case BT_HCI_EVT_LINK_KEY_NOTIFY: + return "LINK_KEY_NOTIFY"; + case BT_HCI_EVT_DATA_BUF_OVERFLOW: + return "DATA_BUF_OVERFLOW"; + case BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI: + return "INQUIRY_RESULT_WITH_RSSI"; + case BT_HCI_EVT_REMOTE_EXT_FEATURES: + return "REMOTE_EXT_FEATURES"; + case BT_HCI_EVT_SYNC_CONN_COMPLETE: + return "SYNC_CONN_COMPLETE"; + case BT_HCI_EVT_EXTENDED_INQUIRY_RESULT: + return "EXTENDED_INQUIRY_RESULT"; + case BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE: + return "ENCRYPT_KEY_REFRESH_COMPLETE"; + case BT_HCI_EVT_IO_CAPA_REQ: + return "IO_CAPA_REQ"; + case BT_HCI_EVT_IO_CAPA_RESP: + return "IO_CAPA_RESP"; + case BT_HCI_EVT_USER_CONFIRM_REQ: + return "USER_CONFIRM_REQ"; + case BT_HCI_EVT_USER_PASSKEY_REQ: + return "USER_PASSKEY_REQ"; + case BT_HCI_EVT_SSP_COMPLETE: + return "SSP_COMPLETE"; + case BT_HCI_EVT_USER_PASSKEY_NOTIFY: + return "USER_PASSKEY_NOTIFY"; + case BT_HCI_EVT_LE_META_EVENT: + return "LE_META_EVENT"; + case BT_HCI_EVT_AUTH_PAYLOAD_TIMEOUT_EXP: + return "AUTH_PAYLOAD_TIMEOUT_EXP"; + default: + return ""; } } -STATIC const char* hci_evt_le_name(uint8_t evt_le) { +STATIC const char *hci_evt_le_name(uint8_t evt_le) { switch (evt_le) { - case BT_HCI_EVT_LE_CONN_COMPLETE: return "LE_CONN_COMPLETE"; - case BT_HCI_EVT_LE_ADVERTISING_REPORT: return "LE_ADVERTISING_REPORT"; - case BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE: return "LE_CONN_UPDATE_COMPLETE"; - case BT_HCI_EVT_LE_LTK_REQUEST: return "LE_LTK_REQUEST"; - case BT_HCI_EVT_LE_CONN_PARAM_REQ: return "LE_CONN_PARAM_REQ"; - case BT_HCI_EVT_LE_DATA_LEN_CHANGE: return "LE_DATA_LEN_CHANGE"; - case BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE: return "LE_P256_PUBLIC_KEY_COMPLETE"; - case BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE: return "LE_GENERATE_DHKEY_COMPLETE"; - case BT_HCI_EVT_LE_ENH_CONN_COMPLETE: return "LE_ENH_CONN_COMPLETE"; - case BT_HCI_EVT_LE_DIRECT_ADV_REPORT: return "LE_DIRECT_ADV_REPORT"; - case BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE: return "LE_PHY_UPDATE_COMPLETE"; - case BT_HCI_EVT_LE_EXT_ADVERTISING_REPORT: return "LE_EXT_ADVERTISING_REPORT"; - case BT_HCI_EVT_LE_PER_ADV_SYNC_ESTABLISHED: return "LE_PER_ADV_SYNC_ESTABLISHED"; - case BT_HCI_EVT_LE_PER_ADVERTISING_REPORT: return "LE_PER_ADVERTISING_REPORT"; - case BT_HCI_EVT_LE_PER_ADV_SYNC_LOST: return "LE_PER_ADV_SYNC_LOST"; - case BT_HCI_EVT_LE_SCAN_TIMEOUT: return "LE_SCAN_TIMEOUT"; - case BT_HCI_EVT_LE_ADV_SET_TERMINATED: return "LE_ADV_SET_TERMINATED"; - case BT_HCI_EVT_LE_SCAN_REQ_RECEIVED: return "LE_SCAN_REQ_RECEIVED"; - case BT_HCI_EVT_LE_CHAN_SEL_ALGO: return "LE_CHAN_SEL_ALGO"; - default: return ""; + case BT_HCI_EVT_LE_CONN_COMPLETE: + return "LE_CONN_COMPLETE"; + case BT_HCI_EVT_LE_ADVERTISING_REPORT: + return "LE_ADVERTISING_REPORT"; + case BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE: + return "LE_CONN_UPDATE_COMPLETE"; + case BT_HCI_EVT_LE_LTK_REQUEST: + return "LE_LTK_REQUEST"; + case BT_HCI_EVT_LE_CONN_PARAM_REQ: + return "LE_CONN_PARAM_REQ"; + case BT_HCI_EVT_LE_DATA_LEN_CHANGE: + return "LE_DATA_LEN_CHANGE"; + case BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE: + return "LE_P256_PUBLIC_KEY_COMPLETE"; + case BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE: + return "LE_GENERATE_DHKEY_COMPLETE"; + case BT_HCI_EVT_LE_ENH_CONN_COMPLETE: + return "LE_ENH_CONN_COMPLETE"; + case BT_HCI_EVT_LE_DIRECT_ADV_REPORT: + return "LE_DIRECT_ADV_REPORT"; + case BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE: + return "LE_PHY_UPDATE_COMPLETE"; + case BT_HCI_EVT_LE_EXT_ADVERTISING_REPORT: + return "LE_EXT_ADVERTISING_REPORT"; + case BT_HCI_EVT_LE_PER_ADV_SYNC_ESTABLISHED: + return "LE_PER_ADV_SYNC_ESTABLISHED"; + case BT_HCI_EVT_LE_PER_ADVERTISING_REPORT: + return "LE_PER_ADVERTISING_REPORT"; + case BT_HCI_EVT_LE_PER_ADV_SYNC_LOST: + return "LE_PER_ADV_SYNC_LOST"; + case BT_HCI_EVT_LE_SCAN_TIMEOUT: + return "LE_SCAN_TIMEOUT"; + case BT_HCI_EVT_LE_ADV_SET_TERMINATED: + return "LE_ADV_SET_TERMINATED"; + case BT_HCI_EVT_LE_SCAN_REQ_RECEIVED: + return "LE_SCAN_REQ_RECEIVED"; + case BT_HCI_EVT_LE_CHAN_SEL_ALGO: + return "LE_CHAN_SEL_ALGO"; + default: + return ""; } } -STATIC const char* hci_opcode_name(uint16_t opcode) { +STATIC const char *hci_opcode_name(uint16_t opcode) { switch (opcode) { - case BT_OP_NOP: return "NOP"; - case BT_HCI_OP_INQUIRY: return "INQUIRY"; - case BT_HCI_OP_INQUIRY_CANCEL: return "INQUIRY_CANCEL"; - case BT_HCI_OP_CONNECT: return "CONNECT"; - case BT_HCI_OP_DISCONNECT: return "DISCONNECT"; - case BT_HCI_OP_CONNECT_CANCEL: return "CONNECT_CANCEL"; - case BT_HCI_OP_ACCEPT_CONN_REQ: return "ACCEPT_CONN_REQ"; - case BT_HCI_OP_SETUP_SYNC_CONN: return "SETUP_SYNC_CONN"; - case BT_HCI_OP_ACCEPT_SYNC_CONN_REQ: return "ACCEPT_SYNC_CONN_REQ"; - case BT_HCI_OP_REJECT_CONN_REQ: return "REJECT_CONN_REQ"; - case BT_HCI_OP_LINK_KEY_REPLY: return "LINK_KEY_REPLY"; - case BT_HCI_OP_LINK_KEY_NEG_REPLY: return "LINK_KEY_NEG_REPLY"; - case BT_HCI_OP_PIN_CODE_REPLY: return "PIN_CODE_REPLY"; - case BT_HCI_OP_PIN_CODE_NEG_REPLY: return "PIN_CODE_NEG_REPLY"; - case BT_HCI_OP_AUTH_REQUESTED: return "AUTH_REQUESTED"; - case BT_HCI_OP_SET_CONN_ENCRYPT: return "SET_CONN_ENCRYPT"; - case BT_HCI_OP_REMOTE_NAME_REQUEST: return "REMOTE_NAME_REQUEST"; - case BT_HCI_OP_REMOTE_NAME_CANCEL: return "REMOTE_NAME_CANCEL"; - case BT_HCI_OP_READ_REMOTE_FEATURES: return "READ_REMOTE_FEATURES"; - case BT_HCI_OP_READ_REMOTE_EXT_FEATURES: return "READ_REMOTE_EXT_FEATURES"; - case BT_HCI_OP_READ_REMOTE_VERSION_INFO: return "READ_REMOTE_VERSION_INFO"; - case BT_HCI_OP_IO_CAPABILITY_REPLY: return "IO_CAPABILITY_REPLY"; - case BT_HCI_OP_USER_CONFIRM_REPLY: return "USER_CONFIRM_REPLY"; - case BT_HCI_OP_USER_CONFIRM_NEG_REPLY: return "USER_CONFIRM_NEG_REPLY"; - case BT_HCI_OP_USER_PASSKEY_REPLY: return "USER_PASSKEY_REPLY"; - case BT_HCI_OP_USER_PASSKEY_NEG_REPLY: return "USER_PASSKEY_NEG_REPLY"; - case BT_HCI_OP_IO_CAPABILITY_NEG_REPLY: return "IO_CAPABILITY_NEG_REPLY"; - case BT_HCI_OP_SET_EVENT_MASK: return "SET_EVENT_MASK"; - case BT_HCI_OP_RESET: return "RESET"; - case BT_HCI_OP_WRITE_LOCAL_NAME: return "WRITE_LOCAL_NAME"; - case BT_HCI_OP_WRITE_PAGE_TIMEOUT: return "WRITE_PAGE_TIMEOUT"; - case BT_HCI_OP_WRITE_SCAN_ENABLE: return "WRITE_SCAN_ENABLE"; - case BT_HCI_OP_READ_TX_POWER_LEVEL: return "READ_TX_POWER_LEVEL"; - case BT_HCI_OP_SET_CTL_TO_HOST_FLOW: return "SET_CTL_TO_HOST_FLOW"; - case BT_HCI_OP_HOST_BUFFER_SIZE: return "HOST_BUFFER_SIZE"; - case BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS: return "HOST_NUM_COMPLETED_PACKETS"; - case BT_HCI_OP_WRITE_INQUIRY_MODE: return "WRITE_INQUIRY_MODE"; - case BT_HCI_OP_WRITE_SSP_MODE: return "WRITE_SSP_MODE"; - case BT_HCI_OP_SET_EVENT_MASK_PAGE_2: return "SET_EVENT_MASK_PAGE_2"; - case BT_HCI_OP_LE_WRITE_LE_HOST_SUPP: return "LE_WRITE_LE_HOST_SUPP"; - case BT_HCI_OP_WRITE_SC_HOST_SUPP: return "WRITE_SC_HOST_SUPP"; - case BT_HCI_OP_READ_AUTH_PAYLOAD_TIMEOUT: return "READ_AUTH_PAYLOAD_TIMEOUT"; - case BT_HCI_OP_WRITE_AUTH_PAYLOAD_TIMEOUT: return "WRITE_AUTH_PAYLOAD_TIMEOUT"; - case BT_HCI_OP_READ_LOCAL_VERSION_INFO: return "READ_LOCAL_VERSION_INFO"; - case BT_HCI_OP_READ_SUPPORTED_COMMANDS: return "READ_SUPPORTED_COMMANDS"; - case BT_HCI_OP_READ_LOCAL_EXT_FEATURES: return "READ_LOCAL_EXT_FEATURES"; - case BT_HCI_OP_READ_LOCAL_FEATURES: return "READ_LOCAL_FEATURES"; - case BT_HCI_OP_READ_BUFFER_SIZE: return "READ_BUFFER_SIZE"; - case BT_HCI_OP_READ_BD_ADDR: return "READ_BD_ADDR"; - case BT_HCI_OP_READ_RSSI: return "READ_RSSI"; - case BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE: return "READ_ENCRYPTION_KEY_SIZE"; - case BT_HCI_OP_LE_SET_EVENT_MASK: return "LE_SET_EVENT_MASK"; - case BT_HCI_OP_LE_READ_BUFFER_SIZE: return "LE_READ_BUFFER_SIZE"; - case BT_HCI_OP_LE_READ_LOCAL_FEATURES: return "LE_READ_LOCAL_FEATURES"; - case BT_HCI_OP_LE_SET_RANDOM_ADDRESS: return "LE_SET_RANDOM_ADDRESS"; - case BT_HCI_OP_LE_SET_ADV_PARAM: return "LE_SET_ADV_PARAM"; - case BT_HCI_OP_LE_READ_ADV_CHAN_TX_POWER: return "LE_READ_ADV_CHAN_TX_POWER"; - case BT_HCI_OP_LE_SET_ADV_DATA: return "LE_SET_ADV_DATA"; - case BT_HCI_OP_LE_SET_SCAN_RSP_DATA: return "LE_SET_SCAN_RSP_DATA"; - case BT_HCI_OP_LE_SET_ADV_ENABLE: return "LE_SET_ADV_ENABLE"; - case BT_HCI_OP_LE_SET_SCAN_PARAM: return "LE_SET_SCAN_PARAM"; - case BT_HCI_OP_LE_SET_SCAN_ENABLE: return "LE_SET_SCAN_ENABLE"; - case BT_HCI_OP_LE_CREATE_CONN: return "LE_CREATE_CONN"; - case BT_HCI_OP_LE_CREATE_CONN_CANCEL: return "LE_CREATE_CONN_CANCEL"; - case BT_HCI_OP_LE_READ_WL_SIZE: return "LE_READ_WL_SIZE"; - case BT_HCI_OP_LE_CLEAR_WL: return "LE_CLEAR_WL"; - case BT_HCI_OP_LE_ADD_DEV_TO_WL: return "LE_ADD_DEV_TO_WL"; - case BT_HCI_OP_LE_REM_DEV_FROM_WL: return "LE_REM_DEV_FROM_WL"; - case BT_HCI_OP_LE_CONN_UPDATE: return "LE_CONN_UPDATE"; - case BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF: return "LE_SET_HOST_CHAN_CLASSIF"; - case BT_HCI_OP_LE_READ_CHAN_MAP: return "LE_READ_CHAN_MAP"; - case BT_HCI_OP_LE_READ_REMOTE_FEATURES: return "LE_READ_REMOTE_FEATURES"; - case BT_HCI_OP_LE_ENCRYPT: return "LE_ENCRYPT"; - case BT_HCI_OP_LE_RAND: return "LE_RAND"; - case BT_HCI_OP_LE_START_ENCRYPTION: return "LE_START_ENCRYPTION"; - case BT_HCI_OP_LE_LTK_REQ_REPLY: return "LE_LTK_REQ_REPLY"; - case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY: return "LE_LTK_REQ_NEG_REPLY"; - case BT_HCI_OP_LE_READ_SUPP_STATES: return "LE_READ_SUPP_STATES"; - case BT_HCI_OP_LE_RX_TEST: return "LE_RX_TEST"; - case BT_HCI_OP_LE_TX_TEST: return "LE_TX_TEST"; - case BT_HCI_OP_LE_TEST_END: return "LE_TEST_END"; - case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY: return "LE_CONN_PARAM_REQ_REPLY"; - case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY: return "LE_CONN_PARAM_REQ_NEG_REPLY"; - case BT_HCI_OP_LE_SET_DATA_LEN: return "LE_SET_DATA_LEN"; - case BT_HCI_OP_LE_READ_DEFAULT_DATA_LEN: return "LE_READ_DEFAULT_DATA_LEN"; - case BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN: return "LE_WRITE_DEFAULT_DATA_LEN"; - case BT_HCI_OP_LE_P256_PUBLIC_KEY: return "LE_P256_PUBLIC_KEY"; - case BT_HCI_OP_LE_GENERATE_DHKEY: return "LE_GENERATE_DHKEY"; - case BT_HCI_OP_LE_ADD_DEV_TO_RL: return "LE_ADD_DEV_TO_RL"; - case BT_HCI_OP_LE_REM_DEV_FROM_RL: return "LE_REM_DEV_FROM_RL"; - case BT_HCI_OP_LE_CLEAR_RL: return "LE_CLEAR_RL"; - case BT_HCI_OP_LE_READ_RL_SIZE: return "LE_READ_RL_SIZE"; - case BT_HCI_OP_LE_READ_PEER_RPA: return "LE_READ_PEER_RPA"; - case BT_HCI_OP_LE_READ_LOCAL_RPA: return "LE_READ_LOCAL_RPA"; - case BT_HCI_OP_LE_SET_ADDR_RES_ENABLE: return "LE_SET_ADDR_RES_ENABLE"; - case BT_HCI_OP_LE_SET_RPA_TIMEOUT: return "LE_SET_RPA_TIMEOUT"; - case BT_HCI_OP_LE_READ_MAX_DATA_LEN: return "LE_READ_MAX_DATA_LEN"; - case BT_HCI_OP_LE_READ_PHY: return "LE_READ_PHY"; - case BT_HCI_OP_LE_SET_DEFAULT_PHY: return "LE_SET_DEFAULT_PHY"; - case BT_HCI_OP_LE_SET_PHY: return "LE_SET_PHY"; - case BT_HCI_OP_LE_ENH_RX_TEST: return "LE_ENH_RX_TEST"; - case BT_HCI_OP_LE_ENH_TX_TEST: return "LE_ENH_TX_TEST"; - case BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR: return "LE_SET_ADV_SET_RANDOM_ADDR"; - case BT_HCI_OP_LE_SET_EXT_ADV_PARAM: return "LE_SET_EXT_ADV_PARAM"; - case BT_HCI_OP_LE_SET_EXT_ADV_DATA: return "LE_SET_EXT_ADV_DATA"; - case BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA: return "LE_SET_EXT_SCAN_RSP_DATA"; - case BT_HCI_OP_LE_SET_EXT_ADV_ENABLE: return "LE_SET_EXT_ADV_ENABLE"; - case BT_HCI_OP_LE_READ_MAX_ADV_DATA_LEN: return "LE_READ_MAX_ADV_DATA_LEN"; - case BT_HCI_OP_LE_READ_NUM_ADV_SETS: return "LE_READ_NUM_ADV_SETS"; - case BT_HCI_OP_LE_REMOVE_ADV_SET: return "LE_REMOVE_ADV_SET"; - case BT_HCI_OP_CLEAR_ADV_SETS: return "CLEAR_ADV_SETS"; - case BT_HCI_OP_LE_SET_PER_ADV_PARAM: return "LE_SET_PER_ADV_PARAM"; - case BT_HCI_OP_LE_SET_PER_ADV_DATA: return "LE_SET_PER_ADV_DATA"; - case BT_HCI_OP_LE_SET_PER_ADV_ENABLE: return "LE_SET_PER_ADV_ENABLE"; - case BT_HCI_OP_LE_SET_EXT_SCAN_PARAM: return "LE_SET_EXT_SCAN_PARAM"; - case BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE: return "LE_SET_EXT_SCAN_ENABLE"; - case BT_HCI_OP_LE_EXT_CREATE_CONN: return "LE_EXT_CREATE_CONN"; - case BT_HCI_OP_LE_PER_ADV_CREATE_SYNC: return "LE_PER_ADV_CREATE_SYNC"; - case BT_HCI_OP_LE_PER_ADV_CREATE_SYNC_CANCEL: return "LE_PER_ADV_CREATE_SYNC_CANCEL"; - case BT_HCI_OP_LE_PER_ADV_TERMINATE_SYNC: return "LE_PER_ADV_TERMINATE_SYNC"; - case BT_HCI_OP_LE_ADD_DEV_TO_PER_ADV_LIST: return "LE_ADD_DEV_TO_PER_ADV_LIST"; - case BT_HCI_OP_LE_REM_DEV_FROM_PER_ADV_LIST: return "LE_REM_DEV_FROM_PER_ADV_LIST"; - case BT_HCI_OP_LE_CLEAR_PER_ADV_LIST: return "LE_CLEAR_PER_ADV_LIST"; - case BT_HCI_OP_LE_READ_PER_ADV_LIST_SIZE: return "LE_READ_PER_ADV_LIST_SIZE"; - case BT_HCI_OP_LE_READ_TX_POWER: return "LE_READ_TX_POWER"; - case BT_HCI_OP_LE_READ_RF_PATH_COMP: return "LE_READ_RF_PATH_COMP"; - case BT_HCI_OP_LE_WRITE_RF_PATH_COMP: return "LE_WRITE_RF_PATH_COMP"; - case BT_HCI_OP_LE_SET_PRIVACY_MODE: return "LE_SET_PRIVACY_MODE"; - default: return ""; + case BT_OP_NOP: + return "NOP"; + case BT_HCI_OP_INQUIRY: + return "INQUIRY"; + case BT_HCI_OP_INQUIRY_CANCEL: + return "INQUIRY_CANCEL"; + case BT_HCI_OP_CONNECT: + return "CONNECT"; + case BT_HCI_OP_DISCONNECT: + return "DISCONNECT"; + case BT_HCI_OP_CONNECT_CANCEL: + return "CONNECT_CANCEL"; + case BT_HCI_OP_ACCEPT_CONN_REQ: + return "ACCEPT_CONN_REQ"; + case BT_HCI_OP_SETUP_SYNC_CONN: + return "SETUP_SYNC_CONN"; + case BT_HCI_OP_ACCEPT_SYNC_CONN_REQ: + return "ACCEPT_SYNC_CONN_REQ"; + case BT_HCI_OP_REJECT_CONN_REQ: + return "REJECT_CONN_REQ"; + case BT_HCI_OP_LINK_KEY_REPLY: + return "LINK_KEY_REPLY"; + case BT_HCI_OP_LINK_KEY_NEG_REPLY: + return "LINK_KEY_NEG_REPLY"; + case BT_HCI_OP_PIN_CODE_REPLY: + return "PIN_CODE_REPLY"; + case BT_HCI_OP_PIN_CODE_NEG_REPLY: + return "PIN_CODE_NEG_REPLY"; + case BT_HCI_OP_AUTH_REQUESTED: + return "AUTH_REQUESTED"; + case BT_HCI_OP_SET_CONN_ENCRYPT: + return "SET_CONN_ENCRYPT"; + case BT_HCI_OP_REMOTE_NAME_REQUEST: + return "REMOTE_NAME_REQUEST"; + case BT_HCI_OP_REMOTE_NAME_CANCEL: + return "REMOTE_NAME_CANCEL"; + case BT_HCI_OP_READ_REMOTE_FEATURES: + return "READ_REMOTE_FEATURES"; + case BT_HCI_OP_READ_REMOTE_EXT_FEATURES: + return "READ_REMOTE_EXT_FEATURES"; + case BT_HCI_OP_READ_REMOTE_VERSION_INFO: + return "READ_REMOTE_VERSION_INFO"; + case BT_HCI_OP_IO_CAPABILITY_REPLY: + return "IO_CAPABILITY_REPLY"; + case BT_HCI_OP_USER_CONFIRM_REPLY: + return "USER_CONFIRM_REPLY"; + case BT_HCI_OP_USER_CONFIRM_NEG_REPLY: + return "USER_CONFIRM_NEG_REPLY"; + case BT_HCI_OP_USER_PASSKEY_REPLY: + return "USER_PASSKEY_REPLY"; + case BT_HCI_OP_USER_PASSKEY_NEG_REPLY: + return "USER_PASSKEY_NEG_REPLY"; + case BT_HCI_OP_IO_CAPABILITY_NEG_REPLY: + return "IO_CAPABILITY_NEG_REPLY"; + case BT_HCI_OP_SET_EVENT_MASK: + return "SET_EVENT_MASK"; + case BT_HCI_OP_RESET: + return "RESET"; + case BT_HCI_OP_WRITE_LOCAL_NAME: + return "WRITE_LOCAL_NAME"; + case BT_HCI_OP_WRITE_PAGE_TIMEOUT: + return "WRITE_PAGE_TIMEOUT"; + case BT_HCI_OP_WRITE_SCAN_ENABLE: + return "WRITE_SCAN_ENABLE"; + case BT_HCI_OP_READ_TX_POWER_LEVEL: + return "READ_TX_POWER_LEVEL"; + case BT_HCI_OP_SET_CTL_TO_HOST_FLOW: + return "SET_CTL_TO_HOST_FLOW"; + case BT_HCI_OP_HOST_BUFFER_SIZE: + return "HOST_BUFFER_SIZE"; + case BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS: + return "HOST_NUM_COMPLETED_PACKETS"; + case BT_HCI_OP_WRITE_INQUIRY_MODE: + return "WRITE_INQUIRY_MODE"; + case BT_HCI_OP_WRITE_SSP_MODE: + return "WRITE_SSP_MODE"; + case BT_HCI_OP_SET_EVENT_MASK_PAGE_2: + return "SET_EVENT_MASK_PAGE_2"; + case BT_HCI_OP_LE_WRITE_LE_HOST_SUPP: + return "LE_WRITE_LE_HOST_SUPP"; + case BT_HCI_OP_WRITE_SC_HOST_SUPP: + return "WRITE_SC_HOST_SUPP"; + case BT_HCI_OP_READ_AUTH_PAYLOAD_TIMEOUT: + return "READ_AUTH_PAYLOAD_TIMEOUT"; + case BT_HCI_OP_WRITE_AUTH_PAYLOAD_TIMEOUT: + return "WRITE_AUTH_PAYLOAD_TIMEOUT"; + case BT_HCI_OP_READ_LOCAL_VERSION_INFO: + return "READ_LOCAL_VERSION_INFO"; + case BT_HCI_OP_READ_SUPPORTED_COMMANDS: + return "READ_SUPPORTED_COMMANDS"; + case BT_HCI_OP_READ_LOCAL_EXT_FEATURES: + return "READ_LOCAL_EXT_FEATURES"; + case BT_HCI_OP_READ_LOCAL_FEATURES: + return "READ_LOCAL_FEATURES"; + case BT_HCI_OP_READ_BUFFER_SIZE: + return "READ_BUFFER_SIZE"; + case BT_HCI_OP_READ_BD_ADDR: + return "READ_BD_ADDR"; + case BT_HCI_OP_READ_RSSI: + return "READ_RSSI"; + case BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE: + return "READ_ENCRYPTION_KEY_SIZE"; + case BT_HCI_OP_LE_SET_EVENT_MASK: + return "LE_SET_EVENT_MASK"; + case BT_HCI_OP_LE_READ_BUFFER_SIZE: + return "LE_READ_BUFFER_SIZE"; + case BT_HCI_OP_LE_READ_LOCAL_FEATURES: + return "LE_READ_LOCAL_FEATURES"; + case BT_HCI_OP_LE_SET_RANDOM_ADDRESS: + return "LE_SET_RANDOM_ADDRESS"; + case BT_HCI_OP_LE_SET_ADV_PARAM: + return "LE_SET_ADV_PARAM"; + case BT_HCI_OP_LE_READ_ADV_CHAN_TX_POWER: + return "LE_READ_ADV_CHAN_TX_POWER"; + case BT_HCI_OP_LE_SET_ADV_DATA: + return "LE_SET_ADV_DATA"; + case BT_HCI_OP_LE_SET_SCAN_RSP_DATA: + return "LE_SET_SCAN_RSP_DATA"; + case BT_HCI_OP_LE_SET_ADV_ENABLE: + return "LE_SET_ADV_ENABLE"; + case BT_HCI_OP_LE_SET_SCAN_PARAM: + return "LE_SET_SCAN_PARAM"; + case BT_HCI_OP_LE_SET_SCAN_ENABLE: + return "LE_SET_SCAN_ENABLE"; + case BT_HCI_OP_LE_CREATE_CONN: + return "LE_CREATE_CONN"; + case BT_HCI_OP_LE_CREATE_CONN_CANCEL: + return "LE_CREATE_CONN_CANCEL"; + case BT_HCI_OP_LE_READ_WL_SIZE: + return "LE_READ_WL_SIZE"; + case BT_HCI_OP_LE_CLEAR_WL: + return "LE_CLEAR_WL"; + case BT_HCI_OP_LE_ADD_DEV_TO_WL: + return "LE_ADD_DEV_TO_WL"; + case BT_HCI_OP_LE_REM_DEV_FROM_WL: + return "LE_REM_DEV_FROM_WL"; + case BT_HCI_OP_LE_CONN_UPDATE: + return "LE_CONN_UPDATE"; + case BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF: + return "LE_SET_HOST_CHAN_CLASSIF"; + case BT_HCI_OP_LE_READ_CHAN_MAP: + return "LE_READ_CHAN_MAP"; + case BT_HCI_OP_LE_READ_REMOTE_FEATURES: + return "LE_READ_REMOTE_FEATURES"; + case BT_HCI_OP_LE_ENCRYPT: + return "LE_ENCRYPT"; + case BT_HCI_OP_LE_RAND: + return "LE_RAND"; + case BT_HCI_OP_LE_START_ENCRYPTION: + return "LE_START_ENCRYPTION"; + case BT_HCI_OP_LE_LTK_REQ_REPLY: + return "LE_LTK_REQ_REPLY"; + case BT_HCI_OP_LE_LTK_REQ_NEG_REPLY: + return "LE_LTK_REQ_NEG_REPLY"; + case BT_HCI_OP_LE_READ_SUPP_STATES: + return "LE_READ_SUPP_STATES"; + case BT_HCI_OP_LE_RX_TEST: + return "LE_RX_TEST"; + case BT_HCI_OP_LE_TX_TEST: + return "LE_TX_TEST"; + case BT_HCI_OP_LE_TEST_END: + return "LE_TEST_END"; + case BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY: + return "LE_CONN_PARAM_REQ_REPLY"; + case BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY: + return "LE_CONN_PARAM_REQ_NEG_REPLY"; + case BT_HCI_OP_LE_SET_DATA_LEN: + return "LE_SET_DATA_LEN"; + case BT_HCI_OP_LE_READ_DEFAULT_DATA_LEN: + return "LE_READ_DEFAULT_DATA_LEN"; + case BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN: + return "LE_WRITE_DEFAULT_DATA_LEN"; + case BT_HCI_OP_LE_P256_PUBLIC_KEY: + return "LE_P256_PUBLIC_KEY"; + case BT_HCI_OP_LE_GENERATE_DHKEY: + return "LE_GENERATE_DHKEY"; + case BT_HCI_OP_LE_ADD_DEV_TO_RL: + return "LE_ADD_DEV_TO_RL"; + case BT_HCI_OP_LE_REM_DEV_FROM_RL: + return "LE_REM_DEV_FROM_RL"; + case BT_HCI_OP_LE_CLEAR_RL: + return "LE_CLEAR_RL"; + case BT_HCI_OP_LE_READ_RL_SIZE: + return "LE_READ_RL_SIZE"; + case BT_HCI_OP_LE_READ_PEER_RPA: + return "LE_READ_PEER_RPA"; + case BT_HCI_OP_LE_READ_LOCAL_RPA: + return "LE_READ_LOCAL_RPA"; + case BT_HCI_OP_LE_SET_ADDR_RES_ENABLE: + return "LE_SET_ADDR_RES_ENABLE"; + case BT_HCI_OP_LE_SET_RPA_TIMEOUT: + return "LE_SET_RPA_TIMEOUT"; + case BT_HCI_OP_LE_READ_MAX_DATA_LEN: + return "LE_READ_MAX_DATA_LEN"; + case BT_HCI_OP_LE_READ_PHY: + return "LE_READ_PHY"; + case BT_HCI_OP_LE_SET_DEFAULT_PHY: + return "LE_SET_DEFAULT_PHY"; + case BT_HCI_OP_LE_SET_PHY: + return "LE_SET_PHY"; + case BT_HCI_OP_LE_ENH_RX_TEST: + return "LE_ENH_RX_TEST"; + case BT_HCI_OP_LE_ENH_TX_TEST: + return "LE_ENH_TX_TEST"; + case BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR: + return "LE_SET_ADV_SET_RANDOM_ADDR"; + case BT_HCI_OP_LE_SET_EXT_ADV_PARAM: + return "LE_SET_EXT_ADV_PARAM"; + case BT_HCI_OP_LE_SET_EXT_ADV_DATA: + return "LE_SET_EXT_ADV_DATA"; + case BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA: + return "LE_SET_EXT_SCAN_RSP_DATA"; + case BT_HCI_OP_LE_SET_EXT_ADV_ENABLE: + return "LE_SET_EXT_ADV_ENABLE"; + case BT_HCI_OP_LE_READ_MAX_ADV_DATA_LEN: + return "LE_READ_MAX_ADV_DATA_LEN"; + case BT_HCI_OP_LE_READ_NUM_ADV_SETS: + return "LE_READ_NUM_ADV_SETS"; + case BT_HCI_OP_LE_REMOVE_ADV_SET: + return "LE_REMOVE_ADV_SET"; + case BT_HCI_OP_CLEAR_ADV_SETS: + return "CLEAR_ADV_SETS"; + case BT_HCI_OP_LE_SET_PER_ADV_PARAM: + return "LE_SET_PER_ADV_PARAM"; + case BT_HCI_OP_LE_SET_PER_ADV_DATA: + return "LE_SET_PER_ADV_DATA"; + case BT_HCI_OP_LE_SET_PER_ADV_ENABLE: + return "LE_SET_PER_ADV_ENABLE"; + case BT_HCI_OP_LE_SET_EXT_SCAN_PARAM: + return "LE_SET_EXT_SCAN_PARAM"; + case BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE: + return "LE_SET_EXT_SCAN_ENABLE"; + case BT_HCI_OP_LE_EXT_CREATE_CONN: + return "LE_EXT_CREATE_CONN"; + case BT_HCI_OP_LE_PER_ADV_CREATE_SYNC: + return "LE_PER_ADV_CREATE_SYNC"; + case BT_HCI_OP_LE_PER_ADV_CREATE_SYNC_CANCEL: + return "LE_PER_ADV_CREATE_SYNC_CANCEL"; + case BT_HCI_OP_LE_PER_ADV_TERMINATE_SYNC: + return "LE_PER_ADV_TERMINATE_SYNC"; + case BT_HCI_OP_LE_ADD_DEV_TO_PER_ADV_LIST: + return "LE_ADD_DEV_TO_PER_ADV_LIST"; + case BT_HCI_OP_LE_REM_DEV_FROM_PER_ADV_LIST: + return "LE_REM_DEV_FROM_PER_ADV_LIST"; + case BT_HCI_OP_LE_CLEAR_PER_ADV_LIST: + return "LE_CLEAR_PER_ADV_LIST"; + case BT_HCI_OP_LE_READ_PER_ADV_LIST_SIZE: + return "LE_READ_PER_ADV_LIST_SIZE"; + case BT_HCI_OP_LE_READ_TX_POWER: + return "LE_READ_TX_POWER"; + case BT_HCI_OP_LE_READ_RF_PATH_COMP: + return "LE_READ_RF_PATH_COMP"; + case BT_HCI_OP_LE_WRITE_RF_PATH_COMP: + return "LE_WRITE_RF_PATH_COMP"; + case BT_HCI_OP_LE_SET_PRIVACY_MODE: + return "LE_SET_PRIVACY_MODE"; + default: + return ""; } } STATIC void dump_cmd_pkt(bool tx, uint8_t pkt_len, uint8_t pkt_data[]) { - h4_hci_cmd_pkt_t *pkt = (h4_hci_cmd_pkt_t *) pkt_data; + h4_hci_cmd_pkt_t *pkt = (h4_hci_cmd_pkt_t *)pkt_data; mp_printf(&mp_plat_print, - "%s HCI COMMAND (%x) op: %s (%04x), len: %d, data: ", - tx ? "TX->" : "RX<-", - pkt->pkt_type, - hci_opcode_name(pkt->opcode), pkt->opcode, pkt->param_len); + "%s HCI COMMAND (%x) op: %s (%04x), len: %d, data: ", + tx ? "TX->" : "RX<-", + pkt->pkt_type, + hci_opcode_name(pkt->opcode), pkt->opcode, pkt->param_len); for (size_t i = 0; i < pkt->param_len; i++) { mp_printf(&mp_plat_print, "%02x ", pkt->params[i]); } @@ -278,12 +492,12 @@ STATIC void dump_cmd_pkt(bool tx, uint8_t pkt_len, uint8_t pkt_data[]) { } STATIC void dump_acl_pkt(bool tx, uint8_t pkt_len, uint8_t pkt_data[]) { - h4_hci_acl_pkt_t *pkt = (h4_hci_acl_pkt_t *) pkt_data; - acl_data_t *acl = (acl_data_t *) pkt->data; + h4_hci_acl_pkt_t *pkt = (h4_hci_acl_pkt_t *)pkt_data; + acl_data_t *acl = (acl_data_t *)pkt->data; mp_printf(&mp_plat_print, - "%s HCI ACLDATA (%x) ", - tx ? "TX->" : "RX<-", pkt->pkt_type); + "%s HCI ACLDATA (%x) ", + tx ? "TX->" : "RX<-", pkt->pkt_type); if (pkt->pb != ACL_DATA_PB_MIDDLE && acl->cid == BT_L2CAP_CID_ATT) { // This is the start of a fragmented acl_data packet or is a full packet, @@ -292,14 +506,14 @@ STATIC void dump_acl_pkt(bool tx, uint8_t pkt_len, uint8_t pkt_data[]) { } mp_printf(&mp_plat_print, - "handle: %04x, pb: %d, bc: %d, data_len: %d, ", - pkt->handle, pkt->pb, pkt->bc, pkt->data_len); + "handle: %04x, pb: %d, bc: %d, data_len: %d, ", + pkt->handle, pkt->pb, pkt->bc, pkt->data_len); if (pkt->pb != ACL_DATA_PB_MIDDLE) { // This is the start of a fragmented acl_data packet or is a full packet. mp_printf(&mp_plat_print, - "acl data_len: %d, cid: %04x, data: ", - acl->acl_data_len, acl->cid); + "acl data_len: %d, cid: %04x, data: ", + acl->acl_data_len, acl->cid); for (size_t i = 0; i < acl->acl_data_len; i++) { mp_printf(&mp_plat_print, "%02x ", acl->acl_data[i]); } @@ -316,15 +530,15 @@ STATIC void dump_acl_pkt(bool tx, uint8_t pkt_len, uint8_t pkt_data[]) { } STATIC void dump_evt_pkt(bool tx, uint8_t pkt_len, uint8_t pkt_data[]) { - h4_hci_evt_pkt_t *pkt = (h4_hci_evt_pkt_t *) pkt_data; + h4_hci_evt_pkt_t *pkt = (h4_hci_evt_pkt_t *)pkt_data; mp_printf(&mp_plat_print, - "%s HCI EVENT (%x) evt: %s (%02x), param_len: %d, data: ", - tx ? "TX->" : "RX<-", - pkt->pkt_type, - pkt->evt == BT_HCI_EVT_LE_META_EVENT + "%s HCI EVENT (%x) evt: %s (%02x), param_len: %d, data: ", + tx ? "TX->" : "RX<-", + pkt->pkt_type, + pkt->evt == BT_HCI_EVT_LE_META_EVENT ? hci_evt_le_name(pkt->params[0]) : hci_evt_name(pkt->evt), - pkt->evt, pkt->param_len); + pkt->evt, pkt->param_len); for (size_t i = 0; i < pkt->param_len; i++) { mp_printf(&mp_plat_print, "%02x ", pkt->params[i]); } diff --git a/devices/ble_hci/common-hal/_bleio/hci_include/addr.h b/devices/ble_hci/common-hal/_bleio/hci_include/addr.h index fd74a95e8d..44f057e43d 100644 --- a/devices/ble_hci/common-hal/_bleio/hci_include/addr.h +++ b/devices/ble_hci/common-hal/_bleio/hci_include/addr.h @@ -29,40 +29,36 @@ /** Bluetooth Device Address */ typedef struct { - uint8_t val[6]; + uint8_t val[6]; } bt_addr_t; /** Bluetooth LE Device Address */ typedef struct { - uint8_t type; - bt_addr_t a; + uint8_t type; + bt_addr_t a; } bt_addr_le_t; #define BT_ADDR_ANY ((bt_addr_t[]) { { { 0, 0, 0, 0, 0, 0 } } }) #define BT_ADDR_NONE ((bt_addr_t[]) { { \ - { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } }) + { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } }) #define BT_ADDR_LE_ANY ((bt_addr_le_t[]) { { 0, { { 0, 0, 0, 0, 0, 0 } } } }) #define BT_ADDR_LE_NONE ((bt_addr_le_t[]) { { 0, \ - { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } } }) + { { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff } } } }) -static inline int bt_addr_cmp(const bt_addr_t *a, const bt_addr_t *b) -{ - return memcmp(a, b, sizeof(*a)); +static inline int bt_addr_cmp(const bt_addr_t *a, const bt_addr_t *b) { + return memcmp(a, b, sizeof(*a)); } -static inline int bt_addr_le_cmp(const bt_addr_le_t *a, const bt_addr_le_t *b) -{ - return memcmp(a, b, sizeof(*a)); +static inline int bt_addr_le_cmp(const bt_addr_le_t *a, const bt_addr_le_t *b) { + return memcmp(a, b, sizeof(*a)); } -static inline void bt_addr_copy(bt_addr_t *dst, const bt_addr_t *src) -{ - memcpy(dst, src, sizeof(*dst)); +static inline void bt_addr_copy(bt_addr_t *dst, const bt_addr_t *src) { + memcpy(dst, src, sizeof(*dst)); } -static inline void bt_addr_le_copy(bt_addr_le_t *dst, const bt_addr_le_t *src) -{ - memcpy(dst, src, sizeof(*dst)); +static inline void bt_addr_le_copy(bt_addr_le_t *dst, const bt_addr_le_t *src) { + memcpy(dst, src, sizeof(*dst)); } #define BT_ADDR_IS_RPA(a) (((a)->val[5] & 0xc0) == 0x40) @@ -76,22 +72,20 @@ static inline void bt_addr_le_copy(bt_addr_le_t *dst, const bt_addr_le_t *src) int bt_addr_le_create_nrpa(bt_addr_le_t *addr); int bt_addr_le_create_static(bt_addr_le_t *addr); -static inline bool bt_addr_le_is_rpa(const bt_addr_le_t *addr) -{ - if (addr->type != BT_ADDR_LE_RANDOM) { - return false; - } +static inline bool bt_addr_le_is_rpa(const bt_addr_le_t *addr) { + if (addr->type != BT_ADDR_LE_RANDOM) { + return false; + } - return BT_ADDR_IS_RPA(&addr->a); + return BT_ADDR_IS_RPA(&addr->a); } -static inline bool bt_addr_le_is_identity(const bt_addr_le_t *addr) -{ - if (addr->type == BT_ADDR_LE_PUBLIC) { - return true; - } +static inline bool bt_addr_le_is_identity(const bt_addr_le_t *addr) { + if (addr->type == BT_ADDR_LE_PUBLIC) { + return true; + } - return BT_ADDR_IS_STATIC(&addr->a); + return BT_ADDR_IS_STATIC(&addr->a); } /** diff --git a/devices/ble_hci/common-hal/_bleio/hci_include/att.h b/devices/ble_hci/common-hal/_bleio/hci_include/att.h index 8117a48f45..f292ceb4c3 100644 --- a/devices/ble_hci/common-hal/_bleio/hci_include/att.h +++ b/devices/ble_hci/common-hal/_bleio/hci_include/att.h @@ -12,30 +12,30 @@ #define ZEPHYR_INCLUDE_BLUETOOTH_ATT_H_ /* Error codes for Error response PDU */ -#define BT_ATT_ERR_INVALID_HANDLE 0x01 -#define BT_ATT_ERR_READ_NOT_PERMITTED 0x02 -#define BT_ATT_ERR_WRITE_NOT_PERMITTED 0x03 -#define BT_ATT_ERR_INVALID_PDU 0x04 -#define BT_ATT_ERR_AUTHENTICATION 0x05 -#define BT_ATT_ERR_NOT_SUPPORTED 0x06 -#define BT_ATT_ERR_INVALID_OFFSET 0x07 -#define BT_ATT_ERR_AUTHORIZATION 0x08 -#define BT_ATT_ERR_PREPARE_QUEUE_FULL 0x09 -#define BT_ATT_ERR_ATTRIBUTE_NOT_FOUND 0x0a -#define BT_ATT_ERR_ATTRIBUTE_NOT_LONG 0x0b -#define BT_ATT_ERR_ENCRYPTION_KEY_SIZE 0x0c -#define BT_ATT_ERR_INVALID_ATTRIBUTE_LEN 0x0d -#define BT_ATT_ERR_UNLIKELY 0x0e -#define BT_ATT_ERR_INSUFFICIENT_ENCRYPTION 0x0f -#define BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE 0x10 -#define BT_ATT_ERR_INSUFFICIENT_RESOURCES 0x11 -#define BT_ATT_ERR_DB_OUT_OF_SYNC 0x12 -#define BT_ATT_ERR_VALUE_NOT_ALLOWED 0x13 +#define BT_ATT_ERR_INVALID_HANDLE 0x01 +#define BT_ATT_ERR_READ_NOT_PERMITTED 0x02 +#define BT_ATT_ERR_WRITE_NOT_PERMITTED 0x03 +#define BT_ATT_ERR_INVALID_PDU 0x04 +#define BT_ATT_ERR_AUTHENTICATION 0x05 +#define BT_ATT_ERR_NOT_SUPPORTED 0x06 +#define BT_ATT_ERR_INVALID_OFFSET 0x07 +#define BT_ATT_ERR_AUTHORIZATION 0x08 +#define BT_ATT_ERR_PREPARE_QUEUE_FULL 0x09 +#define BT_ATT_ERR_ATTRIBUTE_NOT_FOUND 0x0a +#define BT_ATT_ERR_ATTRIBUTE_NOT_LONG 0x0b +#define BT_ATT_ERR_ENCRYPTION_KEY_SIZE 0x0c +#define BT_ATT_ERR_INVALID_ATTRIBUTE_LEN 0x0d +#define BT_ATT_ERR_UNLIKELY 0x0e +#define BT_ATT_ERR_INSUFFICIENT_ENCRYPTION 0x0f +#define BT_ATT_ERR_UNSUPPORTED_GROUP_TYPE 0x10 +#define BT_ATT_ERR_INSUFFICIENT_RESOURCES 0x11 +#define BT_ATT_ERR_DB_OUT_OF_SYNC 0x12 +#define BT_ATT_ERR_VALUE_NOT_ALLOWED 0x13 /* Common Profile Error Codes (from CSS) */ -#define BT_ATT_ERR_WRITE_REQ_REJECTED 0xfc -#define BT_ATT_ERR_CCC_IMPROPER_CONF 0xfd -#define BT_ATT_ERR_PROCEDURE_IN_PROGRESS 0xfe -#define BT_ATT_ERR_OUT_OF_RANGE 0xff +#define BT_ATT_ERR_WRITE_REQ_REJECTED 0xfc +#define BT_ATT_ERR_CCC_IMPROPER_CONF 0xfd +#define BT_ATT_ERR_PROCEDURE_IN_PROGRESS 0xfe +#define BT_ATT_ERR_OUT_OF_RANGE 0xff #endif /* ZEPHYR_INCLUDE_BLUETOOTH_ATT_H_ */ diff --git a/devices/ble_hci/common-hal/_bleio/hci_include/att_internal.h b/devices/ble_hci/common-hal/_bleio/hci_include/att_internal.h index b8efccaf46..820246dec1 100644 --- a/devices/ble_hci/common-hal/_bleio/hci_include/att_internal.h +++ b/devices/ble_hci/common-hal/_bleio/hci_include/att_internal.h @@ -13,260 +13,260 @@ // for __packed #include -#define BT_EATT_PSM 0x27 -#define BT_ATT_DEFAULT_LE_MTU 23 -#define BT_ATT_TIMEOUT K_SECONDS(30) +#define BT_EATT_PSM 0x27 +#define BT_ATT_DEFAULT_LE_MTU 23 +#define BT_ATT_TIMEOUT K_SECONDS(30) -//FIX #if BT_L2CAP_RX_MTU < CONFIG_BT_L2CAP_TX_MTU +// FIX #if BT_L2CAP_RX_MTU < CONFIG_BT_L2CAP_TX_MTU // #define BT_ATT_MTU BT_L2CAP_RX_MTU // #else // #define BT_ATT_MTU CONFIG_BT_L2CAP_TX_MTU // #endif struct bt_att_hdr { - uint8_t code; + uint8_t code; } __packed; -#define BT_ATT_OP_ERROR_RSP 0x01 +#define BT_ATT_OP_ERROR_RSP 0x01 struct bt_att_error_rsp { - uint8_t request; - uint16_t handle; - uint8_t error; + uint8_t request; + uint16_t handle; + uint8_t error; } __packed; -#define BT_ATT_OP_MTU_REQ 0x02 +#define BT_ATT_OP_MTU_REQ 0x02 struct bt_att_exchange_mtu_req { - uint16_t mtu; + uint16_t mtu; } __packed; -#define BT_ATT_OP_MTU_RSP 0x03 +#define BT_ATT_OP_MTU_RSP 0x03 struct bt_att_exchange_mtu_rsp { - uint16_t mtu; + uint16_t mtu; } __packed; /* Find Information Request */ -#define BT_ATT_OP_FIND_INFO_REQ 0x04 +#define BT_ATT_OP_FIND_INFO_REQ 0x04 struct bt_att_find_info_req { - uint16_t start_handle; - uint16_t end_handle; + uint16_t start_handle; + uint16_t end_handle; } __packed; /* Format field values for BT_ATT_OP_FIND_INFO_RSP */ -#define BT_ATT_INFO_16 0x01 -#define BT_ATT_INFO_128 0x02 +#define BT_ATT_INFO_16 0x01 +#define BT_ATT_INFO_128 0x02 struct bt_att_info_16 { - uint16_t handle; - uint16_t uuid; + uint16_t handle; + uint16_t uuid; } __packed; struct bt_att_info_128 { - uint16_t handle; - uint8_t uuid[16]; + uint16_t handle; + uint8_t uuid[16]; } __packed; /* Find Information Response */ -#define BT_ATT_OP_FIND_INFO_RSP 0x05 +#define BT_ATT_OP_FIND_INFO_RSP 0x05 struct bt_att_find_info_rsp { - uint8_t format; - uint8_t info[]; + uint8_t format; + uint8_t info[]; } __packed; /* Find By Type Value Request */ -#define BT_ATT_OP_FIND_TYPE_REQ 0x06 +#define BT_ATT_OP_FIND_TYPE_REQ 0x06 struct bt_att_find_type_req { - uint16_t start_handle; - uint16_t end_handle; - uint16_t type; - uint8_t value[]; + uint16_t start_handle; + uint16_t end_handle; + uint16_t type; + uint8_t value[]; } __packed; struct bt_att_handle_group { - uint16_t start_handle; - uint16_t end_handle; + uint16_t start_handle; + uint16_t end_handle; } __packed; /* Find By Type Value Response */ -#define BT_ATT_OP_FIND_TYPE_RSP 0x07 +#define BT_ATT_OP_FIND_TYPE_RSP 0x07 struct bt_att_find_type_rsp { - uint8_t _dummy[0]; - struct bt_att_handle_group list[]; + uint8_t _dummy[0]; + struct bt_att_handle_group list[]; } __packed; /* Read By Type Request */ -#define BT_ATT_OP_READ_TYPE_REQ 0x08 +#define BT_ATT_OP_READ_TYPE_REQ 0x08 struct bt_att_read_type_req { - uint16_t start_handle; - uint16_t end_handle; - uint8_t uuid[]; + uint16_t start_handle; + uint16_t end_handle; + uint8_t uuid[]; } __packed; struct bt_att_data { - uint16_t handle; - uint8_t value[]; + uint16_t handle; + uint8_t value[]; } __packed; /* Read By Type Response */ -#define BT_ATT_OP_READ_TYPE_RSP 0x09 +#define BT_ATT_OP_READ_TYPE_RSP 0x09 struct bt_att_read_type_rsp { - uint8_t len; - struct bt_att_data data[]; + uint8_t len; + struct bt_att_data data[]; } __packed; /* Read Request */ -#define BT_ATT_OP_READ_REQ 0x0a +#define BT_ATT_OP_READ_REQ 0x0a struct bt_att_read_req { - uint16_t handle; + uint16_t handle; } __packed; /* Read Response */ -#define BT_ATT_OP_READ_RSP 0x0b +#define BT_ATT_OP_READ_RSP 0x0b struct bt_att_read_rsp { - uint8_t _dummy[0]; - uint8_t value[]; + uint8_t _dummy[0]; + uint8_t value[]; } __packed; /* Read Blob Request */ -#define BT_ATT_OP_READ_BLOB_REQ 0x0c +#define BT_ATT_OP_READ_BLOB_REQ 0x0c struct bt_att_read_blob_req { - uint16_t handle; - uint16_t offset; + uint16_t handle; + uint16_t offset; } __packed; /* Read Blob Response */ -#define BT_ATT_OP_READ_BLOB_RSP 0x0d +#define BT_ATT_OP_READ_BLOB_RSP 0x0d struct bt_att_read_blob_rsp { - uint8_t _dummy[0]; - uint8_t value[]; + uint8_t _dummy[0]; + uint8_t value[]; } __packed; /* Read Multiple Request */ -#define BT_ATT_READ_MULT_MIN_LEN_REQ 0x04 +#define BT_ATT_READ_MULT_MIN_LEN_REQ 0x04 -#define BT_ATT_OP_READ_MULT_REQ 0x0e +#define BT_ATT_OP_READ_MULT_REQ 0x0e struct bt_att_read_mult_req { - uint8_t _dummy[0]; - uint16_t handles[]; + uint8_t _dummy[0]; + uint16_t handles[]; } __packed; /* Read Multiple Respose */ -#define BT_ATT_OP_READ_MULT_RSP 0x0f +#define BT_ATT_OP_READ_MULT_RSP 0x0f struct bt_att_read_mult_rsp { - uint8_t _dummy[0]; - uint8_t value[]; + uint8_t _dummy[0]; + uint8_t value[]; } __packed; /* Read by Group Type Request */ -#define BT_ATT_OP_READ_GROUP_REQ 0x10 +#define BT_ATT_OP_READ_GROUP_REQ 0x10 struct bt_att_read_group_req { - uint16_t start_handle; - uint16_t end_handle; - uint8_t uuid[]; + uint16_t start_handle; + uint16_t end_handle; + uint8_t uuid[]; } __packed; struct bt_att_group_data { - uint16_t start_handle; - uint16_t end_handle; - uint8_t value[]; + uint16_t start_handle; + uint16_t end_handle; + uint8_t value[]; } __packed; /* Read by Group Type Response */ -#define BT_ATT_OP_READ_GROUP_RSP 0x11 +#define BT_ATT_OP_READ_GROUP_RSP 0x11 struct bt_att_read_group_rsp { - uint8_t len; - struct bt_att_group_data data[]; + uint8_t len; + struct bt_att_group_data data[]; } __packed; /* Write Request */ -#define BT_ATT_OP_WRITE_REQ 0x12 +#define BT_ATT_OP_WRITE_REQ 0x12 struct bt_att_write_req { - uint16_t handle; - uint8_t value[]; + uint16_t handle; + uint8_t value[]; } __packed; /* Write Response */ -#define BT_ATT_OP_WRITE_RSP 0x13 +#define BT_ATT_OP_WRITE_RSP 0x13 /* Prepare Write Request */ -#define BT_ATT_OP_PREPARE_WRITE_REQ 0x16 +#define BT_ATT_OP_PREPARE_WRITE_REQ 0x16 struct bt_att_prepare_write_req { - uint16_t handle; - uint16_t offset; - uint8_t value[]; + uint16_t handle; + uint16_t offset; + uint8_t value[]; } __packed; /* Prepare Write Respond */ -#define BT_ATT_OP_PREPARE_WRITE_RSP 0x17 +#define BT_ATT_OP_PREPARE_WRITE_RSP 0x17 struct bt_att_prepare_write_rsp { - uint16_t handle; - uint16_t offset; - uint8_t value[]; + uint16_t handle; + uint16_t offset; + uint8_t value[]; } __packed; /* Execute Write Request */ -#define BT_ATT_FLAG_CANCEL 0x00 -#define BT_ATT_FLAG_EXEC 0x01 +#define BT_ATT_FLAG_CANCEL 0x00 +#define BT_ATT_FLAG_EXEC 0x01 -#define BT_ATT_OP_EXEC_WRITE_REQ 0x18 +#define BT_ATT_OP_EXEC_WRITE_REQ 0x18 struct bt_att_exec_write_req { - uint8_t flags; + uint8_t flags; } __packed; /* Execute Write Response */ -#define BT_ATT_OP_EXEC_WRITE_RSP 0x19 +#define BT_ATT_OP_EXEC_WRITE_RSP 0x19 /* Handle Value Notification */ -#define BT_ATT_OP_NOTIFY 0x1b +#define BT_ATT_OP_NOTIFY 0x1b struct bt_att_notify { - uint16_t handle; - uint8_t value[]; + uint16_t handle; + uint8_t value[]; } __packed; /* Handle Value Indication */ -#define BT_ATT_OP_INDICATE 0x1d +#define BT_ATT_OP_INDICATE 0x1d struct bt_att_indicate { - uint16_t handle; - uint8_t value[]; + uint16_t handle; + uint8_t value[]; } __packed; /* Handle Value Confirm */ -#define BT_ATT_OP_CONFIRM 0x1e +#define BT_ATT_OP_CONFIRM 0x1e struct bt_att_signature { - uint8_t value[12]; + uint8_t value[12]; } __packed; -#define BT_ATT_OP_READ_MULT_VL_REQ 0x20 +#define BT_ATT_OP_READ_MULT_VL_REQ 0x20 struct bt_att_read_mult_vl_req { - uint8_t _dummy[0]; - uint16_t handles[]; + uint8_t _dummy[0]; + uint16_t handles[]; } __packed; /* Read Multiple Respose */ -#define BT_ATT_OP_READ_MULT_VL_RSP 0x21 +#define BT_ATT_OP_READ_MULT_VL_RSP 0x21 struct bt_att_read_mult_vl_rsp { - uint16_t len; - uint8_t value[]; + uint16_t len; + uint8_t value[]; } __packed; /* Handle Multiple Value Notification */ -#define BT_ATT_OP_NOTIFY_MULT 0x23 +#define BT_ATT_OP_NOTIFY_MULT 0x23 struct bt_att_notify_mult { - uint16_t handle; - uint16_t len; - uint8_t value[]; + uint16_t handle; + uint16_t len; + uint8_t value[]; } __packed; /* Write Command */ -#define BT_ATT_OP_WRITE_CMD 0x52 +#define BT_ATT_OP_WRITE_CMD 0x52 struct bt_att_write_cmd { - uint16_t handle; - uint8_t value[]; + uint16_t handle; + uint8_t value[]; } __packed; /* Signed Write Command */ -#define BT_ATT_OP_SIGNED_WRITE_CMD 0xd2 +#define BT_ATT_OP_SIGNED_WRITE_CMD 0xd2 struct bt_att_signed_write_cmd { - uint16_t handle; - uint8_t value[]; + uint16_t handle; + uint8_t value[]; } __packed; diff --git a/devices/ble_hci/common-hal/_bleio/hci_include/hci.h b/devices/ble_hci/common-hal/_bleio/hci_include/hci.h index 797278946a..b5f9506181 100644 --- a/devices/ble_hci/common-hal/_bleio/hci_include/hci.h +++ b/devices/ble_hci/common-hal/_bleio/hci_include/hci.h @@ -34,8 +34,8 @@ #define BT_ENC_KEY_SIZE_MAX 0x10 struct bt_hci_evt_hdr { - uint8_t evt; - uint8_t len; + uint8_t evt; + uint8_t len; } __packed; #define BT_HCI_EVT_HDR_SIZE 2 @@ -54,14 +54,14 @@ struct bt_hci_evt_hdr { #define bt_acl_handle_pack(h, f) ((h) | ((f) << 12)) struct bt_hci_acl_hdr { - uint16_t handle; - uint16_t len; + uint16_t handle; + uint16_t len; } __packed; #define BT_HCI_ACL_HDR_SIZE 4 struct bt_hci_cmd_hdr { - uint16_t opcode; - uint8_t param_len; + uint16_t opcode; + uint8_t param_len; } __packed; #define BT_HCI_CMD_HDR_SIZE 3 @@ -125,24 +125,24 @@ struct bt_hci_cmd_hdr { #define BT_LE_FEAT_BIT_PATH_LOSS_MONITOR 35 #define BT_LE_FEAT_TEST(feat, n) (feat[(n) >> 3] & \ - BIT((n) & 7)) + BIT((n) & 7)) #define BT_FEAT_LE_ENCR(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_ENC) + BT_LE_FEAT_BIT_ENC) #define BT_FEAT_LE_CONN_PARAM_REQ_PROC(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_CONN_PARAM_REQ) + BT_LE_FEAT_BIT_CONN_PARAM_REQ) #define BT_FEAT_LE_SLAVE_FEATURE_XCHG(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_SLAVE_FEAT_REQ) + BT_LE_FEAT_BIT_SLAVE_FEAT_REQ) #define BT_FEAT_LE_DLE(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_DLE) + BT_LE_FEAT_BIT_DLE) #define BT_FEAT_LE_PHY_2M(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_PHY_2M) + BT_LE_FEAT_BIT_PHY_2M) #define BT_FEAT_LE_PHY_CODED(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_PHY_CODED) + BT_LE_FEAT_BIT_PHY_CODED) #define BT_FEAT_LE_PRIVACY(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_PRIVACY) + BT_LE_FEAT_BIT_PRIVACY) #define BT_FEAT_LE_EXT_ADV(feat) BT_LE_FEAT_TEST(feat, \ - BT_LE_FEAT_BIT_EXT_ADV) + BT_LE_FEAT_BIT_EXT_ADV) /* LE States */ #define BT_LE_STATES_SLAVE_CONN_ADV(states) (states & 0x0000004000000000) @@ -186,15 +186,15 @@ struct bt_hci_cmd_hdr { #define ESCO_PKT_MASK (HCI_PKT_TYPE_ESCO_HV1 | \ - HCI_PKT_TYPE_ESCO_HV2 | \ - HCI_PKT_TYPE_ESCO_HV3) + HCI_PKT_TYPE_ESCO_HV2 | \ + HCI_PKT_TYPE_ESCO_HV3) #define SCO_PKT_MASK (HCI_PKT_TYPE_HV1 | \ - HCI_PKT_TYPE_HV2 | \ - HCI_PKT_TYPE_HV3) + HCI_PKT_TYPE_HV2 | \ + HCI_PKT_TYPE_HV3) #define EDR_ESCO_PKT_MASK (HCI_PKT_TYPE_ESCO_2EV3 | \ - HCI_PKT_TYPE_ESCO_3EV3 | \ - HCI_PKT_TYPE_ESCO_2EV5 | \ - HCI_PKT_TYPE_ESCO_3EV5) + HCI_PKT_TYPE_ESCO_3EV3 | \ + HCI_PKT_TYPE_ESCO_2EV5 | \ + HCI_PKT_TYPE_ESCO_3EV5) /* HCI BR/EDR link types */ #define BT_HCI_SCO 0x00 @@ -213,7 +213,7 @@ struct bt_hci_cmd_hdr { #define BT_OP(ogf, ocf) ((ocf) | ((ogf) << 10)) /* Invalid opcode */ -#define BT_OP_NOP 0x0000 +#define BT_OP_NOP 0x0000 /* Obtain OGF from OpCode */ #define BT_OGF(opcode) (((opcode) >> 10) & BIT_MASK(6)) @@ -222,192 +222,192 @@ struct bt_hci_cmd_hdr { #define BT_HCI_OP_INQUIRY BT_OP(BT_OGF_LINK_CTRL, 0x0001) struct bt_hci_op_inquiry { - uint8_t lap[3]; - uint8_t length; - uint8_t num_rsp; + uint8_t lap[3]; + uint8_t length; + uint8_t num_rsp; } __packed; #define BT_HCI_OP_INQUIRY_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x0002) #define BT_HCI_OP_CONNECT BT_OP(BT_OGF_LINK_CTRL, 0x0005) struct bt_hci_cp_connect { - bt_addr_t bdaddr; - uint16_t packet_type; - uint8_t pscan_rep_mode; - uint8_t reserved; - uint16_t clock_offset; - uint8_t allow_role_switch; + bt_addr_t bdaddr; + uint16_t packet_type; + uint8_t pscan_rep_mode; + uint8_t reserved; + uint16_t clock_offset; + uint8_t allow_role_switch; } __packed; #define BT_HCI_OP_DISCONNECT BT_OP(BT_OGF_LINK_CTRL, 0x0006) struct bt_hci_cp_disconnect { - uint16_t handle; - uint8_t reason; + uint16_t handle; + uint8_t reason; } __packed; #define BT_HCI_OP_CONNECT_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x0008) struct bt_hci_cp_connect_cancel { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; struct bt_hci_rp_connect_cancel { - uint8_t status; - bt_addr_t bdaddr; + uint8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_ACCEPT_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x0009) struct bt_hci_cp_accept_conn_req { - bt_addr_t bdaddr; - uint8_t role; + bt_addr_t bdaddr; + uint8_t role; } __packed; #define BT_HCI_OP_SETUP_SYNC_CONN BT_OP(BT_OGF_LINK_CTRL, 0x0028) struct bt_hci_cp_setup_sync_conn { - uint16_t handle; - uint32_t tx_bandwidth; - uint32_t rx_bandwidth; - uint16_t max_latency; - uint16_t content_format; - uint8_t retrans_effort; - uint16_t pkt_type; + uint16_t handle; + uint32_t tx_bandwidth; + uint32_t rx_bandwidth; + uint16_t max_latency; + uint16_t content_format; + uint8_t retrans_effort; + uint16_t pkt_type; } __packed; #define BT_HCI_OP_ACCEPT_SYNC_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x0029) struct bt_hci_cp_accept_sync_conn_req { - bt_addr_t bdaddr; - uint32_t tx_bandwidth; - uint32_t rx_bandwidth; - uint16_t max_latency; - uint16_t content_format; - uint8_t retrans_effort; - uint16_t pkt_type; + bt_addr_t bdaddr; + uint32_t tx_bandwidth; + uint32_t rx_bandwidth; + uint16_t max_latency; + uint16_t content_format; + uint8_t retrans_effort; + uint16_t pkt_type; } __packed; #define BT_HCI_OP_REJECT_CONN_REQ BT_OP(BT_OGF_LINK_CTRL, 0x000a) struct bt_hci_cp_reject_conn_req { - bt_addr_t bdaddr; - uint8_t reason; + bt_addr_t bdaddr; + uint8_t reason; } __packed; #define BT_HCI_OP_LINK_KEY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000b) struct bt_hci_cp_link_key_reply { - bt_addr_t bdaddr; - uint8_t link_key[16]; + bt_addr_t bdaddr; + uint8_t link_key[16]; } __packed; #define BT_HCI_OP_LINK_KEY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000c) struct bt_hci_cp_link_key_neg_reply { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_PIN_CODE_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000d) struct bt_hci_cp_pin_code_reply { - bt_addr_t bdaddr; - uint8_t pin_len; - uint8_t pin_code[16]; + bt_addr_t bdaddr; + uint8_t pin_len; + uint8_t pin_code[16]; } __packed; struct bt_hci_rp_pin_code_reply { - uint8_t status; - bt_addr_t bdaddr; + uint8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_PIN_CODE_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x000e) struct bt_hci_cp_pin_code_neg_reply { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; struct bt_hci_rp_pin_code_neg_reply { - uint8_t status; - bt_addr_t bdaddr; + uint8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_AUTH_REQUESTED BT_OP(BT_OGF_LINK_CTRL, 0x0011) struct bt_hci_cp_auth_requested { - uint16_t handle; + uint16_t handle; } __packed; #define BT_HCI_OP_SET_CONN_ENCRYPT BT_OP(BT_OGF_LINK_CTRL, 0x0013) struct bt_hci_cp_set_conn_encrypt { - uint16_t handle; - uint8_t encrypt; + uint16_t handle; + uint8_t encrypt; } __packed; #define BT_HCI_OP_REMOTE_NAME_REQUEST BT_OP(BT_OGF_LINK_CTRL, 0x0019) struct bt_hci_cp_remote_name_request { - bt_addr_t bdaddr; - uint8_t pscan_rep_mode; - uint8_t reserved; - uint16_t clock_offset; + bt_addr_t bdaddr; + uint8_t pscan_rep_mode; + uint8_t reserved; + uint16_t clock_offset; } __packed; #define BT_HCI_OP_REMOTE_NAME_CANCEL BT_OP(BT_OGF_LINK_CTRL, 0x001a) struct bt_hci_cp_remote_name_cancel { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; struct bt_hci_rp_remote_name_cancel { - uint8_t status; - bt_addr_t bdaddr; + uint8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_READ_REMOTE_FEATURES BT_OP(BT_OGF_LINK_CTRL, 0x001b) struct bt_hci_cp_read_remote_features { - uint16_t handle; + uint16_t handle; } __packed; #define BT_HCI_OP_READ_REMOTE_EXT_FEATURES BT_OP(BT_OGF_LINK_CTRL, 0x001c) struct bt_hci_cp_read_remote_ext_features { - uint16_t handle; - uint8_t page; + uint16_t handle; + uint8_t page; } __packed; #define BT_HCI_OP_READ_REMOTE_VERSION_INFO BT_OP(BT_OGF_LINK_CTRL, 0x001d) struct bt_hci_cp_read_remote_version_info { - uint16_t handle; + uint16_t handle; } __packed; #define BT_HCI_OP_IO_CAPABILITY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002b) struct bt_hci_cp_io_capability_reply { - bt_addr_t bdaddr; - uint8_t capability; - uint8_t oob_data; - uint8_t authentication; + bt_addr_t bdaddr; + uint8_t capability; + uint8_t oob_data; + uint8_t authentication; } __packed; #define BT_HCI_OP_USER_CONFIRM_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002c) #define BT_HCI_OP_USER_CONFIRM_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002d) struct bt_hci_cp_user_confirm_reply { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; struct bt_hci_rp_user_confirm_reply { - uint8_t status; - bt_addr_t bdaddr; + uint8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_USER_PASSKEY_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002e) struct bt_hci_cp_user_passkey_reply { - bt_addr_t bdaddr; - uint32_t passkey; + bt_addr_t bdaddr; + uint32_t passkey; } __packed; #define BT_HCI_OP_USER_PASSKEY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x002f) struct bt_hci_cp_user_passkey_neg_reply { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_IO_CAPABILITY_NEG_REPLY BT_OP(BT_OGF_LINK_CTRL, 0x0034) struct bt_hci_cp_io_capability_neg_reply { - bt_addr_t bdaddr; - uint8_t reason; + bt_addr_t bdaddr; + uint8_t reason; } __packed; #define BT_HCI_OP_SET_EVENT_MASK BT_OP(BT_OGF_BASEBAND, 0x0001) struct bt_hci_cp_set_event_mask { - uint8_t events[8]; + uint8_t events[8]; } __packed; #define BT_HCI_OP_RESET BT_OP(BT_OGF_BASEBAND, 0x0003) #define BT_HCI_OP_WRITE_LOCAL_NAME BT_OP(BT_OGF_BASEBAND, 0x0013) struct bt_hci_write_local_name { - uint8_t local_name[248]; + uint8_t local_name[248]; } __packed; #define BT_HCI_OP_WRITE_PAGE_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x0018) @@ -421,88 +421,88 @@ struct bt_hci_write_local_name { #define BT_TX_POWER_LEVEL_MAX 0x01 #define BT_HCI_OP_READ_TX_POWER_LEVEL BT_OP(BT_OGF_BASEBAND, 0x002d) struct bt_hci_cp_read_tx_power_level { - uint16_t handle; - uint8_t type; + uint16_t handle; + uint8_t type; } __packed; struct bt_hci_rp_read_tx_power_level { - uint8_t status; - uint16_t handle; - int8_t tx_power_level; + uint8_t status; + uint16_t handle; + int8_t tx_power_level; } __packed; #define BT_HCI_CTL_TO_HOST_FLOW_DISABLE 0x00 #define BT_HCI_CTL_TO_HOST_FLOW_ENABLE 0x01 #define BT_HCI_OP_SET_CTL_TO_HOST_FLOW BT_OP(BT_OGF_BASEBAND, 0x0031) struct bt_hci_cp_set_ctl_to_host_flow { - uint8_t flow_enable; + uint8_t flow_enable; } __packed; #define BT_HCI_OP_HOST_BUFFER_SIZE BT_OP(BT_OGF_BASEBAND, 0x0033) struct bt_hci_cp_host_buffer_size { - uint16_t acl_mtu; - uint8_t sco_mtu; - uint16_t acl_pkts; - uint16_t sco_pkts; + uint16_t acl_mtu; + uint8_t sco_mtu; + uint16_t acl_pkts; + uint16_t sco_pkts; } __packed; struct bt_hci_handle_count { - uint16_t handle; - uint16_t count; + uint16_t handle; + uint16_t count; } __packed; #define BT_HCI_OP_HOST_NUM_COMPLETED_PACKETS BT_OP(BT_OGF_BASEBAND, 0x0035) struct bt_hci_cp_host_num_completed_packets { - uint8_t num_handles; - struct bt_hci_handle_count h[]; + uint8_t num_handles; + struct bt_hci_handle_count h[]; } __packed; #define BT_HCI_OP_WRITE_INQUIRY_MODE BT_OP(BT_OGF_BASEBAND, 0x0045) struct bt_hci_cp_write_inquiry_mode { - uint8_t mode; + uint8_t mode; } __packed; #define BT_HCI_OP_WRITE_SSP_MODE BT_OP(BT_OGF_BASEBAND, 0x0056) struct bt_hci_cp_write_ssp_mode { - uint8_t mode; + uint8_t mode; } __packed; #define BT_HCI_OP_SET_EVENT_MASK_PAGE_2 BT_OP(BT_OGF_BASEBAND, 0x0063) struct bt_hci_cp_set_event_mask_page_2 { - uint8_t events_page_2[8]; + uint8_t events_page_2[8]; } __packed; #define BT_HCI_OP_LE_WRITE_LE_HOST_SUPP BT_OP(BT_OGF_BASEBAND, 0x006d) struct bt_hci_cp_write_le_host_supp { - uint8_t le; - uint8_t simul; + uint8_t le; + uint8_t simul; } __packed; #define BT_HCI_OP_WRITE_SC_HOST_SUPP BT_OP(BT_OGF_BASEBAND, 0x007a) struct bt_hci_cp_write_sc_host_supp { - uint8_t sc_support; + uint8_t sc_support; } __packed; #define BT_HCI_OP_READ_AUTH_PAYLOAD_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x007b) struct bt_hci_cp_read_auth_payload_timeout { - uint16_t handle; + uint16_t handle; } __packed; struct bt_hci_rp_read_auth_payload_timeout { - uint8_t status; - uint16_t handle; - uint16_t auth_payload_timeout; + uint8_t status; + uint16_t handle; + uint16_t auth_payload_timeout; } __packed; #define BT_HCI_OP_WRITE_AUTH_PAYLOAD_TIMEOUT BT_OP(BT_OGF_BASEBAND, 0x007c) struct bt_hci_cp_write_auth_payload_timeout { - uint16_t handle; - uint16_t auth_payload_timeout; + uint16_t handle; + uint16_t auth_payload_timeout; } __packed; struct bt_hci_rp_write_auth_payload_timeout { - uint8_t status; - uint16_t handle; + uint8_t status; + uint16_t handle; } __packed; /* HCI version from Assigned Numbers */ @@ -521,60 +521,60 @@ struct bt_hci_rp_write_auth_payload_timeout { #define BT_HCI_OP_READ_LOCAL_VERSION_INFO BT_OP(BT_OGF_INFO, 0x0001) struct bt_hci_rp_read_local_version_info { - uint8_t status; - uint8_t hci_version; - uint16_t hci_revision; - uint8_t lmp_version; - uint16_t manufacturer; - uint16_t lmp_subversion; + uint8_t status; + uint8_t hci_version; + uint16_t hci_revision; + uint8_t lmp_version; + uint16_t manufacturer; + uint16_t lmp_subversion; } __packed; #define BT_HCI_OP_READ_SUPPORTED_COMMANDS BT_OP(BT_OGF_INFO, 0x0002) struct bt_hci_rp_read_supported_commands { - uint8_t status; - uint8_t commands[64]; + uint8_t status; + uint8_t commands[64]; } __packed; #define BT_HCI_OP_READ_LOCAL_EXT_FEATURES BT_OP(BT_OGF_INFO, 0x0004) struct bt_hci_cp_read_local_ext_features { - uint8_t page; + uint8_t page; }; struct bt_hci_rp_read_local_ext_features { - uint8_t status; - uint8_t page; - uint8_t max_page; - uint8_t ext_features[8]; + uint8_t status; + uint8_t page; + uint8_t max_page; + uint8_t ext_features[8]; } __packed; #define BT_HCI_OP_READ_LOCAL_FEATURES BT_OP(BT_OGF_INFO, 0x0003) struct bt_hci_rp_read_local_features { - uint8_t status; - uint8_t features[8]; + uint8_t status; + uint8_t features[8]; } __packed; #define BT_HCI_OP_READ_BUFFER_SIZE BT_OP(BT_OGF_INFO, 0x0005) struct bt_hci_rp_read_buffer_size { - uint8_t status; - uint16_t acl_max_len; - uint8_t sco_max_len; - uint16_t acl_max_num; - uint16_t sco_max_num; + uint8_t status; + uint16_t acl_max_len; + uint8_t sco_max_len; + uint16_t acl_max_num; + uint16_t sco_max_num; } __packed; #define BT_HCI_OP_READ_BD_ADDR BT_OP(BT_OGF_INFO, 0x0009) struct bt_hci_rp_read_bd_addr { - uint8_t status; - bt_addr_t bdaddr; + uint8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_OP_READ_RSSI BT_OP(BT_OGF_STATUS, 0x0005) struct bt_hci_cp_read_rssi { - uint16_t handle; + uint16_t handle; } __packed; struct bt_hci_rp_read_rssi { - uint8_t status; - uint16_t handle; - int8_t rssi; + uint8_t status; + uint16_t handle; + int8_t rssi; } __packed; #define BT_HCI_ENCRYPTION_KEY_SIZE_MIN 7 @@ -582,37 +582,37 @@ struct bt_hci_rp_read_rssi { #define BT_HCI_OP_READ_ENCRYPTION_KEY_SIZE BT_OP(BT_OGF_STATUS, 0x0008) struct bt_hci_cp_read_encryption_key_size { - uint16_t handle; + uint16_t handle; } __packed; struct bt_hci_rp_read_encryption_key_size { - uint8_t status; - uint16_t handle; - uint8_t key_size; + uint8_t status; + uint16_t handle; + uint8_t key_size; } __packed; /* BLE */ #define BT_HCI_OP_LE_SET_EVENT_MASK BT_OP(BT_OGF_LE, 0x0001) struct bt_hci_cp_le_set_event_mask { - uint8_t events[8]; + uint8_t events[8]; } __packed; #define BT_HCI_OP_LE_READ_BUFFER_SIZE BT_OP(BT_OGF_LE, 0x0002) struct bt_hci_rp_le_read_buffer_size { - uint8_t status; - uint16_t le_max_len; - uint8_t le_max_num; + uint8_t status; + uint16_t le_max_len; + uint8_t le_max_num; } __packed; #define BT_HCI_OP_LE_READ_LOCAL_FEATURES BT_OP(BT_OGF_LE, 0x0003) struct bt_hci_rp_le_read_local_features { - uint8_t status; - uint8_t features[8]; + uint8_t status; + uint8_t features[8]; } __packed; #define BT_HCI_OP_LE_SET_RANDOM_ADDRESS BT_OP(BT_OGF_LE, 0x0005) struct bt_hci_cp_le_set_random_address { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; /* LE Advertising Types (LE Advertising Parameters Set)*/ @@ -638,31 +638,31 @@ struct bt_hci_cp_le_set_random_address { #define BT_HCI_OP_LE_SET_ADV_PARAM BT_OP(BT_OGF_LE, 0x0006) struct bt_hci_cp_le_set_adv_param { - uint16_t min_interval; - uint16_t max_interval; - uint8_t type; - uint8_t own_addr_type; - bt_addr_le_t direct_addr; - uint8_t channel_map; - uint8_t filter_policy; + uint16_t min_interval; + uint16_t max_interval; + uint8_t type; + uint8_t own_addr_type; + bt_addr_le_t direct_addr; + uint8_t channel_map; + uint8_t filter_policy; } __packed; #define BT_HCI_OP_LE_READ_ADV_CHAN_TX_POWER BT_OP(BT_OGF_LE, 0x0007) struct bt_hci_rp_le_read_chan_tx_power { - uint8_t status; - int8_t tx_power_level; + uint8_t status; + int8_t tx_power_level; } __packed; #define BT_HCI_OP_LE_SET_ADV_DATA BT_OP(BT_OGF_LE, 0x0008) struct bt_hci_cp_le_set_adv_data { - uint8_t len; - uint8_t data[31]; + uint8_t len; + uint8_t data[31]; } __packed; #define BT_HCI_OP_LE_SET_SCAN_RSP_DATA BT_OP(BT_OGF_LE, 0x0009) struct bt_hci_cp_le_set_scan_rsp_data { - uint8_t len; - uint8_t data[31]; + uint8_t len; + uint8_t data[31]; } __packed; #define BT_HCI_LE_ADV_DISABLE 0x00 @@ -670,7 +670,7 @@ struct bt_hci_cp_le_set_scan_rsp_data { #define BT_HCI_OP_LE_SET_ADV_ENABLE BT_OP(BT_OGF_LE, 0x000a) struct bt_hci_cp_le_set_adv_enable { - uint8_t enable; + uint8_t enable; } __packed; /* Scan types */ @@ -682,11 +682,11 @@ struct bt_hci_cp_le_set_adv_enable { #define BT_HCI_LE_SCAN_FP_USE_WHITELIST 0x01 struct bt_hci_cp_le_set_scan_param { - uint8_t scan_type; - uint16_t interval; - uint16_t window; - uint8_t addr_type; - uint8_t filter_policy; + uint8_t scan_type; + uint16_t interval; + uint16_t window; + uint8_t addr_type; + uint8_t filter_policy; } __packed; #define BT_HCI_OP_LE_SET_SCAN_ENABLE BT_OP(BT_OGF_LE, 0x000c) @@ -698,8 +698,8 @@ struct bt_hci_cp_le_set_scan_param { #define BT_HCI_LE_SCAN_FILTER_DUP_ENABLE 0x01 struct bt_hci_cp_le_set_scan_enable { - uint8_t enable; - uint8_t filter_dup; + uint8_t enable; + uint8_t filter_dup; } __packed; #define BT_HCI_OP_LE_CREATE_CONN BT_OP(BT_OGF_LE, 0x000d) @@ -708,229 +708,229 @@ struct bt_hci_cp_le_set_scan_enable { #define BT_HCI_LE_CREATE_CONN_FP_WHITELIST 0x01 struct bt_hci_cp_le_create_conn { - uint16_t scan_interval; - uint16_t scan_window; - uint8_t filter_policy; - bt_addr_le_t peer_addr; - uint8_t own_addr_type; - uint16_t conn_interval_min; - uint16_t conn_interval_max; - uint16_t conn_latency; - uint16_t supervision_timeout; - uint16_t min_ce_len; - uint16_t max_ce_len; + uint16_t scan_interval; + uint16_t scan_window; + uint8_t filter_policy; + bt_addr_le_t peer_addr; + uint8_t own_addr_type; + uint16_t conn_interval_min; + uint16_t conn_interval_max; + uint16_t conn_latency; + uint16_t supervision_timeout; + uint16_t min_ce_len; + uint16_t max_ce_len; } __packed; #define BT_HCI_OP_LE_CREATE_CONN_CANCEL BT_OP(BT_OGF_LE, 0x000e) #define BT_HCI_OP_LE_READ_WL_SIZE BT_OP(BT_OGF_LE, 0x000f) struct bt_hci_rp_le_read_wl_size { - uint8_t status; - uint8_t wl_size; + uint8_t status; + uint8_t wl_size; } __packed; #define BT_HCI_OP_LE_CLEAR_WL BT_OP(BT_OGF_LE, 0x0010) #define BT_HCI_OP_LE_ADD_DEV_TO_WL BT_OP(BT_OGF_LE, 0x0011) struct bt_hci_cp_le_add_dev_to_wl { - bt_addr_le_t addr; + bt_addr_le_t addr; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_WL BT_OP(BT_OGF_LE, 0x0012) struct bt_hci_cp_le_rem_dev_from_wl { - bt_addr_le_t addr; + bt_addr_le_t addr; } __packed; #define BT_HCI_OP_LE_CONN_UPDATE BT_OP(BT_OGF_LE, 0x0013) struct hci_cp_le_conn_update { - uint16_t handle; - uint16_t conn_interval_min; - uint16_t conn_interval_max; - uint16_t conn_latency; - uint16_t supervision_timeout; - uint16_t min_ce_len; - uint16_t max_ce_len; + uint16_t handle; + uint16_t conn_interval_min; + uint16_t conn_interval_max; + uint16_t conn_latency; + uint16_t supervision_timeout; + uint16_t min_ce_len; + uint16_t max_ce_len; } __packed; #define BT_HCI_OP_LE_SET_HOST_CHAN_CLASSIF BT_OP(BT_OGF_LE, 0x0014) struct bt_hci_cp_le_set_host_chan_classif { - uint8_t ch_map[5]; + uint8_t ch_map[5]; } __packed; #define BT_HCI_OP_LE_READ_CHAN_MAP BT_OP(BT_OGF_LE, 0x0015) struct bt_hci_cp_le_read_chan_map { - uint16_t handle; + uint16_t handle; } __packed; struct bt_hci_rp_le_read_chan_map { - uint8_t status; - uint16_t handle; - uint8_t ch_map[5]; + uint8_t status; + uint16_t handle; + uint8_t ch_map[5]; } __packed; #define BT_HCI_OP_LE_READ_REMOTE_FEATURES BT_OP(BT_OGF_LE, 0x0016) struct bt_hci_cp_le_read_remote_features { - uint16_t handle; + uint16_t handle; } __packed; #define BT_HCI_OP_LE_ENCRYPT BT_OP(BT_OGF_LE, 0x0017) struct bt_hci_cp_le_encrypt { - uint8_t key[16]; - uint8_t plaintext[16]; + uint8_t key[16]; + uint8_t plaintext[16]; } __packed; struct bt_hci_rp_le_encrypt { - uint8_t status; - uint8_t enc_data[16]; + uint8_t status; + uint8_t enc_data[16]; } __packed; #define BT_HCI_OP_LE_RAND BT_OP(BT_OGF_LE, 0x0018) struct bt_hci_rp_le_rand { - uint8_t status; - uint8_t rand[8]; + uint8_t status; + uint8_t rand[8]; } __packed; #define BT_HCI_OP_LE_START_ENCRYPTION BT_OP(BT_OGF_LE, 0x0019) struct bt_hci_cp_le_start_encryption { - uint16_t handle; - uint64_t rand; - uint16_t ediv; - uint8_t ltk[16]; + uint16_t handle; + uint64_t rand; + uint16_t ediv; + uint8_t ltk[16]; } __packed; #define BT_HCI_OP_LE_LTK_REQ_REPLY BT_OP(BT_OGF_LE, 0x001a) struct bt_hci_cp_le_ltk_req_reply { - uint16_t handle; - uint8_t ltk[16]; + uint16_t handle; + uint8_t ltk[16]; } __packed; struct bt_hci_rp_le_ltk_req_reply { - uint8_t status; - uint16_t handle; + uint8_t status; + uint16_t handle; } __packed; #define BT_HCI_OP_LE_LTK_REQ_NEG_REPLY BT_OP(BT_OGF_LE, 0x001b) struct bt_hci_cp_le_ltk_req_neg_reply { - uint16_t handle; + uint16_t handle; } __packed; struct bt_hci_rp_le_ltk_req_neg_reply { - uint8_t status; - uint16_t handle; + uint8_t status; + uint16_t handle; } __packed; #define BT_HCI_OP_LE_READ_SUPP_STATES BT_OP(BT_OGF_LE, 0x001c) struct bt_hci_rp_le_read_supp_states { - uint8_t status; - uint8_t le_states[8]; + uint8_t status; + uint8_t le_states[8]; } __packed; #define BT_HCI_OP_LE_RX_TEST BT_OP(BT_OGF_LE, 0x001d) struct bt_hci_cp_le_rx_test { - uint8_t rx_ch; + uint8_t rx_ch; } __packed; #define BT_HCI_OP_LE_TX_TEST BT_OP(BT_OGF_LE, 0x001e) struct bt_hci_cp_le_tx_test { - uint8_t tx_ch; - uint8_t test_data_len; - uint8_t pkt_payload; + uint8_t tx_ch; + uint8_t test_data_len; + uint8_t pkt_payload; } __packed; #define BT_HCI_OP_LE_TEST_END BT_OP(BT_OGF_LE, 0x001f) struct bt_hci_rp_le_test_end { - uint8_t status; - uint16_t rx_pkt_count; + uint8_t status; + uint16_t rx_pkt_count; } __packed; #define BT_HCI_OP_LE_CONN_PARAM_REQ_REPLY BT_OP(BT_OGF_LE, 0x0020) struct bt_hci_cp_le_conn_param_req_reply { - uint16_t handle; - uint16_t interval_min; - uint16_t interval_max; - uint16_t latency; - uint16_t timeout; - uint16_t min_ce_len; - uint16_t max_ce_len; + uint16_t handle; + uint16_t interval_min; + uint16_t interval_max; + uint16_t latency; + uint16_t timeout; + uint16_t min_ce_len; + uint16_t max_ce_len; } __packed; struct bt_hci_rp_le_conn_param_req_reply { - uint8_t status; - uint16_t handle; + uint8_t status; + uint16_t handle; } __packed; #define BT_HCI_OP_LE_CONN_PARAM_REQ_NEG_REPLY BT_OP(BT_OGF_LE, 0x0021) struct bt_hci_cp_le_conn_param_req_neg_reply { - uint16_t handle; - uint8_t reason; + uint16_t handle; + uint8_t reason; } __packed; struct bt_hci_rp_le_conn_param_req_neg_reply { - uint8_t status; - uint16_t handle; + uint8_t status; + uint16_t handle; } __packed; #define BT_HCI_OP_LE_SET_DATA_LEN BT_OP(BT_OGF_LE, 0x0022) struct bt_hci_cp_le_set_data_len { - uint16_t handle; - uint16_t tx_octets; - uint16_t tx_time; + uint16_t handle; + uint16_t tx_octets; + uint16_t tx_time; } __packed; struct bt_hci_rp_le_set_data_len { - uint8_t status; - uint16_t handle; + uint8_t status; + uint16_t handle; } __packed; #define BT_HCI_OP_LE_READ_DEFAULT_DATA_LEN BT_OP(BT_OGF_LE, 0x0023) struct bt_hci_rp_le_read_default_data_len { - uint8_t status; - uint16_t max_tx_octets; - uint16_t max_tx_time; + uint8_t status; + uint16_t max_tx_octets; + uint16_t max_tx_time; } __packed; #define BT_HCI_OP_LE_WRITE_DEFAULT_DATA_LEN BT_OP(BT_OGF_LE, 0x0024) struct bt_hci_cp_le_write_default_data_len { - uint16_t max_tx_octets; - uint16_t max_tx_time; + uint16_t max_tx_octets; + uint16_t max_tx_time; } __packed; #define BT_HCI_OP_LE_P256_PUBLIC_KEY BT_OP(BT_OGF_LE, 0x0025) #define BT_HCI_OP_LE_GENERATE_DHKEY BT_OP(BT_OGF_LE, 0x0026) struct bt_hci_cp_le_generate_dhkey { - uint8_t key[64]; + uint8_t key[64]; } __packed; #define BT_HCI_OP_LE_ADD_DEV_TO_RL BT_OP(BT_OGF_LE, 0x0027) struct bt_hci_cp_le_add_dev_to_rl { - bt_addr_le_t peer_id_addr; - uint8_t peer_irk[16]; - uint8_t local_irk[16]; + bt_addr_le_t peer_id_addr; + uint8_t peer_irk[16]; + uint8_t local_irk[16]; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_RL BT_OP(BT_OGF_LE, 0x0028) struct bt_hci_cp_le_rem_dev_from_rl { - bt_addr_le_t peer_id_addr; + bt_addr_le_t peer_id_addr; } __packed; #define BT_HCI_OP_LE_CLEAR_RL BT_OP(BT_OGF_LE, 0x0029) #define BT_HCI_OP_LE_READ_RL_SIZE BT_OP(BT_OGF_LE, 0x002a) struct bt_hci_rp_le_read_rl_size { - uint8_t status; - uint8_t rl_size; + uint8_t status; + uint8_t rl_size; } __packed; #define BT_HCI_OP_LE_READ_PEER_RPA BT_OP(BT_OGF_LE, 0x002b) struct bt_hci_cp_le_read_peer_rpa { - bt_addr_le_t peer_id_addr; + bt_addr_le_t peer_id_addr; } __packed; struct bt_hci_rp_le_read_peer_rpa { - uint8_t status; - bt_addr_t peer_rpa; + uint8_t status; + bt_addr_t peer_rpa; } __packed; #define BT_HCI_OP_LE_READ_LOCAL_RPA BT_OP(BT_OGF_LE, 0x002c) struct bt_hci_cp_le_read_local_rpa { - bt_addr_le_t peer_id_addr; + bt_addr_le_t peer_id_addr; } __packed; struct bt_hci_rp_le_read_local_rpa { - uint8_t status; - bt_addr_t local_rpa; + uint8_t status; + bt_addr_t local_rpa; } __packed; #define BT_HCI_ADDR_RES_DISABLE 0x00 @@ -938,21 +938,21 @@ struct bt_hci_rp_le_read_local_rpa { #define BT_HCI_OP_LE_SET_ADDR_RES_ENABLE BT_OP(BT_OGF_LE, 0x002d) struct bt_hci_cp_le_set_addr_res_enable { - uint8_t enable; + uint8_t enable; } __packed; #define BT_HCI_OP_LE_SET_RPA_TIMEOUT BT_OP(BT_OGF_LE, 0x002e) struct bt_hci_cp_le_set_rpa_timeout { - uint16_t rpa_timeout; + uint16_t rpa_timeout; } __packed; #define BT_HCI_OP_LE_READ_MAX_DATA_LEN BT_OP(BT_OGF_LE, 0x002f) struct bt_hci_rp_le_read_max_data_len { - uint8_t status; - uint16_t max_tx_octets; - uint16_t max_tx_time; - uint16_t max_rx_octets; - uint16_t max_rx_time; + uint8_t status; + uint16_t max_tx_octets; + uint16_t max_tx_time; + uint16_t max_rx_octets; + uint16_t max_rx_time; } __packed; #define BT_HCI_LE_PHY_1M 0x01 @@ -961,13 +961,13 @@ struct bt_hci_rp_le_read_max_data_len { #define BT_HCI_OP_LE_READ_PHY BT_OP(BT_OGF_LE, 0x0030) struct bt_hci_cp_le_read_phy { - uint16_t handle; + uint16_t handle; } __packed; struct bt_hci_rp_le_read_phy { - uint8_t status; - uint16_t handle; - uint8_t tx_phy; - uint8_t rx_phy; + uint8_t status; + uint16_t handle; + uint8_t tx_phy; + uint8_t rx_phy; } __packed; #define BT_HCI_LE_PHY_TX_ANY BIT(0) @@ -979,9 +979,9 @@ struct bt_hci_rp_le_read_phy { #define BT_HCI_OP_LE_SET_DEFAULT_PHY BT_OP(BT_OGF_LE, 0x0031) struct bt_hci_cp_le_set_default_phy { - uint8_t all_phys; - uint8_t tx_phys; - uint8_t rx_phys; + uint8_t all_phys; + uint8_t tx_phys; + uint8_t rx_phys; } __packed; #define BT_HCI_LE_PHY_CODED_ANY 0x00 @@ -990,11 +990,11 @@ struct bt_hci_cp_le_set_default_phy { #define BT_HCI_OP_LE_SET_PHY BT_OP(BT_OGF_LE, 0x0032) struct bt_hci_cp_le_set_phy { - uint16_t handle; - uint8_t all_phys; - uint8_t tx_phys; - uint8_t rx_phys; - uint16_t phy_opts; + uint16_t handle; + uint8_t all_phys; + uint8_t tx_phys; + uint8_t rx_phys; + uint16_t phy_opts; } __packed; #define BT_HCI_LE_MOD_INDEX_STANDARD 0x00 @@ -1002,9 +1002,9 @@ struct bt_hci_cp_le_set_phy { #define BT_HCI_OP_LE_ENH_RX_TEST BT_OP(BT_OGF_LE, 0x0033) struct bt_hci_cp_le_enh_rx_test { - uint8_t rx_ch; - uint8_t phy; - uint8_t mod_index; + uint8_t rx_ch; + uint8_t phy; + uint8_t mod_index; } __packed; /* Extends BT_HCI_LE_PHY */ @@ -1013,16 +1013,16 @@ struct bt_hci_cp_le_enh_rx_test { #define BT_HCI_OP_LE_ENH_TX_TEST BT_OP(BT_OGF_LE, 0x0034) struct bt_hci_cp_le_enh_tx_test { - uint8_t tx_ch; - uint8_t test_data_len; - uint8_t pkt_payload; - uint8_t phy; + uint8_t tx_ch; + uint8_t test_data_len; + uint8_t pkt_payload; + uint8_t phy; } __packed; #define BT_HCI_OP_LE_SET_ADV_SET_RANDOM_ADDR BT_OP(BT_OGF_LE, 0x0035) struct bt_hci_cp_le_set_adv_set_random_addr { - uint8_t handle; - bt_addr_t bdaddr; + uint8_t handle; + bt_addr_t bdaddr; } __packed; #define BT_HCI_LE_ADV_PROP_CONN BIT(0) @@ -1040,24 +1040,24 @@ struct bt_hci_cp_le_set_adv_set_random_addr { #define BT_HCI_OP_LE_SET_EXT_ADV_PARAM BT_OP(BT_OGF_LE, 0x0036) struct bt_hci_cp_le_set_ext_adv_param { - uint8_t handle; - uint16_t props; - uint8_t prim_min_interval[3]; - uint8_t prim_max_interval[3]; - uint8_t prim_channel_map; - uint8_t own_addr_type; - bt_addr_le_t peer_addr; - uint8_t filter_policy; - int8_t tx_power; - uint8_t prim_adv_phy; - uint8_t sec_adv_max_skip; - uint8_t sec_adv_phy; - uint8_t sid; - uint8_t scan_req_notify_enable; + uint8_t handle; + uint16_t props; + uint8_t prim_min_interval[3]; + uint8_t prim_max_interval[3]; + uint8_t prim_channel_map; + uint8_t own_addr_type; + bt_addr_le_t peer_addr; + uint8_t filter_policy; + int8_t tx_power; + uint8_t prim_adv_phy; + uint8_t sec_adv_max_skip; + uint8_t sec_adv_phy; + uint8_t sid; + uint8_t scan_req_notify_enable; } __packed; struct bt_hci_rp_le_set_ext_adv_param { - uint8_t status; - int8_t tx_power; + uint8_t status; + int8_t tx_power; } __packed; #define BT_HCI_LE_EXT_ADV_OP_INTERM_FRAG 0x00 @@ -1073,81 +1073,81 @@ struct bt_hci_rp_le_set_ext_adv_param { #define BT_HCI_OP_LE_SET_EXT_ADV_DATA BT_OP(BT_OGF_LE, 0x0037) struct bt_hci_cp_le_set_ext_adv_data { - uint8_t handle; - uint8_t op; - uint8_t frag_pref; - uint8_t len; - uint8_t data[251]; + uint8_t handle; + uint8_t op; + uint8_t frag_pref; + uint8_t len; + uint8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA BT_OP(BT_OGF_LE, 0x0038) struct bt_hci_cp_le_set_ext_scan_rsp_data { - uint8_t handle; - uint8_t op; - uint8_t frag_pref; - uint8_t len; - uint8_t data[251]; + uint8_t handle; + uint8_t op; + uint8_t frag_pref; + uint8_t len; + uint8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_EXT_ADV_ENABLE BT_OP(BT_OGF_LE, 0x0039) struct bt_hci_ext_adv_set { - uint8_t handle; - uint16_t duration; - uint8_t max_ext_adv_evts; + uint8_t handle; + uint16_t duration; + uint8_t max_ext_adv_evts; } __packed; struct bt_hci_cp_le_set_ext_adv_enable { - uint8_t enable; - uint8_t set_num; - struct bt_hci_ext_adv_set s[]; + uint8_t enable; + uint8_t set_num; + struct bt_hci_ext_adv_set s[]; } __packed; #define BT_HCI_OP_LE_READ_MAX_ADV_DATA_LEN BT_OP(BT_OGF_LE, 0x003a) struct bt_hci_rp_le_read_max_adv_data_len { - uint8_t status; - uint16_t max_adv_data_len; + uint8_t status; + uint16_t max_adv_data_len; } __packed; #define BT_HCI_OP_LE_READ_NUM_ADV_SETS BT_OP(BT_OGF_LE, 0x003b) struct bt_hci_rp_le_read_num_adv_sets { - uint8_t status; - uint8_t num_sets; + uint8_t status; + uint8_t num_sets; } __packed; #define BT_HCI_OP_LE_REMOVE_ADV_SET BT_OP(BT_OGF_LE, 0x003c) struct bt_hci_cp_le_remove_adv_set { - uint8_t handle; + uint8_t handle; } __packed; #define BT_HCI_OP_CLEAR_ADV_SETS BT_OP(BT_OGF_LE, 0x003d) #define BT_HCI_OP_LE_SET_PER_ADV_PARAM BT_OP(BT_OGF_LE, 0x003e) struct bt_hci_cp_le_set_per_adv_param { - uint8_t handle; - uint16_t min_interval; - uint16_t max_interval; - uint16_t props; + uint8_t handle; + uint16_t min_interval; + uint16_t max_interval; + uint16_t props; } __packed; #define BT_HCI_OP_LE_SET_PER_ADV_DATA BT_OP(BT_OGF_LE, 0x003f) struct bt_hci_cp_le_set_per_adv_data { - uint8_t handle; - uint8_t op; - uint8_t len; - uint8_t data[251]; + uint8_t handle; + uint8_t op; + uint8_t len; + uint8_t data[251]; } __packed; #define BT_HCI_OP_LE_SET_PER_ADV_ENABLE BT_OP(BT_OGF_LE, 0x0040) struct bt_hci_cp_le_set_per_adv_enable { - uint8_t enable; - uint8_t handle; + uint8_t enable; + uint8_t handle; } __packed; #define BT_HCI_OP_LE_SET_EXT_SCAN_PARAM BT_OP(BT_OGF_LE, 0x0041) struct bt_hci_ext_scan_phy { - uint8_t type; - uint16_t interval; - uint16_t window; + uint8_t type; + uint16_t interval; + uint16_t window; } __packed; #define BT_HCI_LE_EXT_SCAN_PHY_1M BIT(0) @@ -1155,10 +1155,10 @@ struct bt_hci_ext_scan_phy { #define BT_HCI_LE_EXT_SCAN_PHY_CODED BIT(2) struct bt_hci_cp_le_set_ext_scan_param { - uint8_t own_addr_type; - uint8_t filter_policy; - uint8_t phys; - struct bt_hci_ext_scan_phy p[]; + uint8_t own_addr_type; + uint8_t filter_policy; + uint8_t phys; + struct bt_hci_ext_scan_phy p[]; } __packed; /* Extends BT_HCI_LE_SCAN_FILTER_DUP */ @@ -1166,87 +1166,87 @@ struct bt_hci_cp_le_set_ext_scan_param { #define BT_HCI_OP_LE_SET_EXT_SCAN_ENABLE BT_OP(BT_OGF_LE, 0x0042) struct bt_hci_cp_le_set_ext_scan_enable { - uint8_t enable; - uint8_t filter_dup; - uint16_t duration; - uint16_t period; + uint8_t enable; + uint8_t filter_dup; + uint16_t duration; + uint16_t period; } __packed; #define BT_HCI_OP_LE_EXT_CREATE_CONN BT_OP(BT_OGF_LE, 0x0043) struct bt_hci_ext_conn_phy { - uint16_t scan_interval; - uint16_t scan_window; - uint16_t conn_interval_min; - uint16_t conn_interval_max; - uint16_t conn_latency; - uint16_t supervision_timeout; - uint16_t min_ce_len; - uint16_t max_ce_len; + uint16_t scan_interval; + uint16_t scan_window; + uint16_t conn_interval_min; + uint16_t conn_interval_max; + uint16_t conn_latency; + uint16_t supervision_timeout; + uint16_t min_ce_len; + uint16_t max_ce_len; } __packed; struct bt_hci_cp_le_ext_create_conn { - uint8_t filter_policy; - uint8_t own_addr_type; - bt_addr_le_t peer_addr; - uint8_t phys; - struct bt_hci_ext_conn_phy p[]; + uint8_t filter_policy; + uint8_t own_addr_type; + bt_addr_le_t peer_addr; + uint8_t phys; + struct bt_hci_ext_conn_phy p[]; } __packed; #define BT_HCI_OP_LE_PER_ADV_CREATE_SYNC BT_OP(BT_OGF_LE, 0x0044) struct bt_hci_cp_le_per_adv_create_sync { - uint8_t filter_policy; - uint8_t sid; - bt_addr_le_t addr; - uint16_t skip; - uint16_t sync_timeout; - uint8_t unused; + uint8_t filter_policy; + uint8_t sid; + bt_addr_le_t addr; + uint16_t skip; + uint16_t sync_timeout; + uint8_t unused; } __packed; #define BT_HCI_OP_LE_PER_ADV_CREATE_SYNC_CANCEL BT_OP(BT_OGF_LE, 0x0045) #define BT_HCI_OP_LE_PER_ADV_TERMINATE_SYNC BT_OP(BT_OGF_LE, 0x0046) struct bt_hci_cp_le_per_adv_terminate_sync { - uint16_t handle; + uint16_t handle; } __packed; #define BT_HCI_OP_LE_ADD_DEV_TO_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0047) struct bt_hci_cp_le_add_dev_to_per_adv_list { - bt_addr_le_t addr; - uint8_t sid; + bt_addr_le_t addr; + uint8_t sid; } __packed; #define BT_HCI_OP_LE_REM_DEV_FROM_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0048) struct bt_hci_cp_le_rem_dev_from_per_adv_list { - bt_addr_le_t addr; - uint8_t sid; + bt_addr_le_t addr; + uint8_t sid; } __packed; #define BT_HCI_OP_LE_CLEAR_PER_ADV_LIST BT_OP(BT_OGF_LE, 0x0049) #define BT_HCI_OP_LE_READ_PER_ADV_LIST_SIZE BT_OP(BT_OGF_LE, 0x004a) struct bt_hci_rp_le_read_per_adv_list_size { - uint8_t status; - uint8_t list_size; + uint8_t status; + uint8_t list_size; } __packed; #define BT_HCI_OP_LE_READ_TX_POWER BT_OP(BT_OGF_LE, 0x004b) struct bt_hci_rp_le_read_tx_power { - uint8_t status; - int8_t min_tx_power; - int8_t max_tx_power; + uint8_t status; + int8_t min_tx_power; + int8_t max_tx_power; } __packed; #define BT_HCI_OP_LE_READ_RF_PATH_COMP BT_OP(BT_OGF_LE, 0x004c) struct bt_hci_rp_le_read_rf_path_comp { - uint8_t status; - int16_t tx_path_comp; - int16_t rx_path_comp; + uint8_t status; + int16_t tx_path_comp; + int16_t rx_path_comp; } __packed; #define BT_HCI_OP_LE_WRITE_RF_PATH_COMP BT_OP(BT_OGF_LE, 0x004d) struct bt_hci_cp_le_write_rf_path_comp { - int16_t tx_path_comp; - int16_t rx_path_comp; + int16_t tx_path_comp; + int16_t rx_path_comp; } __packed; #define BT_HCI_LE_PRIVACY_MODE_NETWORK 0x00 @@ -1254,8 +1254,8 @@ struct bt_hci_cp_le_write_rf_path_comp { #define BT_HCI_OP_LE_SET_PRIVACY_MODE BT_OP(BT_OGF_LE, 0x004e) struct bt_hci_cp_le_set_privacy_mode { - bt_addr_le_t id_addr; - uint8_t mode; + bt_addr_le_t id_addr; + uint8_t mode; } __packed; /* Event definitions */ @@ -1265,106 +1265,106 @@ struct bt_hci_cp_le_set_privacy_mode { #define BT_HCI_EVT_INQUIRY_COMPLETE 0x01 struct bt_hci_evt_inquiry_complete { - uint8_t status; + uint8_t status; } __packed; #define BT_HCI_EVT_CONN_COMPLETE 0x03 struct bt_hci_evt_conn_complete { - uint8_t status; - uint16_t handle; - bt_addr_t bdaddr; - uint8_t link_type; - uint8_t encr_enabled; + uint8_t status; + uint16_t handle; + bt_addr_t bdaddr; + uint8_t link_type; + uint8_t encr_enabled; } __packed; #define BT_HCI_EVT_CONN_REQUEST 0x04 struct bt_hci_evt_conn_request { - bt_addr_t bdaddr; - uint8_t dev_class[3]; - uint8_t link_type; + bt_addr_t bdaddr; + uint8_t dev_class[3]; + uint8_t link_type; } __packed; #define BT_HCI_EVT_DISCONN_COMPLETE 0x05 struct bt_hci_evt_disconn_complete { - uint8_t status; - uint16_t handle; - uint8_t reason; + uint8_t status; + uint16_t handle; + uint8_t reason; } __packed; #define BT_HCI_EVT_AUTH_COMPLETE 0x06 struct bt_hci_evt_auth_complete { - uint8_t status; - uint16_t handle; + uint8_t status; + uint16_t handle; } __packed; #define BT_HCI_EVT_REMOTE_NAME_REQ_COMPLETE 0x07 struct bt_hci_evt_remote_name_req_complete { - uint8_t status; - bt_addr_t bdaddr; - uint8_t name[248]; + uint8_t status; + bt_addr_t bdaddr; + uint8_t name[248]; } __packed; #define BT_HCI_EVT_ENCRYPT_CHANGE 0x08 struct bt_hci_evt_encrypt_change { - uint8_t status; - uint16_t handle; - uint8_t encrypt; + uint8_t status; + uint16_t handle; + uint8_t encrypt; } __packed; #define BT_HCI_EVT_REMOTE_FEATURES 0x0b struct bt_hci_evt_remote_features { - uint8_t status; - uint16_t handle; - uint8_t features[8]; + uint8_t status; + uint16_t handle; + uint8_t features[8]; } __packed; #define BT_HCI_EVT_REMOTE_VERSION_INFO 0x0c struct bt_hci_evt_remote_version_info { - uint8_t status; - uint16_t handle; - uint8_t version; - uint16_t manufacturer; - uint16_t subversion; + uint8_t status; + uint16_t handle; + uint8_t version; + uint16_t manufacturer; + uint16_t subversion; } __packed; #define BT_HCI_EVT_CMD_COMPLETE 0x0e struct bt_hci_evt_cmd_complete { - uint8_t ncmd; - uint16_t opcode; + uint8_t ncmd; + uint16_t opcode; } __packed; struct bt_hci_evt_cc_status { - uint8_t status; + uint8_t status; } __packed; #define BT_HCI_EVT_CMD_STATUS 0x0f struct bt_hci_evt_cmd_status { - uint8_t status; - uint8_t ncmd; - uint16_t opcode; + uint8_t status; + uint8_t ncmd; + uint16_t opcode; } __packed; #define BT_HCI_EVT_ROLE_CHANGE 0x12 struct bt_hci_evt_role_change { - uint8_t status; - bt_addr_t bdaddr; - uint8_t role; + uint8_t status; + bt_addr_t bdaddr; + uint8_t role; } __packed; #define BT_HCI_EVT_NUM_COMPLETED_PACKETS 0x13 struct bt_hci_evt_num_completed_packets { - uint8_t num_handles; - struct bt_hci_handle_count h[]; + uint8_t num_handles; + struct bt_hci_handle_count h[]; } __packed; #define BT_HCI_EVT_PIN_CODE_REQ 0x16 struct bt_hci_evt_pin_code_req { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_LINK_KEY_REQ 0x17 struct bt_hci_evt_link_key_req { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; /* Link Key types */ @@ -1380,9 +1380,9 @@ struct bt_hci_evt_link_key_req { #define BT_HCI_EVT_LINK_KEY_NOTIFY 0x18 struct bt_hci_evt_link_key_notify { - bt_addr_t bdaddr; - uint8_t link_key[16]; - uint8_t key_type; + bt_addr_t bdaddr; + uint8_t link_key[16]; + uint8_t key_type; } __packed; /* Overflow link types */ @@ -1391,103 +1391,103 @@ struct bt_hci_evt_link_key_notify { #define BT_HCI_EVT_DATA_BUF_OVERFLOW 0x1a struct bt_hci_evt_data_buf_overflow { - uint8_t link_type; + uint8_t link_type; } __packed; #define BT_HCI_EVT_INQUIRY_RESULT_WITH_RSSI 0x22 struct bt_hci_evt_inquiry_result_with_rssi { - bt_addr_t addr; - uint8_t pscan_rep_mode; - uint8_t reserved; - uint8_t cod[3]; - uint16_t clock_offset; - int8_t rssi; + bt_addr_t addr; + uint8_t pscan_rep_mode; + uint8_t reserved; + uint8_t cod[3]; + uint16_t clock_offset; + int8_t rssi; } __packed; #define BT_HCI_EVT_REMOTE_EXT_FEATURES 0x23 struct bt_hci_evt_remote_ext_features { - uint8_t status; - uint16_t handle; - uint8_t page; - uint8_t max_page; - uint8_t features[8]; + uint8_t status; + uint16_t handle; + uint8_t page; + uint8_t max_page; + uint8_t features[8]; } __packed; #define BT_HCI_EVT_SYNC_CONN_COMPLETE 0x2c struct bt_hci_evt_sync_conn_complete { - uint8_t status; - uint16_t handle; - bt_addr_t bdaddr; - uint8_t link_type; - uint8_t tx_interval; - uint8_t retansmission_window; - uint16_t rx_pkt_length; - uint16_t tx_pkt_length; - uint8_t air_mode; + uint8_t status; + uint16_t handle; + bt_addr_t bdaddr; + uint8_t link_type; + uint8_t tx_interval; + uint8_t retansmission_window; + uint16_t rx_pkt_length; + uint16_t tx_pkt_length; + uint8_t air_mode; } __packed; #define BT_HCI_EVT_EXTENDED_INQUIRY_RESULT 0x2f struct bt_hci_evt_extended_inquiry_result { - uint8_t num_reports; - bt_addr_t addr; - uint8_t pscan_rep_mode; - uint8_t reserved; - uint8_t cod[3]; - uint16_t clock_offset; - int8_t rssi; - uint8_t eir[240]; + uint8_t num_reports; + bt_addr_t addr; + uint8_t pscan_rep_mode; + uint8_t reserved; + uint8_t cod[3]; + uint16_t clock_offset; + int8_t rssi; + uint8_t eir[240]; } __packed; #define BT_HCI_EVT_ENCRYPT_KEY_REFRESH_COMPLETE 0x30 struct bt_hci_evt_encrypt_key_refresh_complete { - uint8_t status; - uint16_t handle; + uint8_t status; + uint16_t handle; } __packed; #define BT_HCI_EVT_IO_CAPA_REQ 0x31 struct bt_hci_evt_io_capa_req { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_IO_CAPA_RESP 0x32 struct bt_hci_evt_io_capa_resp { - bt_addr_t bdaddr; - uint8_t capability; - uint8_t oob_data; - uint8_t authentication; + bt_addr_t bdaddr; + uint8_t capability; + uint8_t oob_data; + uint8_t authentication; } __packed; #define BT_HCI_EVT_USER_CONFIRM_REQ 0x33 struct bt_hci_evt_user_confirm_req { - bt_addr_t bdaddr; - uint32_t passkey; + bt_addr_t bdaddr; + uint32_t passkey; } __packed; #define BT_HCI_EVT_USER_PASSKEY_REQ 0x34 struct bt_hci_evt_user_passkey_req { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_SSP_COMPLETE 0x36 struct bt_hci_evt_ssp_complete { - uint8_t status; - bt_addr_t bdaddr; + uint8_t status; + bt_addr_t bdaddr; } __packed; #define BT_HCI_EVT_USER_PASSKEY_NOTIFY 0x3b struct bt_hci_evt_user_passkey_notify { - bt_addr_t bdaddr; - uint32_t passkey; + bt_addr_t bdaddr; + uint32_t passkey; } __packed; #define BT_HCI_EVT_LE_META_EVENT 0x3e struct bt_hci_evt_le_meta_event { - uint8_t subevent; + uint8_t subevent; } __packed; #define BT_HCI_EVT_AUTH_PAYLOAD_TIMEOUT_EXP 0x57 struct bt_hci_evt_auth_payload_timeout_exp { - uint16_t handle; + uint16_t handle; } __packed; #define BT_HCI_ROLE_MASTER 0x00 @@ -1495,113 +1495,113 @@ struct bt_hci_evt_auth_payload_timeout_exp { #define BT_HCI_EVT_LE_CONN_COMPLETE 0x01 struct bt_hci_evt_le_conn_complete { - uint8_t status; - uint16_t handle; - uint8_t role; - bt_addr_le_t peer_addr; - uint16_t interval; - uint16_t latency; - uint16_t supv_timeout; - uint8_t clock_accuracy; + uint8_t status; + uint16_t handle; + uint8_t role; + bt_addr_le_t peer_addr; + uint16_t interval; + uint16_t latency; + uint16_t supv_timeout; + uint8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_ADVERTISING_REPORT 0x02 struct bt_hci_evt_le_advertising_info { - uint8_t evt_type; - bt_addr_le_t addr; - uint8_t length; - uint8_t data[]; + uint8_t evt_type; + bt_addr_le_t addr; + uint8_t length; + uint8_t data[]; } __packed; struct bt_hci_evt_le_advertising_report { - uint8_t num_reports; - struct bt_hci_evt_le_advertising_info adv_info[]; + uint8_t num_reports; + struct bt_hci_evt_le_advertising_info adv_info[]; } __packed; #define BT_HCI_EVT_LE_CONN_UPDATE_COMPLETE 0x03 struct bt_hci_evt_le_conn_update_complete { - uint8_t status; - uint16_t handle; - uint16_t interval; - uint16_t latency; - uint16_t supv_timeout; + uint8_t status; + uint16_t handle; + uint16_t interval; + uint16_t latency; + uint16_t supv_timeout; } __packed; #define BT_HCI_EV_LE_REMOTE_FEAT_COMPLETE 0x04 struct bt_hci_evt_le_remote_feat_complete { - uint8_t status; - uint16_t handle; - uint8_t features[8]; + uint8_t status; + uint16_t handle; + uint8_t features[8]; } __packed; #define BT_HCI_EVT_LE_LTK_REQUEST 0x05 struct bt_hci_evt_le_ltk_request { - uint16_t handle; - uint64_t rand; - uint16_t ediv; + uint16_t handle; + uint64_t rand; + uint16_t ediv; } __packed; #define BT_HCI_EVT_LE_CONN_PARAM_REQ 0x06 struct bt_hci_evt_le_conn_param_req { - uint16_t handle; - uint16_t interval_min; - uint16_t interval_max; - uint16_t latency; - uint16_t timeout; + uint16_t handle; + uint16_t interval_min; + uint16_t interval_max; + uint16_t latency; + uint16_t timeout; } __packed; #define BT_HCI_EVT_LE_DATA_LEN_CHANGE 0x07 struct bt_hci_evt_le_data_len_change { - uint16_t handle; - uint16_t max_tx_octets; - uint16_t max_tx_time; - uint16_t max_rx_octets; - uint16_t max_rx_time; + uint16_t handle; + uint16_t max_tx_octets; + uint16_t max_tx_time; + uint16_t max_rx_octets; + uint16_t max_rx_time; } __packed; #define BT_HCI_EVT_LE_P256_PUBLIC_KEY_COMPLETE 0x08 struct bt_hci_evt_le_p256_public_key_complete { - uint8_t status; - uint8_t key[64]; + uint8_t status; + uint8_t key[64]; } __packed; #define BT_HCI_EVT_LE_GENERATE_DHKEY_COMPLETE 0x09 struct bt_hci_evt_le_generate_dhkey_complete { - uint8_t status; - uint8_t dhkey[32]; + uint8_t status; + uint8_t dhkey[32]; } __packed; #define BT_HCI_EVT_LE_ENH_CONN_COMPLETE 0x0a struct bt_hci_evt_le_enh_conn_complete { - uint8_t status; - uint16_t handle; - uint8_t role; - bt_addr_le_t peer_addr; - bt_addr_t local_rpa; - bt_addr_t peer_rpa; - uint16_t interval; - uint16_t latency; - uint16_t supv_timeout; - uint8_t clock_accuracy; + uint8_t status; + uint16_t handle; + uint8_t role; + bt_addr_le_t peer_addr; + bt_addr_t local_rpa; + bt_addr_t peer_rpa; + uint16_t interval; + uint16_t latency; + uint16_t supv_timeout; + uint8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_DIRECT_ADV_REPORT 0x0b struct bt_hci_evt_le_direct_adv_info { - uint8_t evt_type; - bt_addr_le_t addr; - bt_addr_le_t dir_addr; - int8_t rssi; + uint8_t evt_type; + bt_addr_le_t addr; + bt_addr_le_t dir_addr; + int8_t rssi; } __packed; struct bt_hci_evt_le_direct_adv_report { - uint8_t num_reports; - struct bt_hci_evt_le_direct_adv_info direct_adv_info[]; + uint8_t num_reports; + struct bt_hci_evt_le_direct_adv_info direct_adv_info[]; } __packed; #define BT_HCI_EVT_LE_PHY_UPDATE_COMPLETE 0x0c struct bt_hci_evt_le_phy_update_complete { - uint8_t status; - uint16_t handle; - uint8_t tx_phy; - uint8_t rx_phy; + uint8_t status; + uint16_t handle; + uint8_t tx_phy; + uint8_t rx_phy; } __packed; #define BT_HCI_EVT_LE_EXT_ADVERTISING_REPORT 0x0d @@ -1618,64 +1618,64 @@ struct bt_hci_evt_le_phy_update_complete { #define BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS_INCOMPLETE 2 struct bt_hci_evt_le_ext_advertising_info { - uint16_t evt_type; - bt_addr_le_t addr; - uint8_t prim_phy; - uint8_t sec_phy; - uint8_t sid; - int8_t tx_power; - int8_t rssi; - uint16_t interval; - bt_addr_le_t direct_addr; - uint8_t length; - uint8_t data[]; + uint16_t evt_type; + bt_addr_le_t addr; + uint8_t prim_phy; + uint8_t sec_phy; + uint8_t sid; + int8_t tx_power; + int8_t rssi; + uint16_t interval; + bt_addr_le_t direct_addr; + uint8_t length; + uint8_t data[]; } __packed; struct bt_hci_evt_le_ext_advertising_report { - uint8_t num_reports; - struct bt_hci_evt_le_ext_advertising_info adv_info[]; + uint8_t num_reports; + struct bt_hci_evt_le_ext_advertising_info adv_info[]; } __packed; #define BT_HCI_EVT_LE_PER_ADV_SYNC_ESTABLISHED 0x0e struct bt_hci_evt_le_per_adv_sync_established { - uint8_t status; - uint16_t handle; - uint8_t sid; - bt_addr_le_t adv_addr; - uint8_t phy; - uint16_t interval; - uint8_t clock_accuracy; + uint8_t status; + uint16_t handle; + uint8_t sid; + bt_addr_le_t adv_addr; + uint8_t phy; + uint16_t interval; + uint8_t clock_accuracy; } __packed; #define BT_HCI_EVT_LE_PER_ADVERTISING_REPORT 0x0f struct bt_hci_evt_le_per_advertising_report { - uint16_t handle; - int8_t tx_power; - int8_t rssi; - uint8_t unused; - uint8_t data_status; - uint8_t length; - uint8_t data[]; + uint16_t handle; + int8_t tx_power; + int8_t rssi; + uint8_t unused; + uint8_t data_status; + uint8_t length; + uint8_t data[]; } __packed; #define BT_HCI_EVT_LE_PER_ADV_SYNC_LOST 0x10 struct bt_hci_evt_le_per_adv_sync_lost { - uint16_t handle; + uint16_t handle; } __packed; #define BT_HCI_EVT_LE_SCAN_TIMEOUT 0x11 #define BT_HCI_EVT_LE_ADV_SET_TERMINATED 0x12 struct bt_hci_evt_le_adv_set_terminated { - uint8_t status; - uint8_t adv_handle; - uint16_t conn_handle; - uint8_t num_completed_ext_adv_evts; + uint8_t status; + uint8_t adv_handle; + uint16_t conn_handle; + uint8_t num_completed_ext_adv_evts; } __packed; #define BT_HCI_EVT_LE_SCAN_REQ_RECEIVED 0x13 struct bt_hci_evt_le_scan_req_received { - uint8_t handle; - bt_addr_le_t addr; + uint8_t handle; + bt_addr_le_t addr; } __packed; #define BT_HCI_LE_CHAN_SEL_ALGO_1 0x00 @@ -1683,8 +1683,8 @@ struct bt_hci_evt_le_scan_req_received { #define BT_HCI_EVT_LE_CHAN_SEL_ALGO 0x14 struct bt_hci_evt_le_chan_sel_algo { - uint16_t handle; - uint8_t chan_sel_algo; + uint16_t handle; + uint8_t chan_sel_algo; } __packed; /* Event mask bits */ diff --git a/devices/ble_hci/common-hal/_bleio/hci_include/hci_raw.h b/devices/ble_hci/common-hal/_bleio/hci_include/hci_raw.h index 030fb0ca3c..8fb5564eb1 100644 --- a/devices/ble_hci/common-hal/_bleio/hci_include/hci_raw.h +++ b/devices/ble_hci/common-hal/_bleio/hci_include/hci_raw.h @@ -50,20 +50,20 @@ extern "C" { int bt_send(struct net_buf *buf); enum { - /** Passthrough mode - * - * While in this mode the buffers are passed as is between the stack - * and the driver. - */ - BT_HCI_RAW_MODE_PASSTHROUGH = 0x00, + /** Passthrough mode + * + * While in this mode the buffers are passed as is between the stack + * and the driver. + */ + BT_HCI_RAW_MODE_PASSTHROUGH = 0x00, - /** H:4 mode - * - * While in this mode H:4 headers will added into the buffers - * according to the buffer type when coming from the stack and will be - * removed and used to set the buffer type. - */ - BT_HCI_RAW_MODE_H4 = 0x01, + /** H:4 mode + * + * While in this mode H:4 headers will added into the buffers + * according to the buffer type when coming from the stack and will be + * removed and used to set the buffer type. + */ + BT_HCI_RAW_MODE_H4 = 0x01, }; /** @brief Set Bluetooth RAW channel mode @@ -93,31 +93,31 @@ uint8_t bt_hci_raw_get_mode(void); * @param _func Handler function to be called. */ #define BT_HCI_RAW_CMD_EXT(_op, _min_len, _func) \ - { \ - .op = _op, \ - .min_len = _min_len, \ - .func = _func, \ - } + { \ + .op = _op, \ + .min_len = _min_len, \ + .func = _func, \ + } struct bt_hci_raw_cmd_ext { - /** Opcode of the command */ - uint16_t op; + /** Opcode of the command */ + uint16_t op; - /** Minimal length of the command */ - size_t min_len; + /** Minimal length of the command */ + size_t min_len; - /** Handler function. - * - * Handler function to be called when a command is intercepted. - * - * @param buf Buffer containing the command. - * - * @return HCI Status code or BT_HCI_ERR_EXT_HANDLED if command has - * been handled already and a response has been sent as oppose to - * BT_HCI_ERR_SUCCESS which just indicates that the command can be - * sent to the controller to be processed. - */ - uint8_t (*func)(struct net_buf *buf); + /** Handler function. + * + * Handler function to be called when a command is intercepted. + * + * @param buf Buffer containing the command. + * + * @return HCI Status code or BT_HCI_ERR_EXT_HANDLED if command has + * been handled already and a response has been sent as oppose to + * BT_HCI_ERR_SUCCESS which just indicates that the command can be + * sent to the controller to be processed. + */ + uint8_t (*func)(struct net_buf *buf); }; /** @brief Register Bluetooth RAW command extension table diff --git a/devices/ble_hci/common-hal/_bleio/hci_include/hci_vs.h b/devices/ble_hci/common-hal/_bleio/hci_include/hci_vs.h index 660691398e..02452a7886 100644 --- a/devices/ble_hci/common-hal/_bleio/hci_include/hci_vs.h +++ b/devices/ble_hci/common-hal/_bleio/hci_include/hci_vs.h @@ -32,11 +32,11 @@ extern "C" { #define BT_VS_CMD_BIT_READ_TX_POWER 14 #define BT_VS_CMD_SUP_FEAT(cmd) BT_LE_FEAT_TEST(cmd, \ - BT_VS_CMD_BIT_SUP_FEAT) + BT_VS_CMD_BIT_SUP_FEAT) #define BT_VS_CMD_READ_STATIC_ADDRS(cmd) BT_LE_FEAT_TEST(cmd, \ - BT_VS_CMD_BIT_READ_STATIC_ADDRS) + BT_VS_CMD_BIT_READ_STATIC_ADDRS) #define BT_VS_CMD_READ_KEY_ROOTS(cmd) BT_LE_FEAT_TEST(cmd, \ - BT_VS_CMD_BIT_READ_KEY_ROOTS) + BT_VS_CMD_BIT_READ_KEY_ROOTS) #define BT_HCI_VS_HW_PLAT_INTEL 0x0001 #define BT_HCI_VS_HW_PLAT_NORDIC 0x0002 @@ -50,44 +50,44 @@ extern "C" { #define BT_HCI_VS_FW_VAR_VS_CTLR 0x0002 #define BT_HCI_VS_FW_VAR_FW_LOADER 0x0003 #define BT_HCI_VS_FW_VAR_RESCUE_IMG 0x0004 -#define BT_HCI_OP_VS_READ_VERSION_INFO BT_OP(BT_OGF_VS, 0x0001) +#define BT_HCI_OP_VS_READ_VERSION_INFO BT_OP(BT_OGF_VS, 0x0001) struct bt_hci_rp_vs_read_version_info { - uint8_t status; - uint16_t hw_platform; - uint16_t hw_variant; - uint8_t fw_variant; - uint8_t fw_version; - uint16_t fw_revision; - uint32_t fw_build; + uint8_t status; + uint16_t hw_platform; + uint16_t hw_variant; + uint8_t fw_variant; + uint8_t fw_version; + uint16_t fw_revision; + uint32_t fw_build; } __packed; -#define BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS BT_OP(BT_OGF_VS, 0x0002) +#define BT_HCI_OP_VS_READ_SUPPORTED_COMMANDS BT_OP(BT_OGF_VS, 0x0002) struct bt_hci_rp_vs_read_supported_commands { - uint8_t status; - uint8_t commands[64]; + uint8_t status; + uint8_t commands[64]; } __packed; -#define BT_HCI_OP_VS_READ_SUPPORTED_FEATURES BT_OP(BT_OGF_VS, 0x0003) +#define BT_HCI_OP_VS_READ_SUPPORTED_FEATURES BT_OP(BT_OGF_VS, 0x0003) struct bt_hci_rp_vs_read_supported_features { - uint8_t status; - uint8_t features[8]; + uint8_t status; + uint8_t features[8]; } __packed; #define BT_HCI_OP_VS_SET_EVENT_MASK BT_OP(BT_OGF_VS, 0x0004) struct bt_hci_cp_vs_set_event_mask { - uint8_t event_mask[8]; + uint8_t event_mask[8]; } __packed; #define BT_HCI_VS_RESET_SOFT 0x00 #define BT_HCI_VS_RESET_HARD 0x01 #define BT_HCI_OP_VS_RESET BT_OP(BT_OGF_VS, 0x0005) struct bt_hci_cp_vs_reset { - uint8_t type; + uint8_t type; } __packed; #define BT_HCI_OP_VS_WRITE_BD_ADDR BT_OP(BT_OGF_VS, 0x0006) struct bt_hci_cp_vs_write_bd_addr { - bt_addr_t bdaddr; + bt_addr_t bdaddr; } __packed; #define BT_HCI_VS_TRACE_DISABLED 0x00 @@ -97,60 +97,60 @@ struct bt_hci_cp_vs_write_bd_addr { #define BT_HCI_VS_TRACE_VDC 0x01 #define BT_HCI_OP_VS_SET_TRACE_ENABLE BT_OP(BT_OGF_VS, 0x0007) struct bt_hci_cp_vs_set_trace_enable { - uint8_t enable; - uint8_t type; + uint8_t enable; + uint8_t type; } __packed; #define BT_HCI_OP_VS_READ_BUILD_INFO BT_OP(BT_OGF_VS, 0x0008) struct bt_hci_rp_vs_read_build_info { - uint8_t status; - uint8_t info[]; + uint8_t status; + uint8_t info[]; } __packed; struct bt_hci_vs_static_addr { - bt_addr_t bdaddr; - uint8_t ir[16]; + bt_addr_t bdaddr; + uint8_t ir[16]; } __packed; #define BT_HCI_OP_VS_READ_STATIC_ADDRS BT_OP(BT_OGF_VS, 0x0009) struct bt_hci_rp_vs_read_static_addrs { - uint8_t status; - uint8_t num_addrs; - struct bt_hci_vs_static_addr a[]; + uint8_t status; + uint8_t num_addrs; + struct bt_hci_vs_static_addr a[]; } __packed; #define BT_HCI_OP_VS_READ_KEY_HIERARCHY_ROOTS BT_OP(BT_OGF_VS, 0x000a) struct bt_hci_rp_vs_read_key_hierarchy_roots { - uint8_t status; - uint8_t ir[16]; - uint8_t er[16]; + uint8_t status; + uint8_t ir[16]; + uint8_t er[16]; } __packed; #define BT_HCI_OP_VS_READ_CHIP_TEMP BT_OP(BT_OGF_VS, 0x000b) struct bt_hci_rp_vs_read_chip_temp { - uint8_t status; - int8_t temps; + uint8_t status; + int8_t temps; } __packed; struct bt_hci_vs_cmd { - uint16_t vendor_id; - uint16_t opcode_base; + uint16_t vendor_id; + uint16_t opcode_base; } __packed; #define BT_HCI_VS_VID_ANDROID 0x0001 #define BT_HCI_VS_VID_MICROSOFT 0x0002 #define BT_HCI_OP_VS_READ_HOST_STACK_CMDS BT_OP(BT_OGF_VS, 0x000c) struct bt_hci_rp_vs_read_host_stack_cmds { - uint8_t status; - uint8_t num_cmds; - struct bt_hci_vs_cmd c[]; + uint8_t status; + uint8_t num_cmds; + struct bt_hci_vs_cmd c[]; } __packed; #define BT_HCI_VS_SCAN_REQ_REPORTS_DISABLED 0x00 #define BT_HCI_VS_SCAN_REQ_REPORTS_ENABLED 0x01 #define BT_HCI_OP_VS_SET_SCAN_REQ_REPORTS BT_OP(BT_OGF_VS, 0x000d) struct bt_hci_cp_vs_set_scan_req_reports { - uint8_t enable; + uint8_t enable; } __packed; #define BT_HCI_VS_LL_HANDLE_TYPE_ADV 0x00 @@ -159,37 +159,37 @@ struct bt_hci_cp_vs_set_scan_req_reports { #define BT_HCI_VS_LL_TX_POWER_LEVEL_NO_PREF 0x7F #define BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL BT_OP(BT_OGF_VS, 0x000e) struct bt_hci_cp_vs_write_tx_power_level { - uint8_t handle_type; - uint16_t handle; - int8_t tx_power_level; + uint8_t handle_type; + uint16_t handle; + int8_t tx_power_level; } __packed; struct bt_hci_rp_vs_write_tx_power_level { - uint8_t status; - uint8_t handle_type; - uint16_t handle; - int8_t selected_tx_power; + uint8_t status; + uint8_t handle_type; + uint16_t handle; + int8_t selected_tx_power; } __packed; #define BT_HCI_OP_VS_READ_TX_POWER_LEVEL BT_OP(BT_OGF_VS, 0x000f) struct bt_hci_cp_vs_read_tx_power_level { - uint8_t handle_type; - uint16_t handle; + uint8_t handle_type; + uint16_t handle; } __packed; struct bt_hci_rp_vs_read_tx_power_level { - uint8_t status; - uint8_t handle_type; - uint16_t handle; - int8_t tx_power_level; + uint8_t status; + uint8_t handle_type; + uint16_t handle; + int8_t tx_power_level; } __packed; #define BT_HCI_OP_VS_READ_USB_TRANSPORT_MODE BT_OP(BT_OGF_VS, 0x0010) struct bt_hci_rp_vs_read_usb_transport_mode { - uint8_t status; - uint8_t num_supported_modes; - uint8_t supported_mode[]; + uint8_t status; + uint8_t num_supported_modes; + uint8_t supported_mode[]; } __packed; #define BT_HCI_VS_USB_H2_MODE 0x00 @@ -198,19 +198,19 @@ struct bt_hci_rp_vs_read_usb_transport_mode { #define BT_HCI_OP_VS_SET_USB_TRANSPORT_MODE BT_OP(BT_OGF_VS, 0x0011) struct bt_hci_cp_vs_set_usb_transport_mode { - uint8_t mode; + uint8_t mode; } __packed; /* Events */ struct bt_hci_evt_vs { - uint8_t subevent; + uint8_t subevent; } __packed; #define BT_HCI_EVT_VS_FATAL_ERROR 0x02 struct bt_hci_evt_vs_fatal_error { - uint64_t pc; - uint8_t err_info[]; + uint64_t pc; + uint8_t err_info[]; } __packed; #define BT_HCI_VS_TRACE_LMP_TX 0x01 @@ -220,14 +220,14 @@ struct bt_hci_evt_vs_fatal_error { #define BT_HCI_VS_TRACE_LE_CONN_IND 0x05 #define BT_HCI_EVT_VS_TRACE_INFO 0x03 struct bt_hci_evt_vs_trace_info { - uint8_t type; - uint8_t data[]; + uint8_t type; + uint8_t data[]; } __packed; #define BT_HCI_EVT_VS_SCAN_REQ_RX 0x04 struct bt_hci_evt_vs_scan_req_rx { - bt_addr_le_t addr; - int8_t rssi; + bt_addr_le_t addr; + int8_t rssi; } __packed; /* Event mask bits */ @@ -243,133 +243,133 @@ struct bt_hci_evt_vs_scan_req_rx { #define BT_HCI_MESH_EVT_PREFIX 0xF0 struct bt_hci_cp_mesh { - uint8_t opcode; + uint8_t opcode; } __packed; #define BT_HCI_OC_MESH_GET_OPTS 0x00 struct bt_hci_rp_mesh_get_opts { - uint8_t status; - uint8_t opcode; - uint8_t revision; - uint8_t ch_map; - int8_t min_tx_power; - int8_t max_tx_power; - uint8_t max_scan_filter; - uint8_t max_filter_pattern; - uint8_t max_adv_slot; - uint8_t max_tx_window; - uint8_t evt_prefix_len; - uint8_t evt_prefix; + uint8_t status; + uint8_t opcode; + uint8_t revision; + uint8_t ch_map; + int8_t min_tx_power; + int8_t max_tx_power; + uint8_t max_scan_filter; + uint8_t max_filter_pattern; + uint8_t max_adv_slot; + uint8_t max_tx_window; + uint8_t evt_prefix_len; + uint8_t evt_prefix; } __packed; #define BT_HCI_MESH_PATTERN_LEN_MAX 0x0f #define BT_HCI_OC_MESH_SET_SCAN_FILTER 0x01 struct bt_hci_mesh_pattern { - uint8_t pattern_len; - uint8_t pattern[]; + uint8_t pattern_len; + uint8_t pattern[]; } __packed; struct bt_hci_cp_mesh_set_scan_filter { - uint8_t scan_filter; - uint8_t filter_dup; - uint8_t num_patterns; - struct bt_hci_mesh_pattern patterns[]; + uint8_t scan_filter; + uint8_t filter_dup; + uint8_t num_patterns; + struct bt_hci_mesh_pattern patterns[]; } __packed; struct bt_hci_rp_mesh_set_scan_filter { - uint8_t status; - uint8_t opcode; - uint8_t scan_filter; + uint8_t status; + uint8_t opcode; + uint8_t scan_filter; } __packed; #define BT_HCI_OC_MESH_ADVERTISE 0x02 struct bt_hci_cp_mesh_advertise { - uint8_t adv_slot; - uint8_t own_addr_type; - bt_addr_t random_addr; - uint8_t ch_map; - int8_t tx_power; - uint8_t min_tx_delay; - uint8_t max_tx_delay; - uint8_t retx_count; - uint8_t retx_interval; - uint8_t scan_delay; - uint16_t scan_duration; - uint8_t scan_filter; - uint8_t data_len; - uint8_t data[31]; + uint8_t adv_slot; + uint8_t own_addr_type; + bt_addr_t random_addr; + uint8_t ch_map; + int8_t tx_power; + uint8_t min_tx_delay; + uint8_t max_tx_delay; + uint8_t retx_count; + uint8_t retx_interval; + uint8_t scan_delay; + uint16_t scan_duration; + uint8_t scan_filter; + uint8_t data_len; + uint8_t data[31]; } __packed; struct bt_hci_rp_mesh_advertise { - uint8_t status; - uint8_t opcode; - uint8_t adv_slot; + uint8_t status; + uint8_t opcode; + uint8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_ADVERTISE_TIMED 0x03 struct bt_hci_cp_mesh_advertise_timed { - uint8_t adv_slot; - uint8_t own_addr_type; - bt_addr_t random_addr; - uint8_t ch_map; - int8_t tx_power; - uint8_t retx_count; - uint8_t retx_interval; - uint32_t instant; - uint16_t tx_delay; - uint16_t tx_window; - uint8_t data_len; - uint8_t data[31]; + uint8_t adv_slot; + uint8_t own_addr_type; + bt_addr_t random_addr; + uint8_t ch_map; + int8_t tx_power; + uint8_t retx_count; + uint8_t retx_interval; + uint32_t instant; + uint16_t tx_delay; + uint16_t tx_window; + uint8_t data_len; + uint8_t data[31]; } __packed; struct bt_hci_rp_mesh_advertise_timed { - uint8_t status; - uint8_t opcode; - uint8_t adv_slot; + uint8_t status; + uint8_t opcode; + uint8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_ADVERTISE_CANCEL 0x04 struct bt_hci_cp_mesh_advertise_cancel { - uint8_t adv_slot; + uint8_t adv_slot; } __packed; struct bt_hci_rp_mesh_advertise_cancel { - uint8_t status; - uint8_t opcode; - uint8_t adv_slot; + uint8_t status; + uint8_t opcode; + uint8_t adv_slot; } __packed; #define BT_HCI_OC_MESH_SET_SCANNING 0x05 struct bt_hci_cp_mesh_set_scanning { - uint8_t enable; - uint8_t ch_map; - uint8_t scan_filter; + uint8_t enable; + uint8_t ch_map; + uint8_t scan_filter; } __packed; struct bt_hci_rp_mesh_set_scanning { - uint8_t status; - uint8_t opcode; + uint8_t status; + uint8_t opcode; } __packed; /* Events */ struct bt_hci_evt_mesh { - uint8_t prefix; - uint8_t subevent; + uint8_t prefix; + uint8_t subevent; } __packed; #define BT_HCI_EVT_MESH_ADV_COMPLETE 0x00 struct bt_hci_evt_mesh_adv_complete { - uint8_t adv_slot; + uint8_t adv_slot; } __packed; #define BT_HCI_EVT_MESH_SCANNING_REPORT 0x01 struct bt_hci_evt_mesh_scan_report { - bt_addr_le_t addr; - uint8_t chan; - int8_t rssi; - uint32_t instant; - uint8_t data_len; - uint8_t data[]; + bt_addr_le_t addr; + uint8_t chan; + int8_t rssi; + uint32_t instant; + uint8_t data_len; + uint8_t data[]; } __packed; struct bt_hci_evt_mesh_scanning_report { - uint8_t num_reports; - struct bt_hci_evt_mesh_scan_report reports[]; + uint8_t num_reports; + struct bt_hci_evt_mesh_scan_report reports[]; } __packed; #ifdef __cplusplus diff --git a/devices/ble_hci/common-hal/_bleio/hci_include/l2cap_internal.h b/devices/ble_hci/common-hal/_bleio/hci_include/l2cap_internal.h index a0a2ed056c..b2e7fb450d 100644 --- a/devices/ble_hci/common-hal/_bleio/hci_include/l2cap_internal.h +++ b/devices/ble_hci/common-hal/_bleio/hci_include/l2cap_internal.h @@ -15,8 +15,8 @@ #include enum l2cap_conn_list_action { - BT_L2CAP_CHAN_LOOKUP, - BT_L2CAP_CHAN_DETACH, + BT_L2CAP_CHAN_LOOKUP, + BT_L2CAP_CHAN_DETACH, }; #define BT_L2CAP_CID_BR_SIG 0x0001 @@ -28,14 +28,14 @@ enum l2cap_conn_list_action { #define BT_L2CAP_PSM_RFCOMM 0x0003 struct bt_l2cap_hdr { - uint16_t len; - uint16_t cid; + uint16_t len; + uint16_t cid; } __packed; struct bt_l2cap_sig_hdr { - uint8_t code; - uint8_t ident; - uint16_t len; + uint8_t code; + uint8_t ident; + uint16_t len; } __packed; #define BT_L2CAP_REJ_NOT_UNDERSTOOD 0x0000 @@ -44,19 +44,19 @@ struct bt_l2cap_sig_hdr { #define BT_L2CAP_CMD_REJECT 0x01 struct bt_l2cap_cmd_reject { - uint16_t reason; - uint8_t data[]; + uint16_t reason; + uint8_t data[]; } __packed; struct bt_l2cap_cmd_reject_cid_data { - uint16_t scid; - uint16_t dcid; + uint16_t scid; + uint16_t dcid; } __packed; #define BT_L2CAP_CONN_REQ 0x02 struct bt_l2cap_conn_req { - uint16_t psm; - uint16_t scid; + uint16_t psm; + uint16_t scid; } __packed; /* command statuses in reposnse */ @@ -74,10 +74,10 @@ struct bt_l2cap_conn_req { #define BT_L2CAP_CONN_RSP 0x03 struct bt_l2cap_conn_rsp { - uint16_t dcid; - uint16_t scid; - uint16_t result; - uint16_t status; + uint16_t dcid; + uint16_t scid; + uint16_t result; + uint16_t status; } __packed; #define BT_L2CAP_CONF_SUCCESS 0x0000 @@ -86,17 +86,17 @@ struct bt_l2cap_conn_rsp { #define BT_L2CAP_CONF_REQ 0x04 struct bt_l2cap_conf_req { - uint16_t dcid; - uint16_t flags; - uint8_t data[]; + uint16_t dcid; + uint16_t flags; + uint8_t data[]; } __packed; #define BT_L2CAP_CONF_RSP 0x05 struct bt_l2cap_conf_rsp { - uint16_t scid; - uint16_t flags; - uint16_t result; - uint8_t data[]; + uint16_t scid; + uint16_t flags; + uint16_t result; + uint8_t data[]; } __packed; /* Option type used by MTU config request data */ @@ -106,21 +106,21 @@ struct bt_l2cap_conf_rsp { #define BT_L2CAP_CONF_MASK 0x7f struct bt_l2cap_conf_opt { - uint8_t type; - uint8_t len; - uint8_t data[]; + uint8_t type; + uint8_t len; + uint8_t data[]; } __packed; #define BT_L2CAP_DISCONN_REQ 0x06 struct bt_l2cap_disconn_req { - uint16_t dcid; - uint16_t scid; + uint16_t dcid; + uint16_t scid; } __packed; #define BT_L2CAP_DISCONN_RSP 0x07 struct bt_l2cap_disconn_rsp { - uint16_t dcid; - uint16_t scid; + uint16_t dcid; + uint16_t scid; } __packed; #define BT_L2CAP_INFO_FEAT_MASK 0x0002 @@ -128,7 +128,7 @@ struct bt_l2cap_disconn_rsp { #define BT_L2CAP_INFO_REQ 0x0a struct bt_l2cap_info_req { - uint16_t type; + uint16_t type; } __packed; /* info result */ @@ -137,17 +137,17 @@ struct bt_l2cap_info_req { #define BT_L2CAP_INFO_RSP 0x0b struct bt_l2cap_info_rsp { - uint16_t type; - uint16_t result; - uint8_t data[]; + uint16_t type; + uint16_t result; + uint8_t data[]; } __packed; #define BT_L2CAP_CONN_PARAM_REQ 0x12 struct bt_l2cap_conn_param_req { - uint16_t min_interval; - uint16_t max_interval; - uint16_t latency; - uint16_t timeout; + uint16_t min_interval; + uint16_t max_interval; + uint16_t latency; + uint16_t timeout; } __packed; #define BT_L2CAP_CONN_PARAM_ACCEPTED 0x0000 @@ -155,16 +155,16 @@ struct bt_l2cap_conn_param_req { #define BT_L2CAP_CONN_PARAM_RSP 0x13 struct bt_l2cap_conn_param_rsp { - uint16_t result; + uint16_t result; } __packed; #define BT_L2CAP_LE_CONN_REQ 0x14 struct bt_l2cap_le_conn_req { - uint16_t psm; - uint16_t scid; - uint16_t mtu; - uint16_t mps; - uint16_t credits; + uint16_t psm; + uint16_t scid; + uint16_t mtu; + uint16_t mps; + uint16_t credits; } __packed; /* valid results in conn response on LE */ @@ -182,42 +182,42 @@ struct bt_l2cap_le_conn_req { #define BT_L2CAP_LE_CONN_RSP 0x15 struct bt_l2cap_le_conn_rsp { - uint16_t dcid; - uint16_t mtu; - uint16_t mps; - uint16_t credits; - uint16_t result; + uint16_t dcid; + uint16_t mtu; + uint16_t mps; + uint16_t credits; + uint16_t result; } __packed; #define BT_L2CAP_LE_CREDITS 0x16 struct bt_l2cap_le_credits { - uint16_t cid; - uint16_t credits; + uint16_t cid; + uint16_t credits; } __packed; #define BT_L2CAP_ECRED_CONN_REQ 0x17 struct bt_l2cap_ecred_conn_req { - uint16_t psm; - uint16_t mtu; - uint16_t mps; - uint16_t credits; - uint16_t scid[]; + uint16_t psm; + uint16_t mtu; + uint16_t mps; + uint16_t credits; + uint16_t scid[]; } __packed; #define BT_L2CAP_ECRED_CONN_RSP 0x18 struct bt_l2cap_ecred_conn_rsp { - uint16_t mtu; - uint16_t mps; - uint16_t credits; - uint16_t result; - uint16_t dcid[]; + uint16_t mtu; + uint16_t mps; + uint16_t credits; + uint16_t result; + uint16_t dcid[]; } __packed; #define BT_L2CAP_ECRED_RECONF_REQ 0x19 struct bt_l2cap_ecred_reconf_req { - uint16_t mtu; - uint16_t mps; - uint16_t scid[]; + uint16_t mtu; + uint16_t mps; + uint16_t scid[]; } __packed; #define BT_L2CAP_RECONF_SUCCESS 0x0000 @@ -226,5 +226,5 @@ struct bt_l2cap_ecred_reconf_req { #define BT_L2CAP_ECRED_RECONF_RSP 0x1a struct bt_l2cap_ecred_reconf_rsp { - uint16_t result; + uint16_t result; } __packed; diff --git a/drivers/bus/softqspi.c b/drivers/bus/softqspi.c index 87f7c8ae8c..c0aecf87d2 100644 --- a/drivers/bus/softqspi.c +++ b/drivers/bus/softqspi.c @@ -57,7 +57,7 @@ STATIC void nibble_write(mp_soft_qspi_obj_t *self, uint8_t v) { } STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; switch (cmd) { case MP_QSPI_IOCTL_INIT: @@ -67,7 +67,7 @@ STATIC int mp_soft_qspi_ioctl(void *self_in, uint32_t cmd) { // Configure pins mp_hal_pin_write(self->clk, 0); mp_hal_pin_output(self->clk); - //mp_hal_pin_write(self->clk, 1); + // mp_hal_pin_write(self->clk, 1); mp_hal_pin_output(self->io0); mp_hal_pin_input(self->io1); mp_hal_pin_write(self->io2, 1); @@ -155,19 +155,19 @@ STATIC void mp_soft_qspi_qwrite(mp_soft_qspi_obj_t *self, size_t len, const uint SCK_LOW(self); } - //mp_hal_pin_input(self->io1); + // mp_hal_pin_input(self->io1); } STATIC void mp_soft_qspi_write_cmd_data(void *self_in, uint8_t cmd, size_t len, uint32_t data) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; uint32_t cmd_buf = cmd | data << 8; CS_LOW(self); - mp_soft_qspi_transfer(self, 1 + len, (uint8_t*)&cmd_buf, NULL); + mp_soft_qspi_transfer(self, 1 + len, (uint8_t *)&cmd_buf, NULL); CS_HIGH(self); } STATIC void mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_t addr, size_t len, const uint8_t *src) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; uint8_t cmd_buf[4] = {cmd, addr >> 16, addr >> 8, addr}; CS_LOW(self); mp_soft_qspi_transfer(self, 4, cmd_buf, NULL); @@ -176,16 +176,16 @@ STATIC void mp_soft_qspi_write_cmd_addr_data(void *self_in, uint8_t cmd, uint32_ } STATIC uint32_t mp_soft_qspi_read_cmd(void *self_in, uint8_t cmd, size_t len) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; uint32_t cmd_buf = cmd; CS_LOW(self); - mp_soft_qspi_transfer(self, 1 + len, (uint8_t*)&cmd_buf, (uint8_t*)&cmd_buf); + mp_soft_qspi_transfer(self, 1 + len, (uint8_t *)&cmd_buf, (uint8_t *)&cmd_buf); CS_HIGH(self); return cmd_buf >> 8; } STATIC void mp_soft_qspi_read_cmd_qaddr_qdata(void *self_in, uint8_t cmd, uint32_t addr, size_t len, uint8_t *dest) { - mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t*)self_in; + mp_soft_qspi_obj_t *self = (mp_soft_qspi_obj_t *)self_in; uint8_t cmd_buf[7] = {cmd, addr >> 16, addr >> 8, addr}; CS_LOW(self); mp_soft_qspi_transfer(self, 1, cmd_buf, NULL); diff --git a/drivers/bus/softspi.c b/drivers/bus/softspi.c index feb8e00d38..b0b1accd99 100644 --- a/drivers/bus/softspi.c +++ b/drivers/bus/softspi.c @@ -27,7 +27,7 @@ #include "drivers/bus/spi.h" int mp_soft_spi_ioctl(void *self_in, uint32_t cmd) { - mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t*)self_in; + mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t *)self_in; switch (cmd) { case MP_SPI_IOCTL_INIT: @@ -45,7 +45,7 @@ int mp_soft_spi_ioctl(void *self_in, uint32_t cmd) { } void mp_soft_spi_transfer(void *self_in, size_t len, const uint8_t *src, uint8_t *dest) { - mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t*)self_in; + mp_soft_spi_obj_t *self = (mp_soft_spi_obj_t *)self_in; uint32_t delay_half = self->delay_half; // only MSB transfer is implemented diff --git a/extmod/machine_mem.c b/extmod/machine_mem.c index 8944c3a666..9597b32e6c 100644 --- a/extmod/machine_mem.c +++ b/extmod/machine_mem.c @@ -50,9 +50,15 @@ STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t va uintptr_t addr = MICROPY_MACHINE_MEM_GET_READ_ADDR(index, self->elem_size); uint32_t val; switch (self->elem_size) { - case 1: val = (*(uint8_t*)addr); break; - case 2: val = (*(uint16_t*)addr); break; - default: val = (*(uint32_t*)addr); break; + case 1: + val = (*(uint8_t *)addr); + break; + case 2: + val = (*(uint16_t *)addr); + break; + default: + val = (*(uint32_t *)addr); + break; } return mp_obj_new_int(val); } else { @@ -60,9 +66,15 @@ STATIC mp_obj_t machine_mem_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t va uintptr_t addr = MICROPY_MACHINE_MEM_GET_WRITE_ADDR(index, self->elem_size); uint32_t val = mp_obj_get_int_truncated(value); switch (self->elem_size) { - case 1: (*(uint8_t*)addr) = val; break; - case 2: (*(uint16_t*)addr) = val; break; - default: (*(uint32_t*)addr) = val; break; + case 1: + (*(uint8_t *)addr) = val; + break; + case 2: + (*(uint16_t *)addr) = val; + break; + default: + (*(uint32_t *)addr) = val; + break; } return mp_const_none; } diff --git a/extmod/machine_signal.c b/extmod/machine_signal.c index a215fc3889..a8e5ebc928 100644 --- a/extmod/machine_signal.c +++ b/extmod/machine_signal.c @@ -26,7 +26,7 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, const bool invert = false; #if defined(MICROPY_PY_MACHINE_PIN_MAKE_NEW) - mp_pin_p_t *pin_p = (mp_pin_t*)mp_proto_get(QSTR_pin_protocol, pin); + mp_pin_p_t *pin_p = (mp_pin_t *)mp_proto_get(QSTR_pin_protocol, pin); if (pin_p == NULL) { // If first argument isn't a Pin-like object, we filter out "invert" @@ -64,8 +64,7 @@ STATIC mp_obj_t signal_make_new(const mp_obj_type_t *type, size_t n_args, const pin = MICROPY_PY_MACHINE_PIN_MAKE_NEW(NULL, n_args, n_kw, pin_args); mp_local_free(pin_args); - } - else + } else #endif // Otherwise there should be 1 or 2 args { @@ -154,7 +153,7 @@ const mp_obj_type_t machine_signal_type = { .make_new = signal_make_new, .call = signal_call, .protocol = &signal_pin_p, - .locals_dict = (void*)&signal_locals_dict, + .locals_dict = (void *)&signal_locals_dict, }; #endif // MICROPY_PY_MACHINE diff --git a/extmod/modbtree.c b/extmod/modbtree.c index 9f5261b1b7..ac996218ce 100644 --- a/extmod/modbtree.c +++ b/extmod/modbtree.c @@ -34,9 +34,9 @@ typedef struct _mp_obj_btree_t { STATIC const mp_obj_type_t btree_type; #define CHECK_ERROR(res) \ - if (res == RET_ERROR) { \ - mp_raise_OSError(errno); \ - } + if (res == RET_ERROR) { \ + mp_raise_OSError(errno); \ + } void __dbpanic(DB *db) { printf("__dbpanic(%p)\n", db); @@ -74,8 +74,8 @@ STATIC mp_obj_t btree_put(size_t n_args, const mp_obj_t *args) { (void)n_args; mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]); DBT key, val; - key.data = (void*)mp_obj_str_get_data(args[1], &key.size); - val.data = (void*)mp_obj_str_get_data(args[2], &val.size); + key.data = (void *)mp_obj_str_get_data(args[1], &key.size); + val.data = (void *)mp_obj_str_get_data(args[2], &val.size); return MP_OBJ_NEW_SMALL_INT(__bt_put(self->db, &key, &val, 0)); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_put_obj, 3, 4, btree_put); @@ -83,7 +83,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(btree_put_obj, 3, 4, btree_put); STATIC mp_obj_t btree_get(size_t n_args, const mp_obj_t *args) { mp_obj_btree_t *self = MP_OBJ_TO_PTR(args[0]); DBT key, val; - key.data = (void*)mp_obj_str_get_data(args[1], &key.size); + key.data = (void *)mp_obj_str_get_data(args[1], &key.size); int res = __bt_get(self->db, &key, &val, 0); if (res == RET_SPECIAL) { if (n_args > 2) { @@ -102,7 +102,7 @@ STATIC mp_obj_t btree_seq(size_t n_args, const mp_obj_t *args) { int flags = MP_OBJ_SMALL_INT_VALUE(args[1]); DBT key, val; if (n_args > 2) { - key.data = (void*)mp_obj_str_get_data(args[2], &key.size); + key.data = (void *)mp_obj_str_get_data(args[2], &key.size); } int res = __bt_seq(self->db, &key, &val, flags); @@ -177,7 +177,7 @@ STATIC mp_obj_t btree_iternext(mp_obj_t self_in) { if (self->start_key != MP_OBJ_NULL) { int flags = R_FIRST; if (self->start_key != mp_const_none) { - key.data = (void*)mp_obj_str_get_data(self->start_key, &key.size); + key.data = (void *)mp_obj_str_get_data(self->start_key, &key.size); flags = R_CURSOR; } else if (desc) { flags = R_LAST; @@ -195,7 +195,7 @@ STATIC mp_obj_t btree_iternext(mp_obj_t self_in) { if (self->end_key != mp_const_none) { DBT end_key; - end_key.data = (void*)mp_obj_str_get_data(self->end_key, &end_key.size); + end_key.data = (void *)mp_obj_str_get_data(self->end_key, &end_key.size); BTREE *t = self->db->internal; int cmp = t->bt_cmp(&key, &end_key); if (desc) { @@ -230,7 +230,7 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { if (value == MP_OBJ_NULL) { // delete DBT key; - key.data = (void*)mp_obj_str_get_data(index, &key.size); + key.data = (void *)mp_obj_str_get_data(index, &key.size); int res = __bt_delete(self->db, &key, 0); if (res == RET_SPECIAL) { nlr_raise(mp_obj_new_exception(&mp_type_KeyError)); @@ -240,7 +240,7 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } else if (value == MP_OBJ_SENTINEL) { // load DBT key, val; - key.data = (void*)mp_obj_str_get_data(index, &key.size); + key.data = (void *)mp_obj_str_get_data(index, &key.size); int res = __bt_get(self->db, &key, &val, 0); if (res == RET_SPECIAL) { nlr_raise(mp_obj_new_exception(&mp_type_KeyError)); @@ -250,8 +250,8 @@ STATIC mp_obj_t btree_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } else { // store DBT key, val; - key.data = (void*)mp_obj_str_get_data(index, &key.size); - val.data = (void*)mp_obj_str_get_data(value, &val.size); + key.data = (void *)mp_obj_str_get_data(index, &key.size); + val.data = (void *)mp_obj_str_get_data(value, &val.size); int res = __bt_put(self->db, &key, &val, 0); CHECK_ERROR(res); return mp_const_none; @@ -263,7 +263,7 @@ STATIC mp_obj_t btree_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs switch (op) { case MP_BINARY_OP_CONTAINS: { DBT key, val; - key.data = (void*)mp_obj_str_get_data(rhs_in, &key.size); + key.data = (void *)mp_obj_str_get_data(rhs_in, &key.size); int res = __bt_get(self->db, &key, &val, 0); CHECK_ERROR(res); return mp_obj_new_bool(res != RET_SPECIAL); @@ -296,7 +296,7 @@ STATIC const mp_obj_type_t btree_type = { .iternext = btree_iternext, .binary_op = btree_binary_op, .subscr = btree_subscr, - .locals_dict = (void*)&btree_locals_dict, + .locals_dict = (void *)&btree_locals_dict, }; STATIC FILEVTABLE btree_stream_fvtable = { @@ -324,14 +324,14 @@ STATIC mp_obj_t mod_btree_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t mp_arg_val_t minkeypage; } args; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, - MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args); + MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); BTREEINFO openinfo = {0}; openinfo.flags = args.flags.u_int; openinfo.cachesize = args.cachesize.u_int; openinfo.psize = args.pagesize.u_int; openinfo.minkeypage = args.minkeypage.u_int; - DB *db = __bt_open(pos_args[0], &btree_stream_fvtable, &openinfo, /*dflags*/0); + DB *db = __bt_open(pos_args[0], &btree_stream_fvtable, &openinfo, /*dflags*/ 0); if (db == NULL) { mp_raise_OSError(errno); } @@ -350,7 +350,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_btree_globals, mp_module_btree_globals_tab const mp_obj_module_t mp_module_btree = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_btree_globals, + .globals = (mp_obj_dict_t *)&mp_module_btree_globals, }; #endif // MICROPY_PY_BTREE diff --git a/extmod/modframebuf.c b/extmod/modframebuf.c index 07a50a2f4c..ce280090f4 100644 --- a/extmod/modframebuf.c +++ b/extmod/modframebuf.c @@ -22,8 +22,8 @@ typedef struct _mp_obj_framebuf_t { uint8_t format; } mp_obj_framebuf_t; -typedef void (*setpixel_t)(const mp_obj_framebuf_t*, int, int, uint32_t); -typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t*, int, int); +typedef void (*setpixel_t)(const mp_obj_framebuf_t *, int, int, uint32_t); +typedef uint32_t (*getpixel_t)(const mp_obj_framebuf_t *, int, int); typedef void (*fill_rect_t)(const mp_obj_framebuf_t *, int, int, int, int, uint32_t); typedef struct _mp_framebuf_p_t { @@ -47,20 +47,20 @@ typedef struct _mp_framebuf_p_t { STATIC void mono_horiz_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { size_t index = (x + y * fb->stride) >> 3; int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07); - ((uint8_t*)fb->buf)[index] = (((uint8_t*)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); + ((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); } STATIC uint32_t mono_horiz_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { size_t index = (x + y * fb->stride) >> 3; int offset = fb->format == FRAMEBUF_MHMSB ? x & 0x07 : 7 - (x & 0x07); - return (((uint8_t*)fb->buf)[index] >> (offset)) & 0x01; + return (((uint8_t *)fb->buf)[index] >> (offset)) & 0x01; } STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { int reverse = fb->format == FRAMEBUF_MHMSB; int advance = fb->stride >> 3; while (w--) { - uint8_t *b = &((uint8_t*)fb->buf)[(x >> 3) + y * advance]; + uint8_t *b = &((uint8_t *)fb->buf)[(x >> 3) + y * advance]; int offset = reverse ? x & 7 : 7 - (x & 7); for (int hh = h; hh; --hh) { *b = (*b & ~(0x01 << offset)) | ((col != 0) << offset); @@ -75,16 +75,16 @@ STATIC void mono_horiz_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int STATIC void mvlsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { size_t index = (y >> 3) * fb->stride + x; uint8_t offset = y & 0x07; - ((uint8_t*)fb->buf)[index] = (((uint8_t*)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); + ((uint8_t *)fb->buf)[index] = (((uint8_t *)fb->buf)[index] & ~(0x01 << offset)) | ((col != 0) << offset); } STATIC uint32_t mvlsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { - return (((uint8_t*)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01; + return (((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x] >> (y & 0x07)) & 0x01; } STATIC void mvlsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { while (h--) { - uint8_t *b = &((uint8_t*)fb->buf)[(y >> 3) * fb->stride + x]; + uint8_t *b = &((uint8_t *)fb->buf)[(y >> 3) * fb->stride + x]; uint8_t offset = y & 0x07; for (int ww = w; ww; --ww) { *b = (*b & ~(0x01 << offset)) | ((col != 0) << offset); @@ -97,15 +97,15 @@ STATIC void mvlsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, in // Functions for RGB565 format STATIC void rgb565_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { - ((uint16_t*)fb->buf)[x + y * fb->stride] = col; + ((uint16_t *)fb->buf)[x + y * fb->stride] = col; } STATIC uint32_t rgb565_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { - return ((uint16_t*)fb->buf)[x + y * fb->stride]; + return ((uint16_t *)fb->buf)[x + y * fb->stride]; } STATIC void rgb565_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { - uint16_t *b = &((uint16_t*)fb->buf)[x + y * fb->stride]; + uint16_t *b = &((uint16_t *)fb->buf)[x + y * fb->stride]; while (h--) { for (int ww = w; ww; --ww) { *b++ = col; @@ -117,7 +117,7 @@ STATIC void rgb565_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, i // Functions for GS2_HMSB format STATIC void gs2_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { - uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 2]; + uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2]; uint8_t shift = (x & 0x3) << 1; uint8_t mask = 0x3 << shift; uint8_t color = (col & 0x3) << shift; @@ -125,14 +125,14 @@ STATIC void gs2_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_ } STATIC uint32_t gs2_hmsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { - uint8_t pixel = ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 2]; + uint8_t pixel = ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 2]; uint8_t shift = (x & 0x3) << 1; return (pixel >> shift) & 0x3; } STATIC void gs2_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { - for (int xx=x; xx < x+w; xx++) { - for (int yy=y; yy < y+h; yy++) { + for (int xx = x; xx < x + w; xx++) { + for (int yy = y; yy < y + h; yy++) { gs2_hmsb_setpixel(fb, xx, yy, col); } } @@ -141,7 +141,7 @@ STATIC void gs2_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, // Functions for GS4_HMSB format STATIC void gs4_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { - uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1]; + uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1]; if (x % 2) { *pixel = ((uint8_t)col & 0x0f) | (*pixel & 0xf0); @@ -152,15 +152,15 @@ STATIC void gs4_hmsb_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_ STATIC uint32_t gs4_hmsb_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { if (x % 2) { - return ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f; + return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] & 0x0f; } - return ((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1] >> 4; + return ((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1] >> 4; } STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { col &= 0x0f; - uint8_t *pixel_pair = &((uint8_t*)fb->buf)[(x + y * fb->stride) >> 1]; + uint8_t *pixel_pair = &((uint8_t *)fb->buf)[(x + y * fb->stride) >> 1]; uint8_t col_shifted_left = col << 4; uint8_t col_pixel_pair = col_shifted_left | col; int pixel_count_till_next_line = (fb->stride - w) >> 1; @@ -192,16 +192,16 @@ STATIC void gs4_hmsb_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, // Functions for GS8 format STATIC void gs8_setpixel(const mp_obj_framebuf_t *fb, int x, int y, uint32_t col) { - uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride)]; + uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)]; *pixel = col & 0xff; } STATIC uint32_t gs8_getpixel(const mp_obj_framebuf_t *fb, int x, int y) { - return ((uint8_t*)fb->buf)[(x + y * fb->stride)]; + return ((uint8_t *)fb->buf)[(x + y * fb->stride)]; } STATIC void gs8_fill_rect(const mp_obj_framebuf_t *fb, int x, int y, int w, int h, uint32_t col) { - uint8_t *pixel = &((uint8_t*)fb->buf)[(x + y * fb->stride)]; + uint8_t *pixel = &((uint8_t *)fb->buf)[(x + y * fb->stride)]; while (h--) { memset(pixel, col, w); pixel += fb->stride; @@ -287,7 +287,7 @@ STATIC mp_obj_t framebuf_make_new(const mp_obj_type_t *type, size_t n_args, cons STATIC const mp_obj_type_t mp_type_framebuf; // Helper to ensure we have the native super class instead of a subclass. -static mp_obj_framebuf_t* native_framebuf(mp_obj_t framebuf_obj) { +static mp_obj_framebuf_t *native_framebuf(mp_obj_t framebuf_obj) { mp_obj_t native_framebuf = mp_instance_cast_to_native_base(framebuf_obj, &mp_type_framebuf); mp_obj_assert_native_inited(native_framebuf); return MP_OBJ_TO_PTR(native_framebuf); @@ -384,9 +384,9 @@ STATIC mp_obj_t framebuf_rect(size_t n_args, const mp_obj_t *args) { mp_int_t col = mp_obj_get_int(args[5]); fill_rect(self, x, y, w, 1, col); - fill_rect(self, x, y + h- 1, w, 1, col); + fill_rect(self, x, y + h - 1, w, 1, col); fill_rect(self, x, y, 1, h, col); - fill_rect(self, x + w- 1, y, 1, h, col); + fill_rect(self, x + w - 1, y, 1, h, col); return mp_const_none; } @@ -423,9 +423,15 @@ STATIC mp_obj_t framebuf_line(size_t n_args, const mp_obj_t *args) { bool steep; if (dy > dx) { mp_int_t temp; - temp = x1; x1 = y1; y1 = temp; - temp = dx; dx = dy; dy = temp; - temp = sx; sx = sy; sy = temp; + temp = x1; + x1 = y1; + y1 = temp; + temp = dx; + dx = dy; + dy = temp; + temp = sx; + sx = sy; + sy = temp; steep = true; } else { steep = false; @@ -473,7 +479,7 @@ STATIC mp_obj_t framebuf_blit(size_t n_args, const mp_obj_t *args) { (y >= self->height) || (-x >= source->width) || (-y >= source->height) - ) { + ) { // Out of bounds, no-op. return mp_const_none; } @@ -547,7 +553,7 @@ STATIC mp_obj_t framebuf_text(size_t n_args, const mp_obj_t *args) { // loop over chars for (; *str; ++str) { // get char and make sure its in range of font - int chr = *(uint8_t*)str; + int chr = *(uint8_t *)str; if (chr < 32 || chr > 127) { chr = 127; } @@ -590,7 +596,7 @@ STATIC const mp_obj_type_t mp_type_framebuf = { .name = MP_QSTR_FrameBuffer, .make_new = framebuf_make_new, .buffer_p = { .get_buffer = framebuf_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&framebuf_locals_dict, + .locals_dict = (mp_obj_dict_t *)&framebuf_locals_dict, }; // this factory function is provided for backwards compatibility with old FrameBuffer1 class @@ -633,7 +639,7 @@ STATIC MP_DEFINE_CONST_DICT(framebuf_module_globals, framebuf_module_globals_tab const mp_obj_module_t mp_module_framebuf = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&framebuf_module_globals, + .globals = (mp_obj_dict_t *)&framebuf_module_globals, }; #endif // MICROPY_PY_FRAMEBUF diff --git a/extmod/modlwip.c b/extmod/modlwip.c index 20cc3a6594..6eb68d3fb9 100644 --- a/extmod/modlwip.c +++ b/extmod/modlwip.c @@ -19,7 +19,7 @@ #include "lwip/init.h" #include "lwip/tcp.h" #include "lwip/udp.h" -//#include "lwip/raw.h" +// #include "lwip/raw.h" #include "lwip/dns.h" #include "lwip/igmp.h" #if LWIP_VERSION_MAJOR < 2 @@ -71,7 +71,7 @@ void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg); void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg); STATIC void slip_lwip_poll(void *netif) { - slipif_poll((struct netif*)netif); + slipif_poll((struct netif *)netif); } STATIC const mp_obj_type_t lwip_slip_type; @@ -120,7 +120,7 @@ STATIC mp_obj_t lwip_slip_make_new(mp_obj_t type_in, size_t n_args, size_t n_kw, struct netif *n = &lwip_slip_obj.lwip_netif; if (netif_add(n, &iplocal, IP_ADDR_BROADCAST, &ipremote, NULL, slipif_init, ip_input) == NULL) { - mp_raise_ValueError("out of memory"); + mp_raise_ValueError("out of memory"); } netif_set_up(n); netif_set_default(n); @@ -146,7 +146,7 @@ STATIC const mp_obj_type_t lwip_slip_type = { { &mp_type_type }, .name = MP_QSTR_slip, .make_new = lwip_slip_make_new, - .locals_dict = (mp_obj_dict_t*)&lwip_slip_locals_dict, + .locals_dict = (mp_obj_dict_t *)&lwip_slip_locals_dict, }; #endif // MICROPY_PY_LWIP_SLIP @@ -158,7 +158,7 @@ STATIC const mp_obj_type_t lwip_slip_type = { // lwIP 2 changed LWIP_VERSION and it can no longer be used in macros, // so we define our own equivalent version that can. #define LWIP_VERSION_MACRO (LWIP_VERSION_MAJOR << 24 | LWIP_VERSION_MINOR << 16 \ - | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) + | LWIP_VERSION_REVISION << 8 | LWIP_VERSION_RC) // Extension to lwIP error codes #define _ERR_BADF -16 @@ -271,11 +271,11 @@ typedef struct _lwip_socket_obj_t { } lwip_socket_obj_t; static inline void poll_sockets(void) { -#ifdef MICROPY_EVENT_POLL_HOOK + #ifdef MICROPY_EVENT_POLL_HOOK MICROPY_EVENT_POLL_HOOK; -#else + #else mp_hal_delay_ms(1); -#endif + #endif } /*******************************************************************************/ @@ -295,7 +295,7 @@ STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, const ip_addr_t *addr, u16_t port) #endif { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; if (socket->incoming.pbuf != NULL) { // That's why they call it "unreliable". No room in the inn, drop the packet. @@ -309,7 +309,7 @@ STATIC void _lwip_udp_incoming(void *arg, struct udp_pcb *upcb, struct pbuf *p, // Callback for general tcp errors. STATIC void _lwip_tcp_error(void *arg, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; // Pass the error code back via the connection variable. socket->state = err; @@ -319,7 +319,7 @@ STATIC void _lwip_tcp_error(void *arg, err_t err) { // Callback for tcp connection requests. Error code err is unused. (See tcp.h) STATIC err_t _lwip_tcp_connected(void *arg, struct tcp_pcb *tpcb, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; socket->state = STATE_CONNECTED; return ERR_OK; @@ -337,9 +337,8 @@ STATIC err_t _lwip_tcp_recv_unaccepted(void *arg, struct tcp_pcb *pcb, struct pb // "Poll" (idle) callback to be called ASAP after accept callback // to execute Python callback function, as it can't be executed // from accept callback itself. -STATIC err_t _lwip_tcp_accept_finished(void *arg, struct tcp_pcb *pcb) -{ - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; +STATIC err_t _lwip_tcp_accept_finished(void *arg, struct tcp_pcb *pcb) { + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; tcp_poll(pcb, NULL, 0); exec_user_callback(socket); return ERR_OK; @@ -347,7 +346,7 @@ STATIC err_t _lwip_tcp_accept_finished(void *arg, struct tcp_pcb *pcb) // Callback for incoming tcp connections. STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; tcp_recv(newpcb, _lwip_tcp_recv_unaccepted); if (socket->incoming.connection != NULL) { @@ -369,7 +368,7 @@ STATIC err_t _lwip_tcp_accept(void *arg, struct tcp_pcb *newpcb, err_t err) { // Callback for inbound tcp packets. STATIC err_t _lwip_tcp_recv(void *arg, struct tcp_pcb *tcpb, struct pbuf *p, err_t err) { - lwip_socket_obj_t *socket = (lwip_socket_obj_t*)arg; + lwip_socket_obj_t *socket = (lwip_socket_obj_t *)arg; if (p == NULL) { // Other side has closed connection. @@ -443,7 +442,9 @@ STATIC mp_uint_t lwip_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_ if (socket->timeout != -1) { for (mp_uint_t retries = socket->timeout / 100; retries--;) { mp_hal_delay_ms(100); - if (socket->incoming.pbuf != NULL) break; + if (socket->incoming.pbuf != NULL) { + break; + } } if (socket->incoming.pbuf == NULL) { *_errno = MP_ETIMEDOUT; @@ -467,16 +468,16 @@ STATIC mp_uint_t lwip_udp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_ pbuf_free(p); socket->incoming.pbuf = NULL; - return (mp_uint_t) result; + return (mp_uint_t)result; } // For use in stream virtual methods #define STREAM_ERROR_CHECK(socket) \ - if (socket->state < 0) { \ - *_errno = error_lookup_table[-socket->state]; \ - return MP_STREAM_ERROR; \ - } \ - assert(socket->pcb.tcp); + if (socket->state < 0) { \ + *_errno = error_lookup_table[-socket->state]; \ + return MP_STREAM_ERROR; \ + } \ + assert(socket->pcb.tcp); // Helper function for send/sendto to handle TCP packets @@ -575,7 +576,7 @@ STATIC mp_uint_t lwip_tcp_receive(lwip_socket_obj_t *socket, byte *buf, mp_uint_ len = remaining; } - memcpy(buf, (byte*)p->payload + socket->recv_offset, len); + memcpy(buf, (byte *)p->payload + socket->recv_offset, len); remaining -= len; if (remaining == 0) { @@ -622,10 +623,15 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s } switch (socket->type) { - case MOD_NETWORK_SOCK_STREAM: socket->pcb.tcp = tcp_new(); break; - case MOD_NETWORK_SOCK_DGRAM: socket->pcb.udp = udp_new(); break; - //case MOD_NETWORK_SOCK_RAW: socket->pcb.raw = raw_new(); break; - default: mp_raise_OSError(MP_EINVAL); + case MOD_NETWORK_SOCK_STREAM: + socket->pcb.tcp = tcp_new(); + break; + case MOD_NETWORK_SOCK_DGRAM: + socket->pcb.udp = udp_new(); + break; + // case MOD_NETWORK_SOCK_RAW: socket->pcb.raw = raw_new(); break; + default: + mp_raise_OSError(MP_EINVAL); } if (socket->pcb.tcp == NULL) { @@ -635,7 +641,7 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { // Register the socket object as our callback argument. - tcp_arg(socket->pcb.tcp, (void*)socket); + tcp_arg(socket->pcb.tcp, (void *)socket); // Register our error callback. tcp_err(socket->pcb.tcp, _lwip_tcp_error); break; @@ -643,7 +649,7 @@ STATIC mp_obj_t lwip_socket_make_new(const mp_obj_type_t *type, size_t n_args, s case MOD_NETWORK_SOCK_DGRAM: { // Register our receive callback now. Since UDP sockets don't require binding or connection // before use, there's no other good time to do it. - udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void*)socket); + udp_recv(socket->pcb.udp, _lwip_udp_incoming, (void *)socket); break; } } @@ -731,7 +737,9 @@ STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) { } else if (socket->timeout != -1) { for (mp_uint_t retries = socket->timeout / 100; retries--;) { mp_hal_delay_ms(100); - if (socket->incoming.connection != NULL) break; + if (socket->incoming.connection != NULL) { + break; + } } if (socket->incoming.connection == NULL) { mp_raise_OSError(MP_ETIMEDOUT); @@ -759,7 +767,7 @@ STATIC mp_obj_t lwip_socket_accept(mp_obj_t self_in) { socket2->state = STATE_CONNECTED; socket2->recv_offset = 0; socket2->callback = MP_OBJ_NULL; - tcp_arg(socket2->pcb.tcp, (void*)socket2); + tcp_arg(socket2->pcb.tcp, (void *)socket2); tcp_err(socket2->pcb.tcp, _lwip_tcp_error); tcp_recv(socket2->pcb.tcp, _lwip_tcp_recv); @@ -815,7 +823,9 @@ STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { if (socket->timeout != -1) { for (mp_uint_t retries = socket->timeout / 100; retries--;) { mp_hal_delay_ms(100); - if (socket->state != STATE_CONNECTING) break; + if (socket->state != STATE_CONNECTING) { + break; + } } if (socket->state == STATE_CONNECTING) { mp_raise_OSError(MP_EINPROGRESS); @@ -826,9 +836,9 @@ STATIC mp_obj_t lwip_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { } } if (socket->state == STATE_CONNECTED) { - err = ERR_OK; + err = ERR_OK; } else { - err = socket->state; + err = socket->state; } break; } @@ -896,11 +906,11 @@ STATIC mp_obj_t lwip_socket_recv(mp_obj_t self_in, mp_obj_t len_in) { mp_uint_t ret = 0; switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { - ret = lwip_tcp_receive(socket, (byte*)vstr.buf, len, &_errno); + ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); break; } case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte*)vstr.buf, len, NULL, NULL, &_errno); + ret = lwip_udp_receive(socket, (byte *)vstr.buf, len, NULL, NULL, &_errno); break; } } @@ -963,12 +973,12 @@ STATIC mp_obj_t lwip_socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { switch (socket->type) { case MOD_NETWORK_SOCK_STREAM: { memcpy(ip, &socket->peer, sizeof(socket->peer)); - port = (mp_uint_t) socket->peer_port; - ret = lwip_tcp_receive(socket, (byte*)vstr.buf, len, &_errno); + port = (mp_uint_t)socket->peer_port; + ret = lwip_tcp_receive(socket, (byte *)vstr.buf, len, &_errno); break; } case MOD_NETWORK_SOCK_DGRAM: { - ret = lwip_udp_receive(socket, (byte*)vstr.buf, len, ip, &port, &_errno); + ret = lwip_udp_receive(socket, (byte *)vstr.buf, len, ip, &port, &_errno); break; } } @@ -1017,7 +1027,7 @@ STATIC mp_obj_t lwip_socket_sendall(mp_obj_t self_in, mp_obj_t buf_in) { mp_raise_OSError(_errno); } bufinfo.len -= ret; - bufinfo.buf = (char*)bufinfo.buf + ret; + bufinfo.buf = (char *)bufinfo.buf + ret; } break; } @@ -1095,7 +1105,7 @@ STATIC mp_obj_t lwip_socket_setsockopt(size_t n_args, const mp_obj_t *args) { } // POSIX setsockopt has order: group addr, if addr, lwIP has it vice-versa - err_t err = igmp_joingroup((ip_addr_t*)bufinfo.buf + 1, bufinfo.buf); + err_t err = igmp_joingroup((ip_addr_t *)bufinfo.buf + 1, bufinfo.buf); if (err != ERR_OK) { mp_raise_OSError(error_lookup_table[-err]); } @@ -1192,8 +1202,10 @@ STATIC mp_uint_t lwip_socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_ } break; } - case MOD_NETWORK_SOCK_DGRAM: udp_remove(socket->pcb.udp); break; - //case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break; + case MOD_NETWORK_SOCK_DGRAM: + udp_remove(socket->pcb.udp); + break; + // case MOD_NETWORK_SOCK_RAW: raw_remove(socket->pcb.raw); break; } socket->pcb.tcp = NULL; socket->state = _ERR_BADF; @@ -1252,7 +1264,7 @@ STATIC const mp_obj_type_t lwip_socket_type = { .print = lwip_socket_print, .make_new = lwip_socket_make_new, .protocol = &lwip_socket_stream_p, - .locals_dict = (mp_obj_dict_t*)&lwip_socket_locals_dict, + .locals_dict = (mp_obj_dict_t *)&lwip_socket_locals_dict, }; /******************************************************************************/ @@ -1272,18 +1284,18 @@ void sys_arch_unprotect(sys_prot_t state) { // itself a "list" but isn't; we only support a single interface. typedef struct nic_poll { - void (* poll)(void *arg); + void (*poll)(void *arg); void *poll_arg; } nic_poll_t; STATIC nic_poll_t lwip_poll_list; -void mod_lwip_register_poll(void (* poll)(void *arg), void *poll_arg) { +void mod_lwip_register_poll(void (*poll)(void *arg), void *poll_arg) { lwip_poll_list.poll = poll; lwip_poll_list.poll_arg = poll_arg; } -void mod_lwip_deregister_poll(void (* poll)(void *arg), void *poll_arg) { +void mod_lwip_deregister_poll(void (*poll)(void *arg), void *poll_arg) { lwip_poll_list.poll = NULL; } @@ -1350,9 +1362,9 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { } } if (!((family == 0 || family == MOD_NETWORK_AF_INET) - && (type == 0 || type == MOD_NETWORK_SOCK_STREAM) - && proto == 0 - && flags == 0)) { + && (type == 0 || type == MOD_NETWORK_SOCK_STREAM) + && proto == 0 + && flags == 0)) { mp_warning("unsupported getaddrinfo constraints"); } } @@ -1360,7 +1372,7 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { getaddrinfo_state_t state; state.status = 0; - err_t ret = dns_gethostbyname(host, (ip_addr_t*)&state.ipaddr, lwip_getaddrinfo_cb, &state); + err_t ret = dns_gethostbyname(host, (ip_addr_t *)&state.ipaddr, lwip_getaddrinfo_cb, &state); switch (ret) { case ERR_OK: // cached @@ -1386,8 +1398,8 @@ STATIC mp_obj_t lwip_getaddrinfo(size_t n_args, const mp_obj_t *args) { tuple->items[1] = MP_OBJ_NEW_SMALL_INT(MOD_NETWORK_SOCK_STREAM); tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0); tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_); - tuple->items[4] = netutils_format_inet_addr((uint8_t*)&state.ipaddr, port, NETUTILS_BIG); - return mp_obj_new_list(1, (mp_obj_t*)&tuple); + tuple->items[4] = netutils_format_inet_addr((uint8_t *)&state.ipaddr, port, NETUTILS_BIG); + return mp_obj_new_list(1, (mp_obj_t *)&tuple); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lwip_getaddrinfo_obj, 2, 6, lwip_getaddrinfo); @@ -1409,9 +1421,9 @@ STATIC const mp_rom_map_elem_t mp_module_lwip_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_print_pcbs), MP_ROM_PTR(&lwip_print_pcbs_obj) }, // objects { MP_ROM_QSTR(MP_QSTR_socket), MP_ROM_PTR(&lwip_socket_type) }, -#if MICROPY_PY_LWIP_SLIP + #if MICROPY_PY_LWIP_SLIP { MP_ROM_QSTR(MP_QSTR_slip), MP_ROM_PTR(&lwip_slip_type) }, -#endif + #endif // class constants { MP_ROM_QSTR(MP_QSTR_AF_INET), MP_ROM_INT(MOD_NETWORK_AF_INET) }, { MP_ROM_QSTR(MP_QSTR_AF_INET6), MP_ROM_INT(MOD_NETWORK_AF_INET6) }, @@ -1431,7 +1443,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_lwip_globals, mp_module_lwip_globals_table const mp_obj_module_t mp_module_lwip = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_lwip_globals, + .globals = (mp_obj_dict_t *)&mp_module_lwip_globals, }; #endif // MICROPY_PY_LWIP diff --git a/extmod/modonewire.c b/extmod/modonewire.c index 1b085a0555..8b4ef86b0c 100644 --- a/extmod/modonewire.c +++ b/extmod/modonewire.c @@ -105,7 +105,7 @@ STATIC mp_obj_t onewire_crc8(mp_obj_t data) { mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); uint8_t crc = 0; for (size_t i = 0; i < bufinfo.len; ++i) { - uint8_t byte = ((uint8_t*)bufinfo.buf)[i]; + uint8_t byte = ((uint8_t *)bufinfo.buf)[i]; for (int b = 0; b < 8; ++b) { uint8_t fb_bit = (crc ^ byte) & 0x01; if (fb_bit == 0x01) { @@ -137,5 +137,5 @@ STATIC MP_DEFINE_CONST_DICT(onewire_module_globals, onewire_module_globals_table const mp_obj_module_t mp_module_onewire = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&onewire_module_globals, + .globals = (mp_obj_dict_t *)&onewire_module_globals, }; diff --git a/extmod/modubinascii.c b/extmod/modubinascii.c index 32c36eea6d..91df02317e 100644 --- a/extmod/modubinascii.c +++ b/extmod/modubinascii.c @@ -12,11 +12,11 @@ #include "extmod/modubinascii.h" static void check_not_unicode(const mp_obj_t arg) { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT if (MP_OBJ_IS_STR(arg)) { mp_raise_TypeError(translate("a bytes-like object is required")); } -#endif + #endif } mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args) { @@ -41,7 +41,7 @@ mp_obj_t mod_binascii_hexlify(size_t n_args, const mp_obj_t *args) { sep = mp_obj_str_get_str(args[1]); } vstr_init_len(&vstr, out_len); - byte *in = bufinfo.buf, *out = (byte*)vstr.buf; + byte *in = bufinfo.buf, *out = (byte *)vstr.buf; for (mp_uint_t i = bufinfo.len; i--;) { byte d = (*in >> 4); if (d > 9) { @@ -70,7 +70,7 @@ mp_obj_t mod_binascii_unhexlify(mp_obj_t data) { } vstr_t vstr; vstr_init_len(&vstr, bufinfo.len / 2); - byte *in = bufinfo.buf, *out = (byte*)vstr.buf; + byte *in = bufinfo.buf, *out = (byte *)vstr.buf; byte hex_byte = 0; for (mp_uint_t i = bufinfo.len; i--;) { byte hex_ch = *in++; @@ -161,7 +161,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { vstr_init_len(&vstr, ((bufinfo.len != 0) ? (((bufinfo.len - 1) / 3) + 1) * 4 : 0) + 1); // First pass, we convert input buffer to numeric base 64 values - byte *in = bufinfo.buf, *out = (byte*)vstr.buf; + byte *in = bufinfo.buf, *out = (byte *)vstr.buf; mp_uint_t i; for (i = bufinfo.len; i >= 3; i -= 3) { *out++ = (in[0] & 0xFC) >> 2; @@ -175,8 +175,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { if (i == 2) { *out++ = (in[0] & 0x03) << 4 | (in[1] & 0xF0) >> 4; *out++ = (in[1] & 0x0F) << 2; - } - else { + } else { *out++ = (in[0] & 0x03) << 4; *out++ = 64; } @@ -184,7 +183,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { } // Second pass, we convert number base 64 values to actual base64 ascii encoding - out = (byte*)vstr.buf; + out = (byte *)vstr.buf; for (mp_uint_t j = vstr.len - 1; j--;) { if (*out < 26) { *out += 'A'; @@ -193,7 +192,7 @@ mp_obj_t mod_binascii_b2a_base64(mp_obj_t data) { } else if (*out < 62) { *out += '0' - 52; } else if (*out == 62) { - *out ='+'; + *out = '+'; } else if (*out == 63) { *out = '/'; } else { @@ -237,7 +236,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_binascii_globals, mp_module_binascii_globa const mp_obj_module_t mp_module_ubinascii = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_binascii_globals, + .globals = (mp_obj_dict_t *)&mp_module_binascii_globals, }; -#endif //MICROPY_PY_UBINASCII +#endif // MICROPY_PY_UBINASCII diff --git a/extmod/moductypes.c b/extmod/moductypes.c index dc8ac4c721..8499d1c29a 100644 --- a/extmod/moductypes.c +++ b/extmod/moductypes.c @@ -105,7 +105,7 @@ STATIC mp_obj_t uctypes_struct_make_new(const mp_obj_type_t *type, size_t n_args mp_arg_check_num(n_args, kw_args, 2, 3, false); mp_obj_uctypes_struct_t *o = m_new_obj(mp_obj_uctypes_struct_t); o->base.type = type; - o->addr = (void*)(uintptr_t)mp_obj_int_get_truncated(args[0]); + o->addr = (void *)(uintptr_t)mp_obj_int_get_truncated(args[0]); o->desc = args[1]; o->flags = LAYOUT_NATIVE; if (n_args == 3) { @@ -125,8 +125,12 @@ STATIC void uctypes_struct_print(const mp_print_t *print, mp_obj_t self_in, mp_p mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(t->items[0]); uint agg_type = GET_TYPE(offset, AGG_TYPE_BITS); switch (agg_type) { - case PTR: typen = "PTR"; break; - case ARRAY: typen = "ARRAY"; break; + case PTR: + typen = "PTR"; + break; + case ARRAY: + typen = "ARRAY"; + break; } } else { typen = "ERROR"; @@ -157,10 +161,10 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_ case STRUCT: return uctypes_struct_size(t->items[1], layout_type, max_field_size); case PTR: - if (sizeof(void*) > *max_field_size) { - *max_field_size = sizeof(void*); + if (sizeof(void *) > *max_field_size) { + *max_field_size = sizeof(void *); } - return sizeof(void*); + return sizeof(void *); case ARRAY: { mp_int_t arr_sz = MP_OBJ_SMALL_INT_VALUE(t->items[1]); uint val_type = GET_TYPE(arr_sz, VAL_TYPE_BITS); @@ -189,7 +193,7 @@ STATIC mp_uint_t uctypes_struct_agg_size(mp_obj_tuple_t *t, int layout_type, mp_ STATIC mp_uint_t uctypes_struct_size(mp_obj_t desc_in, int layout_type, mp_uint_t *max_field_size) { if (!MP_OBJ_IS_TYPE(desc_in, &mp_type_dict)) { if (MP_OBJ_IS_TYPE(desc_in, &mp_type_tuple)) { - return uctypes_struct_agg_size((mp_obj_tuple_t*)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size); + return uctypes_struct_agg_size((mp_obj_tuple_t *)MP_OBJ_TO_PTR(desc_in), layout_type, max_field_size); } else if (MP_OBJ_IS_SMALL_INT(desc_in)) { // We allow sizeof on both type definitions and structures/structure fields, // but scalar structure field is lowered into native Python int, so all @@ -276,11 +280,11 @@ static inline void set_unaligned(uint val_type, byte *p, int big_endian, mp_obj_ static inline mp_uint_t get_aligned_basic(uint val_type, void *p) { switch (val_type) { case UINT8: - return *(uint8_t*)p; + return *(uint8_t *)p; case UINT16: - return *(uint16_t*)p; + return *(uint16_t *)p; case UINT32: - return *(uint32_t*)p; + return *(uint32_t *)p; } assert(0); return 0; @@ -289,11 +293,14 @@ static inline mp_uint_t get_aligned_basic(uint val_type, void *p) { static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) { switch (val_type) { case UINT8: - *(uint8_t*)p = (uint8_t)v; return; + *(uint8_t *)p = (uint8_t)v; + return; case UINT16: - *(uint16_t*)p = (uint16_t)v; return; + *(uint16_t *)p = (uint16_t)v; + return; case UINT32: - *(uint32_t*)p = (uint32_t)v; return; + *(uint32_t *)p = (uint32_t)v; + return; } assert(0); } @@ -301,26 +308,26 @@ static inline void set_aligned_basic(uint val_type, void *p, mp_uint_t v) { STATIC mp_obj_t get_aligned(uint val_type, void *p, mp_int_t index) { switch (val_type) { case UINT8: - return MP_OBJ_NEW_SMALL_INT(((uint8_t*)p)[index]); + return MP_OBJ_NEW_SMALL_INT(((uint8_t *)p)[index]); case INT8: - return MP_OBJ_NEW_SMALL_INT(((int8_t*)p)[index]); + return MP_OBJ_NEW_SMALL_INT(((int8_t *)p)[index]); case UINT16: - return MP_OBJ_NEW_SMALL_INT(((uint16_t*)p)[index]); + return MP_OBJ_NEW_SMALL_INT(((uint16_t *)p)[index]); case INT16: - return MP_OBJ_NEW_SMALL_INT(((int16_t*)p)[index]); + return MP_OBJ_NEW_SMALL_INT(((int16_t *)p)[index]); case UINT32: - return mp_obj_new_int_from_uint(((uint32_t*)p)[index]); + return mp_obj_new_int_from_uint(((uint32_t *)p)[index]); case INT32: - return mp_obj_new_int(((int32_t*)p)[index]); + return mp_obj_new_int(((int32_t *)p)[index]); case UINT64: - return mp_obj_new_int_from_ull(((uint64_t*)p)[index]); + return mp_obj_new_int_from_ull(((uint64_t *)p)[index]); case INT64: - return mp_obj_new_int_from_ll(((int64_t*)p)[index]); + return mp_obj_new_int_from_ll(((int64_t *)p)[index]); #if MICROPY_PY_BUILTINS_FLOAT case FLOAT32: - return mp_obj_new_float((mp_float_t)((float*)p)[index]); + return mp_obj_new_float((mp_float_t)((float *)p)[index]); case FLOAT64: - return mp_obj_new_float(((double*)p)[index]); + return mp_obj_new_float(((double *)p)[index]); #endif default: assert(0); @@ -333,9 +340,9 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { if (val_type == FLOAT32 || val_type == FLOAT64) { mp_float_t v = mp_obj_get_float(val); if (val_type == FLOAT32) { - ((float*)p)[index] = v; + ((float *)p)[index] = v; } else { - ((double*)p)[index] = v; + ((double *)p)[index] = v; } return; } @@ -343,21 +350,27 @@ STATIC void set_aligned(uint val_type, void *p, mp_int_t index, mp_obj_t val) { mp_int_t v = mp_obj_get_int_truncated(val); switch (val_type) { case UINT8: - ((uint8_t*)p)[index] = (uint8_t)v; return; + ((uint8_t *)p)[index] = (uint8_t)v; + return; case INT8: - ((int8_t*)p)[index] = (int8_t)v; return; + ((int8_t *)p)[index] = (int8_t)v; + return; case UINT16: - ((uint16_t*)p)[index] = (uint16_t)v; return; + ((uint16_t *)p)[index] = (uint16_t)v; + return; case INT16: - ((int16_t*)p)[index] = (int16_t)v; return; + ((int16_t *)p)[index] = (int16_t)v; + return; case UINT32: - ((uint32_t*)p)[index] = (uint32_t)v; return; + ((uint32_t *)p)[index] = (uint32_t)v; + return; case INT32: - ((int32_t*)p)[index] = (int32_t)v; return; + ((int32_t *)p)[index] = (int32_t)v; + return; case INT64: case UINT64: if (sizeof(mp_int_t) == 8) { - ((uint64_t*)p)[index] = (uint64_t)v; + ((uint64_t *)p)[index] = (uint64_t)v; } else { // TODO: Doesn't offer atomic store semantics, but should at least try set_unaligned(val_type, p, MP_ENDIANNESS_BIG, val); @@ -373,7 +386,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set // TODO: Support at least OrderedDict in addition if (!MP_OBJ_IS_TYPE(self->desc, &mp_type_dict)) { - mp_raise_TypeError(translate("struct: no fields")); + mp_raise_TypeError(translate("struct: no fields")); } mp_obj_t deref = mp_obj_dict_get(self->desc, MP_OBJ_NEW_QSTR(attr)); @@ -381,7 +394,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(deref); mp_uint_t val_type = GET_TYPE(offset, VAL_TYPE_BITS); offset &= VALUE_MASK(VAL_TYPE_BITS); -//printf("scalar type=%d offset=%x\n", val_type, offset); +// printf("scalar type=%d offset=%x\n", val_type, offset); if (val_type <= INT64 || val_type == FLOAT32 || val_type == FLOAT64) { // printf("size=%d\n", GET_SCALAR_SIZE(val_type)); @@ -451,7 +464,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set mp_int_t offset = MP_OBJ_SMALL_INT_VALUE(sub->items[0]); mp_uint_t agg_type = GET_TYPE(offset, AGG_TYPE_BITS); offset &= VALUE_MASK(AGG_TYPE_BITS); -//printf("agg type=%d offset=%x\n", agg_type, offset); +// printf("agg type=%d offset=%x\n", agg_type, offset); switch (agg_type) { case STRUCT: { @@ -475,7 +488,7 @@ STATIC mp_obj_t uctypes_struct_attr_op(mp_obj_t self_in, qstr attr, mp_obj_t set o->desc = MP_OBJ_FROM_PTR(sub); o->addr = self->addr + offset; o->flags = self->flags; -//printf("PTR/ARR base addr=%p\n", o->addr); +// printf("PTR/ARR base addr=%p\n", o->addr); return MP_OBJ_FROM_PTR(o); } } @@ -555,7 +568,7 @@ STATIC mp_obj_t uctypes_struct_subscr(mp_obj_t base_in, mp_obj_t index_in, mp_ob } } else if (agg_type == PTR) { - byte *p = *(void**)self->addr; + byte *p = *(void **)self->addr; if (MP_OBJ_IS_SMALL_INT(t->items[1])) { uint val_type = GET_TYPE(MP_OBJ_SMALL_INT_VALUE(t->items[1]), VAL_TYPE_BITS); return get_aligned(val_type, p, index); @@ -603,7 +616,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(uctypes_struct_addressof_obj, uctypes_struct_addressof /// captured by reference (and thus memory pointed by bytearray may change /// or become invalid at later time). Use bytes_at() to capture by value. STATIC mp_obj_t uctypes_struct_bytearray_at(mp_obj_t ptr, mp_obj_t size) { - return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr)); + return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void *)(uintptr_t)mp_obj_int_get_truncated(ptr)); } MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytearray_at); @@ -612,7 +625,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytearray_at_obj, uctypes_struct_bytear /// captured by value, i.e. copied. Use bytearray_at() to capture by reference /// ("zero copy"). STATIC mp_obj_t uctypes_struct_bytes_at(mp_obj_t ptr, mp_obj_t size) { - return mp_obj_new_bytes((void*)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size)); + return mp_obj_new_bytes((void *)(uintptr_t)mp_obj_int_get_truncated(ptr), mp_obj_int_get_truncated(size)); } MP_DEFINE_CONST_FUN_OBJ_2(uctypes_struct_bytes_at_obj, uctypes_struct_bytes_at); @@ -690,7 +703,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uctypes_globals, mp_module_uctypes_globals const mp_obj_module_t mp_module_uctypes = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uctypes_globals, + .globals = (mp_obj_dict_t *)&mp_module_uctypes_globals, }; #endif diff --git a/extmod/moduhashlib.c b/extmod/moduhashlib.c index 95485de138..e867aeb9ec 100644 --- a/extmod/moduhashlib.c +++ b/extmod/moduhashlib.c @@ -49,8 +49,8 @@ STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_arg mp_arg_check_num(n_args, kw_args, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha256_context)); o->base.type = type; - mbedtls_sha256_init((mbedtls_sha256_context*)&o->state); - mbedtls_sha256_starts((mbedtls_sha256_context*)&o->state, 0); + mbedtls_sha256_init((mbedtls_sha256_context *)&o->state); + mbedtls_sha256_starts((mbedtls_sha256_context *)&o->state, 0); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -61,7 +61,7 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_sha256_update((mbedtls_sha256_context*)&self->state, bufinfo.buf, bufinfo.len); + mbedtls_sha256_update((mbedtls_sha256_context *)&self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -69,25 +69,25 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 32); - mbedtls_sha256_finish((mbedtls_sha256_context*)&self->state, (unsigned char *)vstr.buf); + mbedtls_sha256_finish((mbedtls_sha256_context *)&self->state, (unsigned char *)vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #else static void check_not_unicode(const mp_obj_t arg) { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT if (MP_OBJ_IS_STR(arg)) { mp_raise_TypeError(translate("a bytes-like object is required")); } -#endif + #endif } STATIC mp_obj_t uhashlib_sha256_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { mp_arg_check_num(n_args, kw_args, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(CRYAL_SHA256_CTX)); o->base.type = type; - sha256_init((CRYAL_SHA256_CTX*)o->state); + sha256_init((CRYAL_SHA256_CTX *)o->state); if (n_args == 1) { uhashlib_sha256_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -99,7 +99,7 @@ STATIC mp_obj_t uhashlib_sha256_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - sha256_update((CRYAL_SHA256_CTX*)self->state, bufinfo.buf, bufinfo.len); + sha256_update((CRYAL_SHA256_CTX *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -107,7 +107,7 @@ STATIC mp_obj_t uhashlib_sha256_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, SHA256_BLOCK_SIZE); - sha256_final((CRYAL_SHA256_CTX*)self->state, (byte*)vstr.buf); + sha256_final((CRYAL_SHA256_CTX *)self->state, (byte *)vstr.buf); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif @@ -126,7 +126,7 @@ STATIC const mp_obj_type_t uhashlib_sha256_type = { { &mp_type_type }, .name = MP_QSTR_sha256, .make_new = uhashlib_sha256_make_new, - .locals_dict = (void*)&uhashlib_sha256_locals_dict, + .locals_dict = (void *)&uhashlib_sha256_locals_dict, }; #endif @@ -138,7 +138,7 @@ STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, mp_arg_check_num(n_args, kw_args, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(SHA1_CTX)); o->base.type = type; - SHA1_Init((SHA1_CTX*)o->state); + SHA1_Init((SHA1_CTX *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -150,7 +150,7 @@ STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - SHA1_Update((SHA1_CTX*)self->state, bufinfo.buf, bufinfo.len); + SHA1_Update((SHA1_CTX *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -158,7 +158,7 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, SHA1_SIZE); - SHA1_Final((byte*)vstr.buf, (SHA1_CTX*)self->state); + SHA1_Final((byte *)vstr.buf, (SHA1_CTX *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif @@ -168,8 +168,8 @@ STATIC mp_obj_t uhashlib_sha1_make_new(const mp_obj_type_t *type, size_t n_args, mp_arg_check_num(n_args, n_kw, 0, 1, false); mp_obj_hash_t *o = m_new_obj_var(mp_obj_hash_t, char, sizeof(mbedtls_sha1_context)); o->base.type = type; - mbedtls_sha1_init((mbedtls_sha1_context*)o->state); - mbedtls_sha1_starts((mbedtls_sha1_context*)o->state); + mbedtls_sha1_init((mbedtls_sha1_context *)o->state); + mbedtls_sha1_starts((mbedtls_sha1_context *)o->state); if (n_args == 1) { uhashlib_sha1_update(MP_OBJ_FROM_PTR(o), args[0]); } @@ -180,7 +180,7 @@ STATIC mp_obj_t uhashlib_sha1_update(mp_obj_t self_in, mp_obj_t arg) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - mbedtls_sha1_update((mbedtls_sha1_context*)self->state, bufinfo.buf, bufinfo.len); + mbedtls_sha1_update((mbedtls_sha1_context *)self->state, bufinfo.buf, bufinfo.len); return mp_const_none; } @@ -188,8 +188,8 @@ STATIC mp_obj_t uhashlib_sha1_digest(mp_obj_t self_in) { mp_obj_hash_t *self = MP_OBJ_TO_PTR(self_in); vstr_t vstr; vstr_init_len(&vstr, 20); - mbedtls_sha1_finish((mbedtls_sha1_context*)self->state, (byte*)vstr.buf); - mbedtls_sha1_free((mbedtls_sha1_context*)self->state); + mbedtls_sha1_finish((mbedtls_sha1_context *)self->state, (byte *)vstr.buf); + mbedtls_sha1_free((mbedtls_sha1_context *)self->state); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); } #endif @@ -207,7 +207,7 @@ STATIC const mp_obj_type_t uhashlib_sha1_type = { { &mp_type_type }, .name = MP_QSTR_sha1, .make_new = uhashlib_sha1_make_new, - .locals_dict = (void*)&uhashlib_sha1_locals_dict, + .locals_dict = (void *)&uhashlib_sha1_locals_dict, }; #endif @@ -225,11 +225,11 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uhashlib_globals, mp_module_uhashlib_globa const mp_obj_module_t mp_module_uhashlib = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uhashlib_globals, + .globals = (mp_obj_dict_t *)&mp_module_uhashlib_globals, }; #if MICROPY_PY_UHASHLIB_SHA256 #include "crypto-algorithms/sha256.c" #endif -#endif //MICROPY_PY_UHASHLIB +#endif // MICROPY_PY_UHASHLIB diff --git a/extmod/moduheapq.c b/extmod/moduheapq.c index 50fe6c0513..9e02d367a2 100644 --- a/extmod/moduheapq.c +++ b/extmod/moduheapq.c @@ -95,7 +95,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uheapq_globals, mp_module_uheapq_globals_t const mp_obj_module_t mp_module_uheapq = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uheapq_globals, + .globals = (mp_obj_dict_t *)&mp_module_uheapq_globals, }; -#endif //MICROPY_PY_UHEAPQ +#endif // MICROPY_PY_UHEAPQ diff --git a/extmod/modujson.c b/extmod/modujson.c index 3bb4b33017..63e8a011bf 100644 --- a/extmod/modujson.c +++ b/extmod/modujson.c @@ -85,8 +85,8 @@ STATIC byte ujson_stream_next(ujson_stream_t *s) { #define CIRCUITPY_JSON_READ_CHUNK_SIZE 64 STATIC mp_uint_t ujson_python_readinto(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode) { - (void) size; // Ignore size because we know it's always 1. - ujson_stream_t* s = obj; + (void)size; // Ignore size because we know it's always 1. + ujson_stream_t *s = obj; if (s->start == s->end) { *errcode = 0; @@ -99,7 +99,7 @@ STATIC mp_uint_t ujson_python_readinto(mp_obj_t obj, void *buf, mp_uint_t size, s->end = mp_obj_get_int(ret); } - *((uint8_t *)buf) = ((uint8_t*) s->bytearray_obj.items)[s->start]; + *((uint8_t *)buf) = ((uint8_t *)s->bytearray_obj.items)[s->start]; s->start++; return 1; } @@ -139,7 +139,7 @@ STATIC mp_obj_t _mod_ujson_load(mp_obj_t stream_obj, bool return_first_json) { mp_obj_t stack_key = MP_OBJ_NULL; S_NEXT(s); for (;;) { - cont: + cont: if (S_END(s)) { break; } @@ -186,11 +186,21 @@ STATIC mp_obj_t _mod_ujson_load(mp_obj_t stream_obj, bool return_first_json) { if (c == '\\') { c = S_NEXT(s); switch (c) { - case 'b': c = 0x08; break; - case 'f': c = 0x0c; break; - case 'n': c = 0x0a; break; - case 'r': c = 0x0d; break; - case 't': c = 0x09; break; + case 'b': + c = 0x08; + break; + case 'f': + c = 0x0c; + break; + case 'n': + c = 0x0a; + break; + case 'r': + c = 0x0d; + break; + case 't': + c = 0x09; + break; case 'u': { mp_uint_t num = 0; for (int i = 0; i < 4; i++) { @@ -216,7 +226,16 @@ STATIC mp_obj_t _mod_ujson_load(mp_obj_t stream_obj, bool return_first_json) { next = mp_obj_new_str(vstr.buf, vstr.len); break; case '-': - case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': { bool flt = false; vstr_reset(&vstr); for (;;) { @@ -298,7 +317,7 @@ STATIC mp_obj_t _mod_ujson_load(mp_obj_t stream_obj, bool return_first_json) { } } } - success: +success: // It is legal for a stream to have contents after JSON. // E.g., A UART is not closed after receiving an object; in load() we will // return the first complete JSON object, while in loads() we will retain @@ -319,7 +338,7 @@ STATIC mp_obj_t _mod_ujson_load(mp_obj_t stream_obj, bool return_first_json) { vstr_clear(&vstr); return stack_top; - fail: +fail: mp_raise_ValueError(translate("syntax error in JSON")); } @@ -331,18 +350,18 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_load_obj, mod_ujson_load); STATIC mp_obj_t mod_ujson_loads(mp_obj_t obj) { size_t len; const char *buf = mp_obj_str_get_data(obj, &len); - vstr_t vstr = {len, len, (char*)buf, true}; + vstr_t vstr = {len, len, (char *)buf, true}; mp_obj_stringio_t sio = {{&mp_type_stringio}, &vstr, 0, MP_OBJ_NULL}; return _mod_ujson_load(MP_OBJ_FROM_PTR(&sio), false); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_ujson_loads_obj, mod_ujson_loads); STATIC const mp_rom_map_elem_t mp_module_ujson_globals_table[] = { -#if CIRCUITPY + #if CIRCUITPY { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_json) }, -#else + #else { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ujson) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_dump), MP_ROM_PTR(&mod_ujson_dump_obj) }, { MP_ROM_QSTR(MP_QSTR_dumps), MP_ROM_PTR(&mod_ujson_dumps_obj) }, { MP_ROM_QSTR(MP_QSTR_load), MP_ROM_PTR(&mod_ujson_load_obj) }, @@ -353,7 +372,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ujson_globals, mp_module_ujson_globals_tab const mp_obj_module_t mp_module_ujson = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ujson_globals, + .globals = (mp_obj_dict_t *)&mp_module_ujson_globals, }; -#endif //MICROPY_PY_UJSON +#endif // MICROPY_PY_UJSON diff --git a/extmod/modurandom.c b/extmod/modurandom.c index a60250efc8..26e89f77f2 100644 --- a/extmod/modurandom.c +++ b/extmod/modurandom.c @@ -18,15 +18,14 @@ STATIC uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233; STATIC uint8_t yasmarang_dat = 0; -STATIC uint32_t yasmarang(void) -{ - yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n; - yasmarang_pad = (yasmarang_pad<<3) + (yasmarang_pad>>29); - yasmarang_n = yasmarang_pad | 2; - yasmarang_d ^= (yasmarang_pad<<31) + (yasmarang_pad>>1); - yasmarang_dat ^= (char) yasmarang_pad ^ (yasmarang_d>>8) ^ 1; +STATIC uint32_t yasmarang(void) { + yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n; + yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29); + yasmarang_n = yasmarang_pad | 2; + yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 1); + yasmarang_dat ^= (char)yasmarang_pad ^ (yasmarang_d >> 8) ^ 1; - return (yasmarang_pad^(yasmarang_d<<5)^(yasmarang_pad>>18)^(yasmarang_dat<<1)); + return yasmarang_pad ^ (yasmarang_d << 5) ^ (yasmarang_pad >> 18) ^ (yasmarang_dat << 1); } /* yasmarang */ // End of Yasmarang @@ -148,9 +147,11 @@ STATIC mp_float_t yasmarang_float(void) { union { mp_float_t f; #if MP_ENDIANNESS_LITTLE - struct { mp_float_int_t frc:MP_FLOAT_FRAC_BITS, exp:MP_FLOAT_EXP_BITS, sgn:1; } p; + struct { mp_float_int_t frc : MP_FLOAT_FRAC_BITS, exp : MP_FLOAT_EXP_BITS, sgn : 1; + } p; #else - struct { mp_float_int_t sgn:1, exp:MP_FLOAT_EXP_BITS, frc:MP_FLOAT_FRAC_BITS; } p; + struct { mp_float_int_t sgn : 1, exp : MP_FLOAT_EXP_BITS, frc : MP_FLOAT_FRAC_BITS; + } p; #endif } u; u.p.sgn = 0; @@ -198,7 +199,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_urandom_globals, mp_module_urandom_globals const mp_obj_module_t mp_module_urandom = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_urandom_globals, + .globals = (mp_obj_dict_t *)&mp_module_urandom_globals, }; -#endif //MICROPY_PY_URANDOM +#endif // MICROPY_PY_URANDOM diff --git a/extmod/modure.c b/extmod/modure.c index bb54bc732f..e9aff9b270 100644 --- a/extmod/modure.c +++ b/extmod/modure.c @@ -52,7 +52,7 @@ STATIC mp_obj_t match_group(mp_obj_t self_in, mp_obj_t no_in) { return mp_const_none; } return mp_obj_new_str_of_type(mp_obj_get_type(self->str), - (const byte*)start, self->caps[no * 2 + 1] - start); + (const byte *)start, self->caps[no * 2 + 1] - start); } MP_DEFINE_CONST_FUN_OBJ_2(match_group_obj, match_group); @@ -141,7 +141,7 @@ STATIC const mp_obj_type_t match_type = { { &mp_type_type }, .name = MP_QSTR_match, .print = match_print, - .locals_dict = (void*)&match_locals_dict, + .locals_dict = (void *)&match_locals_dict, }; STATIC void re_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { @@ -157,7 +157,7 @@ STATIC mp_obj_t ure_exec(bool is_anchored, uint n_args, const mp_obj_t *args) { size_t len; subj.begin = mp_obj_str_get_data(args[1], &len); subj.end = subj.begin + len; -#if MICROPY_PY_URE_MATCH_SPAN_START_END + #if MICROPY_PY_URE_MATCH_SPAN_START_END if (n_args > 2) { const mp_obj_type_t *self_type = mp_obj_get_type(args[1]); mp_int_t str_len = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(args[1])); @@ -185,14 +185,14 @@ STATIC mp_obj_t ure_exec(bool is_anchored, uint n_args, const mp_obj_t *args) { subj.begin = (const char *)pos_ptr; subj.end = (const char *)endpos_ptr; } -#endif + #endif int caps_num = (self->re.sub + 1) * 2; - mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char*, caps_num); + mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, char *, caps_num); // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char - memset((char*)match->caps, 0, caps_num * sizeof(char*)); + memset((char *)match->caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, is_anchored); if (res == 0) { - m_del_var(mp_obj_match_t, char*, caps_num, match); + m_del_var(mp_obj_match_t, char *, caps_num, match); return mp_const_none; } @@ -227,10 +227,10 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { } mp_obj_t retval = mp_obj_new_list(0, NULL); - const char **caps = mp_local_alloc(caps_num * sizeof(char*)); + const char **caps = mp_local_alloc(caps_num * sizeof(char *)); while (true) { // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char - memset((char**)caps, 0, caps_num * sizeof(char*)); + memset((char **)caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, caps, caps_num, false); // if we didn't have a match, or had an empty match, it's time to stop @@ -238,7 +238,7 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { break; } - mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, caps[0] - subj.begin); + mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, caps[0] - subj.begin); mp_obj_list_append(retval, s); if (self->re.sub > 0) { mp_raise_NotImplementedError(translate("Splitting with sub-captures")); @@ -249,9 +249,9 @@ STATIC mp_obj_t re_split(size_t n_args, const mp_obj_t *args) { } } // cast is a workaround for a bug in msvc (see above) - mp_local_free((char**)caps); + mp_local_free((char **)caps); - mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte*)subj.begin, subj.end - subj.begin); + mp_obj_t s = mp_obj_new_str_of_type(str_type, (const byte *)subj.begin, subj.end - subj.begin); mp_obj_list_append(retval, s); return retval; } @@ -278,14 +278,14 @@ STATIC mp_obj_t re_sub_helper(mp_obj_t self_in, size_t n_args, const mp_obj_t *a vstr_t vstr_return; vstr_return.buf = NULL; // We'll init the vstr after the first match - mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char*)); + mp_obj_match_t *match = mp_local_alloc(sizeof(mp_obj_match_t) + caps_num * sizeof(char *)); match->base.type = &match_type; match->num_matches = caps_num / 2; // caps_num counts start and end pointers match->str = where; for (;;) { // cast is a workaround for a bug in msvc: it treats const char** as a const pointer instead of a pointer to pointer to const char - memset((char*)match->caps, 0, caps_num * sizeof(char*)); + memset((char *)match->caps, 0, caps_num * sizeof(char *)); int res = re1_5_recursiveloopprog(&self->re, &subj, match->caps, caps_num, false); // If we didn't have a match, or had an empty match, it's time to stop @@ -302,7 +302,7 @@ STATIC mp_obj_t re_sub_helper(mp_obj_t self_in, size_t n_args, const mp_obj_t *a vstr_add_strn(&vstr_return, subj.begin, match->caps[0] - subj.begin); // Get replacement string - const char* repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace)); + const char *repl = mp_obj_str_get_str((mp_obj_is_callable(replace) ? mp_call_function_1(replace, MP_OBJ_FROM_PTR(match)) : replace)); // Append replacement string to result, substituting any regex groups while (*repl != '\0') { @@ -384,13 +384,13 @@ STATIC MP_DEFINE_CONST_DICT(re_locals_dict, re_locals_dict_table); STATIC const mp_obj_type_t re_type = { { &mp_type_type }, -#if CIRCUITPY + #if CIRCUITPY .name = MP_QSTR_re, -#else + #else .name = MP_QSTR_ure, -#endif + #endif .print = re_print, - .locals_dict = (void*)&re_locals_dict, + .locals_dict = (void *)&re_locals_dict, }; STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) { @@ -407,7 +407,7 @@ STATIC mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) { } int error = re1_5_compilecode(&o->re, re_str); if (error != 0) { -error: + error: mp_raise_ValueError(translate("Error in regex")); } if (flags & FLAG_DEBUG) { @@ -445,11 +445,11 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_re_sub_obj, 3, 5, mod_re_sub); #endif STATIC const mp_rom_map_elem_t mp_module_re_globals_table[] = { -#if CIRCUITPY + #if CIRCUITPY { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_re) }, -#else + #else { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_ure) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_compile), MP_ROM_PTR(&mod_re_compile_obj) }, { MP_ROM_QSTR(MP_QSTR_match), MP_ROM_PTR(&mod_re_match_obj) }, { MP_ROM_QSTR(MP_QSTR_search), MP_ROM_PTR(&mod_re_search_obj) }, @@ -463,7 +463,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_re_globals, mp_module_re_globals_table); const mp_obj_module_t mp_module_ure = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_re_globals, + .globals = (mp_obj_dict_t *)&mp_module_re_globals, }; // Source files #include'd here to make sure they're compiled in @@ -475,4 +475,4 @@ const mp_obj_module_t mp_module_ure = { #include "re1.5/recursiveloop.c" #include "re1.5/charclass.c" -#endif //MICROPY_PY_URE +#endif // MICROPY_PY_URE diff --git a/extmod/moduselect.c b/extmod/moduselect.c index 97b14a5f25..bcdb45bd6d 100644 --- a/extmod/moduselect.c +++ b/extmod/moduselect.c @@ -45,9 +45,9 @@ STATIC void poll_map_add(mp_map_t *poll_map, const mp_obj_t *obj, mp_uint_t obj_ } else { // object exists; update its flags if (or_flags) { - ((poll_obj_t*)elem->value)->flags |= flags; + ((poll_obj_t *)elem->value)->flags |= flags; } else { - ((poll_obj_t*)elem->value)->flags = flags; + ((poll_obj_t *)elem->value)->flags = flags; } } } @@ -61,7 +61,7 @@ STATIC mp_uint_t poll_map_poll(mp_map_t *poll_map, mp_uint_t *rwx_num) { continue; } - poll_obj_t *poll_obj = (poll_obj_t*)poll_map->table[i].value; + poll_obj_t *poll_obj = (poll_obj_t *)poll_map->table[i].value; int errcode; mp_int_t ret = poll_obj->ioctl(poll_obj->obj, MP_STREAM_POLL, poll_obj->flags, &errcode); poll_obj->flags_ret = ret; @@ -138,15 +138,15 @@ STATIC mp_obj_t select_select(uint n_args, const mp_obj_t *args) { if (!MP_MAP_SLOT_IS_FILLED(&poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t*)poll_map.table[i].value; + poll_obj_t *poll_obj = (poll_obj_t *)poll_map.table[i].value; if (poll_obj->flags_ret & MP_STREAM_POLL_RD) { - ((mp_obj_list_t*)list_array[0])->items[rwx_len[0]++] = poll_obj->obj; + ((mp_obj_list_t *)list_array[0])->items[rwx_len[0]++] = poll_obj->obj; } if (poll_obj->flags_ret & MP_STREAM_POLL_WR) { - ((mp_obj_list_t*)list_array[1])->items[rwx_len[1]++] = poll_obj->obj; + ((mp_obj_list_t *)list_array[1])->items[rwx_len[1]++] = poll_obj->obj; } if ((poll_obj->flags_ret & ~(MP_STREAM_POLL_RD | MP_STREAM_POLL_WR)) != 0) { - ((mp_obj_list_t*)list_array[2])->items[rwx_len[2]++] = poll_obj->obj; + ((mp_obj_list_t *)list_array[2])->items[rwx_len[2]++] = poll_obj->obj; } } mp_map_deinit(&poll_map); @@ -199,7 +199,7 @@ STATIC mp_obj_t poll_modify(mp_obj_t self_in, mp_obj_t obj_in, mp_obj_t eventmas if (elem == NULL) { mp_raise_OSError(MP_ENOENT); } - ((poll_obj_t*)elem->value)->flags = mp_obj_get_int(eventmask_in); + ((poll_obj_t *)elem->value)->flags = mp_obj_get_int(eventmask_in); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_3(poll_modify_obj, poll_modify); @@ -249,7 +249,7 @@ STATIC mp_obj_t poll_poll(uint n_args, const mp_obj_t *args) { if (!MP_MAP_SLOT_IS_FILLED(&self->poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t*)self->poll_map.table[i].value; + poll_obj_t *poll_obj = (poll_obj_t *)self->poll_map.table[i].value; if (poll_obj->flags_ret != 0) { mp_obj_t tuple[2] = {poll_obj->obj, MP_OBJ_NEW_SMALL_INT(poll_obj->flags_ret)}; ret_list->items[n_ready++] = mp_obj_new_tuple(2, tuple); @@ -292,7 +292,7 @@ STATIC mp_obj_t poll_iternext(mp_obj_t self_in) { if (!MP_MAP_SLOT_IS_FILLED(&self->poll_map, i)) { continue; } - poll_obj_t *poll_obj = (poll_obj_t*)self->poll_map.table[i].value; + poll_obj_t *poll_obj = (poll_obj_t *)self->poll_map.table[i].value; if (poll_obj->flags_ret != 0) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(self->ret_tuple); t->items[0] = poll_obj->obj; @@ -324,7 +324,7 @@ STATIC const mp_obj_type_t mp_type_poll = { .name = MP_QSTR_poll, .getiter = mp_identity_getiter, .iternext = poll_iternext, - .locals_dict = (void*)&poll_locals_dict, + .locals_dict = (void *)&poll_locals_dict, }; /// \function poll() @@ -352,7 +352,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_select_globals, mp_module_select_globals_t const mp_obj_module_t mp_module_uselect = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_select_globals, + .globals = (mp_obj_dict_t *)&mp_module_select_globals, }; #endif // MICROPY_PY_USELECT diff --git a/extmod/modussl_axtls.c b/extmod/modussl_axtls.c index 7cc2bb3e25..757210871b 100644 --- a/extmod/modussl_axtls.c +++ b/extmod/modussl_axtls.c @@ -34,11 +34,11 @@ struct ssl_args { STATIC const mp_obj_type_t ussl_socket_type; STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { -#if MICROPY_PY_USSL_FINALISER + #if MICROPY_PY_USSL_FINALISER mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t); -#else + #else mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t); -#endif + #endif o->base.type = &ussl_socket_type; o->buf = NULL; o->bytes_left = 0; @@ -54,13 +54,13 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { if (args->key.u_obj != mp_const_none) { size_t len; - const byte *data = (const byte*)mp_obj_str_get_data(args->key.u_obj, &len); + const byte *data = (const byte *)mp_obj_str_get_data(args->key.u_obj, &len); int res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_RSA_KEY, data, len, NULL); if (res != SSL_OK) { mp_raise_ValueError(translate("invalid key")); } - data = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &len); + data = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &len); res = ssl_obj_memory_load(o->ssl_ctx, SSL_OBJ_X509_CERT, data, len, NULL); if (res != SSL_OK) { mp_raise_ValueError(translate("invalid cert")); @@ -73,7 +73,7 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { SSL_EXTENSIONS *ext = ssl_ext_new(); if (args->server_hostname.u_obj != mp_const_none) { - ext->host_name = (char*)mp_obj_str_get_str(args->server_hostname.u_obj); + ext->host_name = (char *)mp_obj_str_get_str(args->server_hostname.u_obj); } o->ssl_sock = ssl_client_new(o->ssl_ctx, (long)sock, NULL, 0, ext); @@ -192,9 +192,9 @@ STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, -#if MICROPY_PY_USSL_FINALISER + #if MICROPY_PY_USSL_FINALISER { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(ussl_socket_locals_dict, ussl_socket_locals_dict_table); @@ -214,7 +214,7 @@ STATIC const mp_obj_type_t ussl_socket_type = { .getiter = NULL, .iternext = NULL, .protocol = &ussl_socket_stream_p, - .locals_dict = (void*)&ussl_socket_locals_dict, + .locals_dict = (void *)&ussl_socket_locals_dict, }; STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -231,7 +231,7 @@ STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_ struct ssl_args args; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, - MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args); + MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); return MP_OBJ_FROM_PTR(socket_new(sock, &args)); } @@ -246,7 +246,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table); const mp_obj_module_t mp_module_ussl = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ssl_globals, + .globals = (mp_obj_dict_t *)&mp_module_ssl_globals, }; #endif // MICROPY_PY_USSL diff --git a/extmod/modussl_mbedtls.c b/extmod/modussl_mbedtls.c index 990523173d..830d6359aa 100644 --- a/extmod/modussl_mbedtls.c +++ b/extmod/modussl_mbedtls.c @@ -53,7 +53,7 @@ STATIC void mbedtls_debug(void *ctx, int level, const char *file, int line, cons #endif STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) { - mp_obj_t sock = *(mp_obj_t*)ctx; + mp_obj_t sock = *(mp_obj_t *)ctx; const mp_stream_p_t *sock_stream = mp_get_stream(sock); int err; @@ -70,7 +70,7 @@ STATIC int _mbedtls_ssl_send(void *ctx, const byte *buf, size_t len) { } STATIC int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) { - mp_obj_t sock = *(mp_obj_t*)ctx; + mp_obj_t sock = *(mp_obj_t *)ctx; const mp_stream_p_t *sock_stream = mp_get_stream(sock); int err; @@ -91,11 +91,11 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { // Verify the socket object has the full stream protocol mp_get_stream_raise(sock, MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); -#if MICROPY_PY_USSL_FINALISER + #if MICROPY_PY_USSL_FINALISER mp_obj_ssl_socket_t *o = m_new_obj_with_finaliser(mp_obj_ssl_socket_t); -#else + #else mp_obj_ssl_socket_t *o = m_new_obj(mp_obj_ssl_socket_t); -#endif + #endif o->base.type = &ussl_socket_type; o->sock = sock; @@ -119,9 +119,9 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { } ret = mbedtls_ssl_config_defaults(&o->conf, - args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, - MBEDTLS_SSL_TRANSPORT_STREAM, - MBEDTLS_SSL_PRESET_DEFAULT); + args->server_side.u_bool ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, + MBEDTLS_SSL_TRANSPORT_STREAM, + MBEDTLS_SSL_PRESET_DEFAULT); if (ret != 0) { goto cleanup; } @@ -149,13 +149,13 @@ STATIC mp_obj_ssl_socket_t *socket_new(mp_obj_t sock, struct ssl_args *args) { if (args->key.u_obj != MP_OBJ_NULL) { size_t key_len; - const byte *key = (const byte*)mp_obj_str_get_data(args->key.u_obj, &key_len); + const byte *key = (const byte *)mp_obj_str_get_data(args->key.u_obj, &key_len); // len should include terminating null ret = mbedtls_pk_parse_key(&o->pkey, key, key_len + 1, NULL, 0); assert(ret == 0); size_t cert_len; - const byte *cert = (const byte*)mp_obj_str_get_data(args->cert.u_obj, &cert_len); + const byte *cert = (const byte *)mp_obj_str_get_data(args->cert.u_obj, &cert_len); // len should include terminating null ret = mbedtls_x509_crt_parse(&o->cert, cert, cert_len + 1); assert(ret == 0); @@ -194,7 +194,7 @@ STATIC mp_obj_t mod_ssl_getpeercert(mp_obj_t o_in, mp_obj_t binary_form) { if (!mp_obj_is_true(binary_form)) { mp_raise_NotImplementedError(NULL); } - const mbedtls_x509_crt* peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl); + const mbedtls_x509_crt *peer_cert = mbedtls_ssl_get_peer_cert(&o->ssl); return mp_obj_new_bytes(peer_cert->raw.p, peer_cert->raw.len); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(mod_ssl_getpeercert_obj, mod_ssl_getpeercert); @@ -275,9 +275,9 @@ STATIC const mp_rom_map_elem_t ussl_socket_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_setblocking), MP_ROM_PTR(&socket_setblocking_obj) }, { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, -#if MICROPY_PY_USSL_FINALISER + #if MICROPY_PY_USSL_FINALISER { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mp_stream_close_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_getpeercert), MP_ROM_PTR(&mod_ssl_getpeercert_obj) }, }; @@ -298,7 +298,7 @@ STATIC const mp_obj_type_t ussl_socket_type = { .getiter = NULL, .iternext = NULL, .protocol = &ussl_socket_stream_p, - .locals_dict = (void*)&ussl_socket_locals_dict, + .locals_dict = (void *)&ussl_socket_locals_dict, }; STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -315,7 +315,7 @@ STATIC mp_obj_t mod_ssl_wrap_socket(size_t n_args, const mp_obj_t *pos_args, mp_ struct ssl_args args; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, - MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args); + MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); return MP_OBJ_FROM_PTR(socket_new(sock, &args)); } @@ -330,7 +330,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ssl_globals, mp_module_ssl_globals_table); const mp_obj_module_t mp_module_ussl = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ssl_globals, + .globals = (mp_obj_dict_t *)&mp_module_ssl_globals, }; #endif // MICROPY_PY_USSL diff --git a/extmod/modutimeq.c b/extmod/modutimeq.c index bb2b6b335d..beeb4353d9 100644 --- a/extmod/modutimeq.c +++ b/extmod/modutimeq.c @@ -171,9 +171,12 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_utimeq_dump_obj, mod_utimeq_dump); STATIC mp_obj_t utimeq_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_utimeq_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(self->len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(self->len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -193,7 +196,7 @@ STATIC const mp_obj_type_t utimeq_type = { .name = MP_QSTR_utimeq, .make_new = utimeq_make_new, .unary_op = utimeq_unary_op, - .locals_dict = (void*)&utimeq_locals_dict, + .locals_dict = (void *)&utimeq_locals_dict, }; STATIC const mp_rom_map_elem_t mp_module_utimeq_globals_table[] = { @@ -205,7 +208,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_utimeq_globals, mp_module_utimeq_globals_t const mp_obj_module_t mp_module_utimeq = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_utimeq_globals, + .globals = (mp_obj_dict_t *)&mp_module_utimeq_globals, }; -#endif //MICROPY_PY_UTIMEQ +#endif // MICROPY_PY_UTIMEQ diff --git a/extmod/moduzlib.c b/extmod/moduzlib.c index b344f96429..9c80f16322 100644 --- a/extmod/moduzlib.c +++ b/extmod/moduzlib.c @@ -31,9 +31,9 @@ typedef struct _mp_obj_decompio_t { } mp_obj_decompio_t; STATIC int read_src_stream(TINF_DATA *data) { - byte *p = (void*)data; + byte *p = (void *)data; p -= offsetof(mp_obj_decompio_t, decomp); - mp_obj_decompio_t *self = (mp_obj_decompio_t*)p; + mp_obj_decompio_t *self = (mp_obj_decompio_t *)p; const mp_stream_p_t *stream = mp_get_stream(self->src_stream); int err; @@ -73,7 +73,7 @@ STATIC mp_obj_t decompio_make_new(const mp_obj_type_t *type, size_t n_args, cons } else if (dict_opt >= 0) { dict_opt = uzlib_zlib_parse_header(&o->decomp); if (dict_opt < 0) { -header_error: + header_error: mp_raise_ValueError(translate("compression header")); } dict_sz = 1 << dict_opt; @@ -92,7 +92,7 @@ STATIC mp_uint_t decompio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *er } o->decomp.dest = buf; - o->decomp.dest_limit = (unsigned char*)buf+size; + o->decomp.dest_limit = (unsigned char *)buf + size; int st = uzlib_uncompress_chksum(&o->decomp); if (st == TINF_DONE) { o->eof = true; @@ -101,7 +101,7 @@ STATIC mp_uint_t decompio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *er *errcode = MP_EINVAL; return MP_STREAM_ERROR; } - return o->decomp.dest - (byte*)buf; + return o->decomp.dest - (byte *)buf; } STATIC const mp_rom_map_elem_t decompio_locals_dict_table[] = { @@ -122,7 +122,7 @@ STATIC const mp_obj_type_t decompio_type = { .name = MP_QSTR_DecompIO, .make_new = decompio_make_new, .protocol = &decompio_stream_p, - .locals_dict = (void*)&decompio_locals_dict, + .locals_dict = (void *)&decompio_locals_dict, }; STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { @@ -138,7 +138,7 @@ STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { byte *dest_buf = m_new(byte, dest_buf_size); decomp->dest = dest_buf; - decomp->dest_limit = dest_buf+dest_buf_size; + decomp->dest_limit = dest_buf + dest_buf_size; DEBUG_printf("uzlib: Initial out buffer: " UINT_FMT " bytes\n", decomp->destSize); decomp->source = bufinfo.buf; decomp->source_limit = (unsigned char *)bufinfo.buf + bufinfo.len; @@ -173,7 +173,7 @@ STATIC mp_obj_t mod_uzlib_decompress(size_t n_args, const mp_obj_t *args) { mp_uint_t final_sz = decomp->dest - dest_buf; DEBUG_printf("uzlib: Resizing from " UINT_FMT " to final size: " UINT_FMT " bytes\n", dest_buf_size, final_sz); - dest_buf = (byte*)m_renew(byte, dest_buf, dest_buf_size, final_sz); + dest_buf = (byte *)m_renew(byte, dest_buf, dest_buf_size, final_sz); mp_obj_t res = mp_obj_new_bytearray_by_ref(final_sz, dest_buf); m_del_obj(TINF_DATA, decomp); return res; @@ -193,7 +193,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_uzlib_globals, mp_module_uzlib_globals_tab const mp_obj_module_t mp_module_uzlib = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uzlib_globals, + .globals = (mp_obj_dict_t *)&mp_module_uzlib_globals, }; // Source files #include'd here to make sure they're compiled in diff --git a/extmod/modwebrepl.c b/extmod/modwebrepl.c index 5b3c6150a7..f34e14caf5 100644 --- a/extmod/modwebrepl.c +++ b/extmod/modwebrepl.c @@ -127,7 +127,7 @@ STATIC void handle_op(mp_obj_webrepl_t *self) { open_args[1] = MP_OBJ_NEW_QSTR(MP_QSTR_wb); } - self->cur_file = mp_builtin_open(2, open_args, (mp_map_t*)&mp_const_empty_map); + self->cur_file = mp_builtin_open(2, open_args, (mp_map_t *)&mp_const_empty_map); #if 0 struct mp_stream_seek_t seek = { .offset = self->hdr.offset, .whence = 0 }; @@ -161,13 +161,13 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int mp_obj_webrepl_t *self = self_in; const mp_stream_p_t *sock_stream = mp_get_stream(self->sock); mp_uint_t out_sz = sock_stream->read(self->sock, buf, size, errcode); - //DEBUG_printf("webrepl: Read %d initial bytes from websocket\n", out_sz); + // DEBUG_printf("webrepl: Read %d initial bytes from websocket\n", out_sz); if (out_sz == 0 || out_sz == MP_STREAM_ERROR) { return out_sz; } if (self->state == STATE_PASSWD) { - char c = *(char*)buf; + char c = *(char *)buf; if (c == '\r' || c == '\n') { self->hdr.fname[self->data_to_recv] = 0; DEBUG_printf("webrepl: entered password: %s\n", self->hdr.fname); @@ -195,8 +195,8 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int DEBUG_printf("webrepl: received bin data, hdr_to_recv: %d, data_to_recv=%d\n", self->hdr_to_recv, self->data_to_recv); if (self->hdr_to_recv != 0) { - char *p = (char*)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv; - *p++ = *(char*)buf; + char *p = (char *)&self->hdr + sizeof(self->hdr) - self->hdr_to_recv; + *p++ = *(char *)buf; if (--self->hdr_to_recv != 0) { mp_uint_t hdr_sz = sock_stream->read(self->sock, p, self->hdr_to_recv, errcode); if (hdr_sz == MP_STREAM_ERROR) { @@ -217,7 +217,7 @@ STATIC mp_uint_t _webrepl_read(mp_obj_t self_in, void *buf, mp_uint_t size, int if (self->data_to_recv != 0) { static byte filebuf[512]; - filebuf[0] = *(byte*)buf; + filebuf[0] = *(byte *)buf; mp_uint_t buf_sz = 1; if (--self->data_to_recv != 0) { size_t to_read = MIN(sizeof(filebuf) - 1, self->data_to_recv); @@ -321,7 +321,7 @@ STATIC const mp_obj_type_t webrepl_type = { .name = MP_QSTR__webrepl, .make_new = webrepl_make_new, .protocol = &webrepl_stream_p, - .locals_dict = (mp_obj_dict_t*)&webrepl_locals_dict, + .locals_dict = (mp_obj_dict_t *)&webrepl_locals_dict, }; STATIC const mp_rom_map_elem_t webrepl_module_globals_table[] = { @@ -334,7 +334,7 @@ STATIC MP_DEFINE_CONST_DICT(webrepl_module_globals, webrepl_module_globals_table const mp_obj_module_t mp_module_webrepl = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&webrepl_module_globals, + .globals = (mp_obj_dict_t *)&webrepl_module_globals, }; #endif // MICROPY_PY_WEBREPL diff --git a/extmod/modwebsocket.c b/extmod/modwebsocket.c index 581af6b588..6547ebee44 100644 --- a/extmod/modwebsocket.c +++ b/extmod/modwebsocket.c @@ -50,11 +50,11 @@ STATIC mp_obj_t websocket_make_new(const mp_obj_type_t *type, size_t n_args, con if (n_args > 1 && args[1] == mp_const_true) { o->opts |= BLOCKING_WRITE; } - return MP_OBJ_FROM_PTR(o); + return MP_OBJ_FROM_PTR(o); } STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { - mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); const mp_stream_p_t *stream_p = mp_get_stream(self->sock); while (1) { if (self->to_recv != 0) { @@ -162,7 +162,7 @@ STATIC mp_uint_t websocket_read(mp_obj_t self_in, void *buf, mp_uint_t size, int self->msg_sz -= out_sz; if (self->msg_sz == 0) { byte last_state; -no_payload: + no_payload: last_state = self->state; self->state = FRAME_HEADER; self->to_recv = 2; @@ -179,7 +179,7 @@ no_payload: return 0; } - //DEBUG_printf("Finished receiving ctrl message %x, ignoring\n", self->last_flags); + // DEBUG_printf("Finished receiving ctrl message %x, ignoring\n", self->last_flags); continue; } } @@ -196,7 +196,7 @@ no_payload: } STATIC mp_uint_t websocket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, int *errcode) { - mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_websocket_t *self = MP_OBJ_TO_PTR(self_in); assert(size < 0x10000); byte header[4] = {0x80 | (self->opts & FRAME_OPCODE_MASK)}; int hdr_sz; @@ -276,7 +276,7 @@ STATIC const mp_obj_type_t websocket_type = { .name = MP_QSTR_websocket, .make_new = websocket_make_new, .protocol = &websocket_stream_p, - .locals_dict = (void*)&websocket_locals_dict, + .locals_dict = (void *)&websocket_locals_dict, }; STATIC const mp_rom_map_elem_t websocket_module_globals_table[] = { @@ -288,7 +288,7 @@ STATIC MP_DEFINE_CONST_DICT(websocket_module_globals, websocket_module_globals_t const mp_obj_module_t mp_module_websocket = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&websocket_module_globals, + .globals = (mp_obj_dict_t *)&websocket_module_globals, }; #endif // MICROPY_PY_WEBSOCKET diff --git a/extmod/utime_mphal.c b/extmod/utime_mphal.c index ebbc9ac263..a21f2f7fc5 100644 --- a/extmod/utime_mphal.c +++ b/extmod/utime_mphal.c @@ -65,7 +65,7 @@ STATIC mp_obj_t time_ticks_diff(mp_obj_t end_in, mp_obj_t start_in) { // Optimized formula avoiding if conditions. We adjust difference "forward", // wrap it around and adjust back. mp_int_t diff = ((end - start + MICROPY_PY_UTIME_TICKS_PERIOD / 2) & (MICROPY_PY_UTIME_TICKS_PERIOD - 1)) - - MICROPY_PY_UTIME_TICKS_PERIOD / 2; + - MICROPY_PY_UTIME_TICKS_PERIOD / 2; return MP_OBJ_NEW_SMALL_INT(diff); } MP_DEFINE_CONST_FUN_OBJ_2(mp_utime_ticks_diff_obj, time_ticks_diff); diff --git a/extmod/vfs.c b/extmod/vfs.c index 420f8305f7..b20b251938 100644 --- a/extmod/vfs.c +++ b/extmod/vfs.c @@ -75,7 +75,7 @@ STATIC mp_vfs_mount_t *lookup_path(mp_obj_t path_in, mp_obj_t *path_out) { mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &p_out); if (vfs != MP_VFS_NONE && vfs != MP_VFS_ROOT) { *path_out = mp_obj_new_str_of_type(mp_obj_get_type(path_in), - (const byte*)p_out, strlen(p_out)); + (const byte *)p_out, strlen(p_out)); } return vfs; } @@ -106,7 +106,7 @@ mp_import_stat_t mp_vfs_import_stat(const char *path) { } // If the mounted object has the VFS protocol, call its import_stat helper - const mp_vfs_proto_t *proto = (mp_vfs_proto_t*)mp_proto_get(MP_QSTR_protocol_vfs, vfs->obj); + const mp_vfs_proto_t *proto = (mp_vfs_proto_t *)mp_proto_get(MP_QSTR_protocol_vfs, vfs->obj); if (proto != NULL) { return proto->import_stat(MP_OBJ_TO_PTR(vfs->obj), path_out); } @@ -168,7 +168,7 @@ mp_obj_t mp_vfs_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args vfs->next = NULL; // call the underlying object to do any mounting operation - mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t*)&args); + mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t *)&args); // check that the destination mount point is unused const char *path_out; @@ -245,7 +245,7 @@ mp_obj_t mp_vfs_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); mp_vfs_mount_t *vfs = lookup_path(args[ARG_file].u_obj, &args[ARG_file].u_obj); - return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t*)&args); + return mp_vfs_proxy_call(vfs, MP_QSTR_open, 2, (mp_obj_t *)&args); } MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_open_obj, 0, mp_vfs_open); @@ -314,7 +314,7 @@ mp_obj_t mp_vfs_ilistdir_it_iternext(mp_obj_t self_in) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); t->items[0] = mp_obj_new_str_of_type( self->is_str ? &mp_type_str : &mp_type_bytes, - (const byte*)vfs->str + 1, vfs->len - 1); + (const byte *)vfs->str + 1, vfs->len - 1); t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number return MP_OBJ_FROM_PTR(t); diff --git a/extmod/vfs.h b/extmod/vfs.h index 85958d80d9..c08c0912c3 100644 --- a/extmod/vfs.h +++ b/extmod/vfs.h @@ -12,8 +12,8 @@ // return values of mp_vfs_lookup_path // ROOT is 0 so that the default current directory is the root directory -#define MP_VFS_NONE ((mp_vfs_mount_t*)1) -#define MP_VFS_ROOT ((mp_vfs_mount_t*)0) +#define MP_VFS_NONE ((mp_vfs_mount_t *)1) +#define MP_VFS_ROOT ((mp_vfs_mount_t *)0) // MicroPython's port-standardized versions of stat constants #define MP_S_IFDIR (0x4000) diff --git a/extmod/vfs_fat.c b/extmod/vfs_fat.c index b8f43ee295..5da4ecd872 100644 --- a/extmod/vfs_fat.c +++ b/extmod/vfs_fat.c @@ -136,7 +136,7 @@ STATIC mp_obj_t mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in) { if (self->is_str) { t->items[0] = mp_obj_new_str(fn, strlen(fn)); } else { - t->items[0] = mp_obj_new_bytes((const byte*)fn, strlen(fn)); + t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); } if (fno.fattrib & AM_DIR) { // dir @@ -234,9 +234,9 @@ STATIC mp_obj_t fat_vfs_rename(mp_obj_t vfs_in, mp_obj_t path_in, mp_obj_t path_ mp_raise_OSError(fresult_to_errno_table[res]); } if ((fno.fattrib & AM_DIR) != 0 && - strlen(new_path) > strlen(old_path) && - new_path[strlen(old_path)] == '/' && - strncmp(old_path, new_path, strlen(old_path)) == 0) { + strlen(new_path) > strlen(old_path) && + new_path[strlen(old_path)] == '/' && + strncmp(old_path, new_path, strlen(old_path)) == 0) { mp_raise_OSError(MP_EINVAL); } @@ -324,11 +324,11 @@ STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) { } else { mode |= MP_S_IFREG; } -#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE + #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE // On non-longint builds, the number of seconds since 1970 (epoch) is too // large to fit in a smallint, so just return 31-DEC-1999 (0). mp_obj_t seconds = MP_OBJ_NEW_SMALL_INT(946684800); -#else + #else mp_obj_t seconds = mp_obj_new_int_from_uint( timeutils_seconds_since_epoch( 1980 + ((fno.fdate >> 9) & 0x7f), @@ -338,7 +338,7 @@ STATIC mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) { (fno.ftime >> 5) & 0x3f, 2 * (fno.ftime & 0x1f) )); -#endif + #endif t->items[0] = MP_OBJ_NEW_SMALL_INT(mode); // st_mode t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev @@ -434,7 +434,7 @@ STATIC mp_obj_t vfs_fat_setlabel(mp_obj_t self_in, mp_obj_t label_in) { const char *label_str = mp_obj_str_get_str(label_in); FRESULT res = f_setlabel(&self->fatfs, label_str); if (res != FR_OK) { - if(res == FR_WRITE_PROTECTED) { + if (res == FR_WRITE_PROTECTED) { mp_raise_msg(&mp_type_OSError, translate("Read-only filesystem")); } mp_raise_OSError(fresult_to_errno_table[res]); @@ -467,9 +467,9 @@ STATIC const mp_rom_map_elem_t fat_vfs_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&fat_vfs_statvfs_obj) }, { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&vfs_fat_mount_obj) }, { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&fat_vfs_umount_obj) }, -#if MICROPY_FATFS_USE_LABEL + #if MICROPY_FATFS_USE_LABEL { MP_ROM_QSTR(MP_QSTR_label), MP_ROM_PTR(&fat_vfs_label_obj) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(fat_vfs_locals_dict, fat_vfs_locals_dict_table); @@ -483,7 +483,7 @@ const mp_obj_type_t mp_fat_vfs_type = { .name = MP_QSTR_VfsFat, .make_new = fat_vfs_make_new, .protocol = &fat_vfs_proto, - .locals_dict = (mp_obj_dict_t*)&fat_vfs_locals_dict, + .locals_dict = (mp_obj_dict_t *)&fat_vfs_locals_dict, }; diff --git a/extmod/vfs_fat_diskio.c b/extmod/vfs_fat_diskio.c index 127b77d7dd..b3054ef2c6 100644 --- a/extmod/vfs_fat_diskio.c +++ b/extmod/vfs_fat_diskio.c @@ -26,32 +26,31 @@ typedef void *bdev_t; STATIC fs_user_mount_t *disk_get_device(void *bdev) { - return (fs_user_mount_t*)bdev; + return (fs_user_mount_t *)bdev; } /*-----------------------------------------------------------------------*/ /* Read Sector(s) */ /*-----------------------------------------------------------------------*/ -DRESULT disk_read ( +DRESULT disk_read( bdev_t pdrv, /* Physical drive */ BYTE *buff, /* Data buffer to store read data */ DWORD sector, /* Sector address (LBA) */ UINT count /* Number of sectors to read (1..128) */ -) -{ + ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; } if (vfs->flags & FSUSER_NATIVE) { - mp_uint_t (*f)(uint8_t*, uint32_t, uint32_t) = (void*)(uintptr_t)vfs->readblocks[2]; + mp_uint_t (*f)(uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)vfs->readblocks[2]; if (f(buff, sector, count) != 0) { return RES_ERROR; } } else { - mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, count * SECSIZE(&vfs->fatfs), buff}; + mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, count *SECSIZE(&vfs->fatfs), buff}; vfs->readblocks[2] = MP_OBJ_NEW_SMALL_INT(sector); vfs->readblocks[3] = MP_OBJ_FROM_PTR(&ar); nlr_buf_t nlr; @@ -74,13 +73,12 @@ DRESULT disk_read ( /* Write Sector(s) */ /*-----------------------------------------------------------------------*/ -DRESULT disk_write ( +DRESULT disk_write( bdev_t pdrv, /* Physical drive */ const BYTE *buff, /* Data to be written */ DWORD sector, /* Sector address (LBA) */ UINT count /* Number of sectors to write (1..128) */ -) -{ + ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; @@ -92,12 +90,12 @@ DRESULT disk_write ( } if (vfs->flags & FSUSER_NATIVE) { - mp_uint_t (*f)(const uint8_t*, uint32_t, uint32_t) = (void*)(uintptr_t)vfs->writeblocks[2]; + mp_uint_t (*f)(const uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)vfs->writeblocks[2]; if (f(buff, sector, count) != 0) { return RES_ERROR; } } else { - mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, count * SECSIZE(&vfs->fatfs), (void*)buff}; + mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, count *SECSIZE(&vfs->fatfs), (void *)buff}; vfs->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(sector); vfs->writeblocks[3] = MP_OBJ_FROM_PTR(&ar); nlr_buf_t nlr; @@ -121,12 +119,11 @@ DRESULT disk_write ( /* Miscellaneous Functions */ /*-----------------------------------------------------------------------*/ -DRESULT disk_ioctl ( +DRESULT disk_ioctl( bdev_t pdrv, /* Physical drive */ BYTE cmd, /* Control code */ void *buff /* Buffer to send/receive control data */ -) -{ + ) { fs_user_mount_t *vfs = disk_get_device(pdrv); if (vfs == NULL) { return RES_PARERR; @@ -145,8 +142,8 @@ DRESULT disk_ioctl ( uint8_t bp_op = op_map[cmd & 7]; if (bp_op != 0) { if (vfs->flags & FSUSER_NATIVE) { - bool (*f)(size_t, mp_int_t*) = (void*)(uintptr_t)vfs->u.ioctl[2]; - if (!f(bp_op, (mp_int_t*) &out_value)) { + bool (*f)(size_t, mp_int_t *) = (void *)(uintptr_t)vfs->u.ioctl[2]; + if (!f(bp_op, (mp_int_t *)&out_value)) { return RES_ERROR; } } else { @@ -190,26 +187,26 @@ DRESULT disk_ioctl ( return RES_OK; case GET_SECTOR_COUNT: { - *((DWORD*)buff) = out_value; + *((DWORD *)buff) = out_value; return RES_OK; } case GET_SECTOR_SIZE: { if (out_value == 0) { // Default sector size - *((WORD*)buff) = 512; + *((WORD *)buff) = 512; } else { - *((WORD*)buff) = out_value; + *((WORD *)buff) = out_value; } #if _MAX_SS != _MIN_SS // need to store ssize because we use it in disk_read/disk_write - vfs->fatfs.ssize = *((WORD*)buff); + vfs->fatfs.ssize = *((WORD *)buff); #endif return RES_OK; } case GET_BLOCK_SIZE: - *((DWORD*)buff) = 1; // erase block size in units of sector size + *((DWORD *)buff) = 1; // erase block size in units of sector size return RES_OK; case IOCTL_INIT: @@ -223,7 +220,7 @@ DRESULT disk_ioctl ( } else { stat = 0; } - *((DSTATUS*)buff) = stat; + *((DSTATUS *)buff) = stat; return RES_OK; } diff --git a/extmod/vfs_fat_file.c b/extmod/vfs_fat_file.c index 89786bfa36..cbcffe11a5 100644 --- a/extmod/vfs_fat_file.c +++ b/extmod/vfs_fat_file.c @@ -83,7 +83,7 @@ STATIC mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, pyb_file_obj_t *self = MP_OBJ_TO_PTR(o_in); if (request == MP_STREAM_SEEK) { - struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)(uintptr_t)arg; + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg; switch (s->whence) { case 0: // SEEK_SET @@ -248,7 +248,7 @@ const mp_obj_type_t mp_type_vfs_fat_fileio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &fileio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; #endif @@ -268,7 +268,7 @@ const mp_obj_type_t mp_type_vfs_fat_textio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &textio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; // Factory function for I/O stream classes diff --git a/extmod/vfs_posix.c b/extmod/vfs_posix.c index 8d81d51751..02f0e7cea9 100644 --- a/extmod/vfs_posix.c +++ b/extmod/vfs_posix.c @@ -42,7 +42,7 @@ STATIC mp_obj_t vfs_posix_get_path_obj(mp_obj_vfs_posix_t *self, mp_obj_t path) } } -STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char*)) { +STATIC mp_obj_t vfs_posix_fun1_helper(mp_obj_t self_in, mp_obj_t path_in, int (*f)(const char *)) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); int ret = f(vfs_posix_get_path_str(self, path_in)); if (ret != 0) { @@ -168,7 +168,7 @@ STATIC mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { if (self->is_str) { t->items[0] = mp_obj_new_str(fn, strlen(fn)); } else { - t->items[0] = mp_obj_new_bytes((const byte*)fn, strlen(fn)); + t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); } #ifdef _DIRENT_HAVE_D_TYPE @@ -338,7 +338,7 @@ const mp_obj_type_t mp_type_vfs_posix = { .name = MP_QSTR_VfsPosix, .make_new = vfs_posix_make_new, .protocol = &vfs_posix_proto, - .locals_dict = (mp_obj_dict_t*)&vfs_posix_locals_dict, + .locals_dict = (mp_obj_dict_t *)&vfs_posix_locals_dict, }; #endif // MICROPY_VFS_POSIX diff --git a/extmod/vfs_posix_file.c b/extmod/vfs_posix_file.c index 593b8d6a29..bc45a2cf2e 100644 --- a/extmod/vfs_posix_file.c +++ b/extmod/vfs_posix_file.c @@ -58,7 +58,7 @@ mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_ case '+': mode_rw = O_RDWR; break; - #if MICROPY_PY_IO_FILEIO + #if MICROPY_PY_IO_FILEIO // If we don't have io.FileIO, then files are in text mode implicitly case 'b': type = &mp_type_vfs_posix_fileio; @@ -66,7 +66,7 @@ mp_obj_t mp_vfs_posix_file_open(const mp_obj_type_t *type, mp_obj_t file_in, mp_ case 't': type = &mp_type_vfs_posix_textio; break; - #endif + #endif } } @@ -159,7 +159,7 @@ STATIC mp_uint_t vfs_posix_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_ } return 0; case MP_STREAM_SEEK: { - struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg; + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; off_t off = lseek(o->fd, s->offset, s->whence); if (off == (off_t)-1) { *errcode = errno; @@ -213,7 +213,7 @@ const mp_obj_type_t mp_type_vfs_posix_fileio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &fileio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; #endif @@ -233,10 +233,10 @@ const mp_obj_type_t mp_type_vfs_posix_textio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &textio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; -const mp_obj_vfs_posix_file_t mp_sys_stdin_obj = {{&mp_type_textio}, STDIN_FILENO}; +const mp_obj_vfs_posix_file_t mp_sys_stdin_obj = {{&mp_type_textio}, STDIN_FILENO}; const mp_obj_vfs_posix_file_t mp_sys_stdout_obj = {{&mp_type_textio}, STDOUT_FILENO}; const mp_obj_vfs_posix_file_t mp_sys_stderr_obj = {{&mp_type_textio}, STDERR_FILENO}; diff --git a/extmod/vfs_reader.c b/extmod/vfs_reader.c index a700611860..d9abc3c957 100644 --- a/extmod/vfs_reader.c +++ b/extmod/vfs_reader.c @@ -21,7 +21,7 @@ typedef struct _mp_reader_vfs_t { } mp_reader_vfs_t; STATIC mp_uint_t mp_reader_vfs_readbyte(void *data) { - mp_reader_vfs_t *reader = (mp_reader_vfs_t*)data; + mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data; if (reader->pos >= reader->len) { if (reader->len < sizeof(reader->buf)) { return MP_READER_EOF; @@ -43,7 +43,7 @@ STATIC mp_uint_t mp_reader_vfs_readbyte(void *data) { } STATIC void mp_reader_vfs_close(void *data) { - mp_reader_vfs_t *reader = (mp_reader_vfs_t*)data; + mp_reader_vfs_t *reader = (mp_reader_vfs_t *)data; mp_stream_close(reader->file); m_del_obj(mp_reader_vfs_t, reader); } @@ -51,7 +51,7 @@ STATIC void mp_reader_vfs_close(void *data) { void mp_reader_new_file(mp_reader_t *reader, const char *filename) { mp_reader_vfs_t *rf = m_new_obj(mp_reader_vfs_t); mp_obj_t arg = mp_obj_new_str(filename, strlen(filename)); - rf->file = mp_vfs_open(1, &arg, (mp_map_t*)&mp_const_empty_map); + rf->file = mp_vfs_open(1, &arg, (mp_map_t *)&mp_const_empty_map); int errcode; rf->len = mp_stream_rw(rf->file, rf->buf, sizeof(rf->buf), &errcode, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE); if (errcode != 0) { diff --git a/extmod/virtpin.c b/extmod/virtpin.c index fb993946a2..bb4935a0bc 100644 --- a/extmod/virtpin.c +++ b/extmod/virtpin.c @@ -7,13 +7,13 @@ #include "py/proto.h" int mp_virtual_pin_read(mp_obj_t pin) { - mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(pin); + mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin); const mp_pin_p_t *pin_p = mp_proto_get(MP_QSTR_protocol_pin, s); return pin_p->ioctl(pin, MP_PIN_READ, 0, NULL); } void mp_virtual_pin_write(mp_obj_t pin, int value) { - mp_obj_base_t* s = (mp_obj_base_t*)MP_OBJ_TO_PTR(pin); + mp_obj_base_t *s = (mp_obj_base_t *)MP_OBJ_TO_PTR(pin); const mp_pin_p_t *pin_p = mp_proto_get(MP_QSTR_protocol_pin, s); pin_p->ioctl(pin, MP_PIN_WRITE, value, NULL); } diff --git a/lib/netutils/netutils.c b/lib/netutils/netutils.c index 4385f5a5e5..e82ef9270d 100644 --- a/lib/netutils/netutils.c +++ b/lib/netutils/netutils.c @@ -65,7 +65,7 @@ void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian } const char *s = addr_str; const char *s_top = addr_str + addr_len; - for (mp_uint_t i = 3 ; ; i--) { + for (mp_uint_t i = 3; ; i--) { mp_uint_t val = 0; for (; s < s_top && *s != '.'; s++) { val = val * 10 + *s - '0'; diff --git a/lib/timeutils/timeutils.c b/lib/timeutils/timeutils.c index fdd3426ad4..6cbea31aab 100644 --- a/lib/timeutils/timeutils.c +++ b/lib/timeutils/timeutils.c @@ -36,11 +36,11 @@ #define LEAPOCH ((31 + 29) * 86400) -#define DAYS_PER_400Y (365*400 + 97) -#define DAYS_PER_100Y (365*100 + 24) -#define DAYS_PER_4Y (365*4 + 1) +#define DAYS_PER_400Y (365 * 400 + 97) +#define DAYS_PER_100Y (365 * 100 + 24) +#define DAYS_PER_4Y (365 * 4 + 1) -STATIC const uint16_t days_since_jan1[]= { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; +STATIC const uint16_t days_since_jan1[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; bool timeutils_is_leap_year(mp_uint_t year) { return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; @@ -164,7 +164,7 @@ void timeutils_seconds_since_epoch_to_struct_time(mp_uint_t t, timeutils_struct_ } mp_uint_t timeutils_seconds_since_epoch(mp_uint_t year, mp_uint_t month, mp_uint_t date, - mp_uint_t hour, mp_uint_t minute, mp_uint_t second) { + mp_uint_t hour, mp_uint_t minute, mp_uint_t second) { mp_uint_t t = timeutils_seconds_since_2000(year, month, date, hour, minute, second); return t + EPOCH1970_EPOCH2000_DIFF_SECS; } diff --git a/lib/timeutils/timeutils.h b/lib/timeutils/timeutils.h index 4ba8c7fdac..1686174287 100644 --- a/lib/timeutils/timeutils.h +++ b/lib/timeutils/timeutils.h @@ -30,14 +30,14 @@ #define EPOCH1970_EPOCH2000_DIFF_SECS 946684800 typedef struct _timeutils_struct_time_t { - uint16_t tm_year; // i.e. 2014 - uint8_t tm_mon; // 1..12 - uint8_t tm_mday; // 1..31 - uint8_t tm_hour; // 0..23 - uint8_t tm_min; // 0..59 - uint8_t tm_sec; // 0..59 - uint8_t tm_wday; // 0..6 0 = Monday - uint16_t tm_yday; // 1..366 + uint16_t tm_year; // i.e. 2014 + uint8_t tm_mon; // 1..12 + uint8_t tm_mday; // 1..31 + uint8_t tm_hour; // 0..23 + uint8_t tm_min; // 0..59 + uint8_t tm_sec; // 0..59 + uint8_t tm_wday; // 0..6 0 = Monday + uint16_t tm_yday; // 1..366 } timeutils_struct_time_t; bool timeutils_is_leap_year(mp_uint_t year); @@ -53,7 +53,7 @@ mp_uint_t timeutils_seconds_since_2000(mp_uint_t year, mp_uint_t month, void timeutils_seconds_since_epoch_to_struct_time(mp_uint_t t, timeutils_struct_time_t *tm); mp_uint_t timeutils_seconds_since_epoch(mp_uint_t year, mp_uint_t month, mp_uint_t date, - mp_uint_t hour, mp_uint_t minute, mp_uint_t second); + mp_uint_t hour, mp_uint_t minute, mp_uint_t second); mp_uint_t timeutils_mktime(mp_uint_t year, mp_int_t month, mp_int_t mday, mp_int_t hours, mp_int_t minutes, mp_int_t seconds); diff --git a/lib/utils/buffer_helper.c b/lib/utils/buffer_helper.c index 694952e3d2..a4008225d6 100644 --- a/lib/utils/buffer_helper.c +++ b/lib/utils/buffer_helper.c @@ -26,10 +26,10 @@ #include "lib/utils/buffer_helper.h" -void normalize_buffer_bounds(int32_t* start, int32_t end, size_t* length) { +void normalize_buffer_bounds(int32_t *start, int32_t end, size_t *length) { if (end < 0) { end += *length; - } else if (((size_t) end) > *length) { + } else if (((size_t)end) > *length) { end = *length; } if (*start < 0) { diff --git a/lib/utils/buffer_helper.h b/lib/utils/buffer_helper.h index 7487b9df53..9611dc309a 100644 --- a/lib/utils/buffer_helper.h +++ b/lib/utils/buffer_helper.h @@ -30,6 +30,6 @@ #include #include -void normalize_buffer_bounds(int32_t* start, int32_t end, size_t* length); +void normalize_buffer_bounds(int32_t *start, int32_t end, size_t *length); #endif // MICROPY_INCLUDED_LIB_UTILS_BUFFER_HELPER_H diff --git a/lib/utils/context_manager_helpers.c b/lib/utils/context_manager_helpers.c index 901c27030f..2614856160 100644 --- a/lib/utils/context_manager_helpers.c +++ b/lib/utils/context_manager_helpers.c @@ -29,6 +29,6 @@ #include "py/obj.h" STATIC mp_obj_t default___enter__(mp_obj_t self_in) { - return self_in; + return self_in; } MP_DEFINE_CONST_FUN_OBJ_1(default___enter___obj, default___enter__); diff --git a/lib/utils/printf.c b/lib/utils/printf.c index e95d778fd2..859c7e0017 100644 --- a/lib/utils/printf.c +++ b/lib/utils/printf.c @@ -108,7 +108,7 @@ STATIC void strn_print_strn(void *data, const char *str, size_t len) { // when linkings against it statically. // GCC 9 gives a warning about missing attributes so it's excluded until // uClibc+GCC9 support is needed. -int __GI_vsnprintf(char *str, size_t size, const char *fmt, va_list ap) __attribute__((weak, alias ("vsnprintf"))); +int __GI_vsnprintf(char *str, size_t size, const char *fmt, va_list ap) __attribute__((weak, alias("vsnprintf"))); #endif int vsnprintf(char *str, size_t size, const char *fmt, va_list ap) { @@ -134,4 +134,4 @@ int snprintf(char *str, size_t size, const char *fmt, ...) { return ret; } -#endif //MICROPY_USE_INTERNAL_PRINTF +#endif // MICROPY_USE_INTERNAL_PRINTF diff --git a/lib/utils/pyexec.c b/lib/utils/pyexec.c old mode 100755 new mode 100644 index 68a3710ce6..450b5ae326 --- a/lib/utils/pyexec.c +++ b/lib/utils/pyexec.c @@ -85,7 +85,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input } else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) { lex = mp_lexer_new_from_file(source); } else { - lex = (mp_lexer_t*)source; + lex = (mp_lexer_t *)source; } // source is a lexer, parse and compile the script qstr source_name = lex->source_name; @@ -95,7 +95,7 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input mp_parse_tree_t parse_tree = mp_parse(lex, input_kind); module_fun = mp_compile(&parse_tree, source_name, MP_EMIT_OPT_NONE, exec_flags & EXEC_FLAG_IS_REPL); // Clear the parse tree because it has a heap pointer we don't need anymore. - *((uint32_t volatile*) &parse_tree.chunk) = 0; + *((uint32_t volatile *)&parse_tree.chunk) = 0; #else mp_raise_msg(&mp_type_RuntimeError, translate("script compilation not supported")); #endif @@ -132,12 +132,12 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input if (mp_obj_is_subclass_fast(mp_obj_get_type((mp_obj_t)nlr.ret_val), &mp_type_SystemExit)) { // at the moment, the value of SystemExit is unused ret = pyexec_system_exit; -#if CIRCUITPY_ALARM + #if CIRCUITPY_ALARM } else if (mp_obj_is_subclass_fast(mp_obj_get_type((mp_obj_t)nlr.ret_val), &mp_type_DeepSleepRequest)) { ret = PYEXEC_DEEP_SLEEP; -#endif + #endif } else { - if ((mp_obj_t) nlr.ret_val != MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_reload_exception))) { + if ((mp_obj_t)nlr.ret_val != MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_reload_exception))) { mp_obj_print_exception(&mp_plat_print, (mp_obj_t)nlr.ret_val); } ret = PYEXEC_EXCEPTION; @@ -169,8 +169,8 @@ STATIC int parse_compile_execute(const void *source, mp_parse_input_kind_t input size_t n_pool, n_qstr, n_str_data_bytes, n_total_bytes; qstr_pool_info(&n_pool, &n_qstr, &n_str_data_bytes, &n_total_bytes); printf("qstr:\n n_pool=" UINT_FMT "\n n_qstr=" UINT_FMT "\n " - "n_str_data_bytes=" UINT_FMT "\n n_total_bytes=" UINT_FMT "\n", - (unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes); + "n_str_data_bytes=" UINT_FMT "\n n_total_bytes=" UINT_FMT "\n", + (unsigned)n_pool, (unsigned)n_qstr, (unsigned)n_str_data_bytes, (unsigned)n_total_bytes); } #if MICROPY_ENABLE_GC @@ -195,7 +195,7 @@ typedef struct _repl_t { // but it was moved to MP_STATE_VM(repl_line) as containing // root pointer. Still keep structure in case more state // will be added later. - //vstr_t line; + // vstr_t line; bool cont_line; } repl_t; @@ -307,10 +307,10 @@ STATIC int pyexec_friendly_repl_process_char(int c) { } else { if (ret == CHAR_CTRL_C) { - // cancel everything - mp_hal_stdout_tx_str("\r\n"); - repl.cont_line = false; - goto input_restart; + // cancel everything + mp_hal_stdout_tx_str("\r\n"); + repl.cont_line = false; + goto input_restart; } else if (ret == CHAR_CTRL_D) { // stop entering compound statement goto exec; @@ -326,13 +326,13 @@ STATIC int pyexec_friendly_repl_process_char(int c) { return 0; } -exec: ; + exec:; int ret = parse_compile_execute(MP_STATE_VM(repl_line), MP_PARSE_SINGLE_INPUT, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR, NULL); if (ret & PYEXEC_FORCED_EXIT) { return ret; } -input_restart: + input_restart: vstr_reset(MP_STATE_VM(repl_line)); repl.cont_line = false; readline_init(MP_STATE_VM(repl_line), ">>> "); @@ -409,11 +409,11 @@ int pyexec_friendly_repl(void) { vstr_t line; vstr_init(&line, 32); -#if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD + #if defined(USE_HOST_MODE) && MICROPY_HW_HAS_LCD // in host mode, we enable the LCD for the repl mp_obj_t lcd_o = mp_call_function_0(mp_load_name(qstr_from_str("LCD"))); mp_call_function_1(mp_load_attr(lcd_o, qstr_from_str("light")), mp_const_true); -#endif + #endif friendly_repl_reset: mp_hal_stdout_tx_str("\r\n"); diff --git a/lib/utils/pyexec.h b/lib/utils/pyexec.h index 4c773cd640..bde2960c29 100644 --- a/lib/utils/pyexec.h +++ b/lib/utils/pyexec.h @@ -35,7 +35,7 @@ typedef enum { typedef struct { int return_code; - const mp_obj_type_t * exception_type; + const mp_obj_type_t *exception_type; int exception_line; } pyexec_result_t; diff --git a/lib/utils/stdout_helpers.c b/lib/utils/stdout_helpers.c index 4323e8a083..500b9748be 100644 --- a/lib/utils/stdout_helpers.c +++ b/lib/utils/stdout_helpers.c @@ -20,7 +20,7 @@ void mp_hal_stdout_tx_strn_cooked(const char *str, size_t len) { i = 1; } // Lump all characters on the next line together. - while((last_cr || str[i] != '\n') && i < len) { + while ((last_cr || str[i] != '\n') && i < len) { last_cr = str[i] == '\r'; i++; } diff --git a/lib/utils/sys_stdio_mphal.c b/lib/utils/sys_stdio_mphal.c index 3a11fa66c9..e2e1999c25 100644 --- a/lib/utils/sys_stdio_mphal.c +++ b/lib/utils/sys_stdio_mphal.c @@ -65,7 +65,7 @@ STATIC mp_uint_t stdio_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *er if (c == '\r') { c = '\n'; } - ((byte*)buf)[i] = c; + ((byte *)buf)[i] = c; } return size; } else { @@ -87,7 +87,7 @@ STATIC mp_uint_t stdio_write(mp_obj_t self_in, const void *buf, mp_uint_t size, STATIC mp_uint_t stdio_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { sys_stdio_obj_t *self = MP_OBJ_TO_PTR(self_in); - (void) self; + (void)self; // For now, pretend we actually flush the stdio stream. if (request == MP_STREAM_FLUSH) { @@ -106,9 +106,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(stdio_obj___exit___obj, 4, 4, stdio_o // TODO gc hook to close the file if not already closed STATIC const mp_rom_map_elem_t stdio_locals_dict_table[] = { -#if MICROPY_PY_SYS_STDIO_BUFFER + #if MICROPY_PY_SYS_STDIO_BUFFER { MP_ROM_QSTR(MP_QSTR_buffer), MP_ROM_PTR(&stdio_buffer_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj)}, @@ -138,7 +138,7 @@ STATIC const mp_obj_type_t stdio_obj_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &stdio_obj_stream_p, - .locals_dict = (mp_obj_dict_t*)&stdio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stdio_locals_dict, }; const sys_stdio_obj_t mp_sys_stdin_obj = {{&stdio_obj_type}, .fd = STDIO_FD_IN}; @@ -148,7 +148,7 @@ const sys_stdio_obj_t mp_sys_stderr_obj = {{&stdio_obj_type}, .fd = STDIO_FD_ERR #if MICROPY_PY_SYS_STDIO_BUFFER STATIC mp_uint_t stdio_buffer_read(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { for (uint i = 0; i < size; i++) { - ((byte*)buf)[i] = mp_hal_stdin_rx_chr(); + ((byte *)buf)[i] = mp_hal_stdin_rx_chr(); } return size; } diff --git a/mpy-cross/fmode.c b/mpy-cross/fmode.c index b1fa3fc857..f32a4af5d3 100644 --- a/mpy-cross/fmode.c +++ b/mpy-cross/fmode.c @@ -11,12 +11,12 @@ // Workaround for setting file translation mode: we must distinguish toolsets // since mingw has no _set_fmode, and altering msvc's _fmode directly has no effect STATIC int set_fmode_impl(int mode) { -#ifndef _MSC_VER + #ifndef _MSC_VER _fmode = mode; return 0; -#else + #else return _set_fmode(mode); -#endif + #endif } void set_fmode_binary(void) { diff --git a/mpy-cross/gccollect.c b/mpy-cross/gccollect.c index 2216fad311..9a975af8db 100644 --- a/mpy-cross/gccollect.c +++ b/mpy-cross/gccollect.c @@ -28,20 +28,20 @@ STATIC void gc_helper_get_regs(regs_t arr) { register long r13 asm ("r13"); register long r14 asm ("r14"); register long r15 asm ("r15"); -#ifdef __clang__ + #ifdef __clang__ // TODO: // This is dirty workaround for Clang. It tries to get around // uncompliant (wrt to GCC) behavior of handling register variables. // Application of this patch here is random, and done only to unbreak // MacOS build. Better, cross-arch ways to deal with Clang issues should // be found. - asm("" : "=r"(rbx)); - asm("" : "=r"(rbp)); - asm("" : "=r"(r12)); - asm("" : "=r"(r13)); - asm("" : "=r"(r14)); - asm("" : "=r"(r15)); -#endif + asm ("" : "=r" (rbx)); + asm ("" : "=r" (rbp)); + asm ("" : "=r" (r12)); + asm ("" : "=r" (r13)); + asm ("" : "=r" (r14)); + asm ("" : "=r" (r15)); + #endif arr[0] = rbx; arr[1] = rbp; arr[2] = r12; @@ -120,7 +120,7 @@ void gc_collect(void) { regs_t regs; gc_helper_get_regs(regs); // GC stack (and regs because we captured them) - void **regs_ptr = (void**)(void*)®s; + void **regs_ptr = (void **)(void *)®s; gc_collect_root(regs_ptr, ((mp_uint_t)MP_STATE_THREAD(stack_top) - (mp_uint_t)®s) / sizeof(mp_uint_t)); #if MICROPY_EMIT_NATIVE mp_unix_mark_exec(); @@ -128,4 +128,4 @@ void gc_collect(void) { gc_collect_end(); } -#endif //MICROPY_ENABLE_GC +#endif // MICROPY_ENABLE_GC diff --git a/mpy-cross/main.c b/mpy-cross/main.c index 7a1012b8fc..6e99ea2408 100644 --- a/mpy-cross/main.c +++ b/mpy-cross/main.c @@ -23,7 +23,7 @@ mp_uint_t mp_verbose_flag = 0; // Heap size of GC heap (if enabled) // Make it larger on a 64 bit machine, because pointers are larger. -long heap_size = 1024*1024 * (sizeof(mp_uint_t) / 4); +long heap_size = 1024 * 1024 * (sizeof(mp_uint_t) / 4); STATIC void stderr_print_strn(void *env, const char *str, mp_uint_t len) { (void)env; @@ -77,28 +77,28 @@ STATIC int compile_and_save(const char *file, const char *output_file, const cha STATIC int usage(char **argv) { printf( -"usage: %s [] [-X ] \n" -"Options:\n" -"-o : output file for compiled bytecode (defaults to input with .mpy extension)\n" -"-s : source filename to embed in the compiled bytecode (defaults to input file)\n" -"-v : verbose (trace various operations); can be multiple\n" -"-O[N] : apply bytecode optimizations of level N\n" -"\n" -"Target specific options:\n" -"-msmall-int-bits=number : set the maximum bits used to encode a small-int\n" -"-mno-unicode : don't support unicode in compiled strings\n" -"-mcache-lookup-bc : cache map lookups in the bytecode\n" -"\n" -"Implementation specific options:\n", argv[0] -); + "usage: %s [] [-X ] \n" + "Options:\n" + "-o : output file for compiled bytecode (defaults to input with .mpy extension)\n" + "-s : source filename to embed in the compiled bytecode (defaults to input file)\n" + "-v : verbose (trace various operations); can be multiple\n" + "-O[N] : apply bytecode optimizations of level N\n" + "\n" + "Target specific options:\n" + "-msmall-int-bits=number : set the maximum bits used to encode a small-int\n" + "-mno-unicode : don't support unicode in compiled strings\n" + "-mcache-lookup-bc : cache map lookups in the bytecode\n" + "\n" + "Implementation specific options:\n", argv[0] + ); int impl_opts_cnt = 0; printf( -" emit={bytecode,native,viper} -- set the default code emitter\n" -); + " emit={bytecode,native,viper} -- set the default code emitter\n" + ); impl_opts_cnt++; printf( -" heapsize= -- set the heap size for the GC (default %ld)\n" -, heap_size); + " heapsize= -- set the heap size for the GC (default %ld)\n" + , heap_size); impl_opts_cnt++; if (impl_opts_cnt == 0) { @@ -162,9 +162,9 @@ MP_NOINLINE int main_(int argc, char **argv) { gc_init(heap, heap + heap_size); mp_init(); -#ifdef _WIN32 + #ifdef _WIN32 set_fmode_binary(); -#endif + #endif mp_obj_list_init(mp_sys_path, 0); mp_obj_list_init(mp_sys_argv, 0); @@ -189,7 +189,8 @@ MP_NOINLINE int main_(int argc, char **argv) { MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf; } else { MP_STATE_VM(mp_optimise_value) = 0; - for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++); + for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++) {; + } } } else if (strcmp(argv[a], "-o") == 0) { if (a + 1 >= argc) { @@ -264,6 +265,6 @@ void nlr_jump_fail(void *val) { exit(1); } -void serial_write(const char* text) { +void serial_write(const char *text) { printf("%s", text); } diff --git a/mpy-cross/mpconfigport.h b/mpy-cross/mpconfigport.h index 464c9113d5..74bb774afc 100644 --- a/mpy-cross/mpconfigport.h +++ b/mpy-cross/mpconfigport.h @@ -68,45 +68,45 @@ // MINGW only handles these errno names. #ifdef __MINGW32__ #define MICROPY_PY_UERRNO_LIST \ - X(EPERM) \ - X(ENOENT) \ - X(ESRCH) \ - X(EINTR) \ - X(EIO) \ - X(ENXIO) \ - X(E2BIG) \ - X(ENOEXEC) \ - X(EBADF) \ - X(ECHILD) \ - X(EAGAIN) \ - X(ENOMEM) \ - X(EACCES) \ - X(EFAULT) \ - X(EBUSY) \ - X(EEXIST) \ - X(EXDEV) \ - X(ENODEV) \ - X(ENOTDIR) \ - X(EISDIR) \ - X(EINVAL) \ - X(ENFILE) \ - X(EMFILE) \ - X(ENOTTY) \ - X(EFBIG) \ - X(ENOSPC) \ - X(ESPIPE) \ - X(EROFS) \ - X(EMLINK) \ - X(EPIPE) \ - X(EDOM) \ - X(ERANGE) \ - X(EDEADLOCK) \ - X(EDEADLK) \ - X(ENAMETOOLONG) \ - X(ENOLCK) \ - X(ENOSYS) \ - X(ENOTEMPTY) \ - X(EILSEQ) + X(EPERM) \ + X(ENOENT) \ + X(ESRCH) \ + X(EINTR) \ + X(EIO) \ + X(ENXIO) \ + X(E2BIG) \ + X(ENOEXEC) \ + X(EBADF) \ + X(ECHILD) \ + X(EAGAIN) \ + X(ENOMEM) \ + X(EACCES) \ + X(EFAULT) \ + X(EBUSY) \ + X(EEXIST) \ + X(EXDEV) \ + X(ENODEV) \ + X(ENOTDIR) \ + X(EISDIR) \ + X(EINVAL) \ + X(ENFILE) \ + X(EMFILE) \ + X(ENOTTY) \ + X(EFBIG) \ + X(ENOSPC) \ + X(ESPIPE) \ + X(EROFS) \ + X(EMLINK) \ + X(EPIPE) \ + X(EDOM) \ + X(ERANGE) \ + X(EDEADLOCK) \ + X(EDEADLK) \ + X(ENAMETOOLONG) \ + X(ENOLCK) \ + X(ENOSYS) \ + X(ENOTEMPTY) \ + X(EILSEQ) #endif // type definitions for the specific machine @@ -114,7 +114,7 @@ #ifdef __LP64__ typedef long mp_int_t; // must be pointer size typedef unsigned long mp_uint_t; // must be pointer size -#elif defined ( __MINGW32__ ) && defined( _WIN64 ) +#elif defined(__MINGW32__) && defined(_WIN64) #include typedef __int64 mp_int_t; typedef unsigned __int64 mp_uint_t; @@ -141,7 +141,7 @@ typedef long mp_off_t; // We need to provide a declaration/definition of alloca() #ifdef __FreeBSD__ #include -#elif defined( _WIN32 ) +#elif defined(_WIN32) #include #else #include diff --git a/ports/atmel-samd/asf4_conf/samd21/hpl_gclk_config.h b/ports/atmel-samd/asf4_conf/samd21/hpl_gclk_config.h index b97131f0bc..a3d67d8b3b 100644 --- a/ports/atmel-samd/asf4_conf/samd21/hpl_gclk_config.h +++ b/ports/atmel-samd/asf4_conf/samd21/hpl_gclk_config.h @@ -93,8 +93,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 0 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 0 division <0x0000-0xFFFF> // // gclk_gen_0_div #ifndef CONF_GCLK_GEN_0_DIV @@ -177,8 +177,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 1 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 1 division <0x0000-0xFFFF> // // gclk_gen_1_div #ifndef CONF_GCLK_GEN_1_DIV @@ -263,8 +263,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 2 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 2 division <0x0000-0xFFFF> // // gclk_gen_2_div #ifndef CONF_GCLK_GEN_2_DIV @@ -349,8 +349,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 3 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 3 division <0x0000-0xFFFF> // // gclk_gen_3_div #ifndef CONF_GCLK_GEN_3_DIV @@ -435,8 +435,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 4 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 4 division <0x0000-0xFFFF> // // gclk_gen_4_div #ifndef CONF_GCLK_GEN_4_DIV @@ -521,8 +521,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 5 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 5 division <0x0000-0xFFFF> // // gclk_gen_5_div #ifndef CONF_GCLK_GEN_5_DIV @@ -607,8 +607,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 6 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 6 division <0x0000-0xFFFF> // // gclk_gen_6_div #ifndef CONF_GCLK_GEN_6_DIV @@ -693,8 +693,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 7 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 7 division <0x0000-0xFFFF> // // gclk_gen_7_div #ifndef CONF_GCLK_GEN_7_DIV diff --git a/ports/atmel-samd/asf4_conf/samd21/hpl_sercom_config.h b/ports/atmel-samd/asf4_conf/samd21/hpl_sercom_config.h index 85d05fc504..007a72d068 100644 --- a/ports/atmel-samd/asf4_conf/samd21/hpl_sercom_config.h +++ b/ports/atmel-samd/asf4_conf/samd21/hpl_sercom_config.h @@ -294,12 +294,12 @@ // BAUD: register value low [7:0] // BAUDLOW: register value high [15:8], only used for odd BAUD + BAUDLOW #define CONF_SERCOM_1_I2CM_BAUD_BAUDLOW \ - (((CONF_GCLK_SERCOM1_CORE_FREQUENCY - (CONF_SERCOM_1_I2CM_BAUD * 10) \ - - (CONF_SERCOM_1_I2CM_TRISE * (CONF_SERCOM_1_I2CM_BAUD / 100) * (CONF_GCLK_SERCOM1_CORE_FREQUENCY / 10000) \ - / 1000)) \ - * 10 \ - + 5) \ - / (CONF_SERCOM_1_I2CM_BAUD * 10)) + (((CONF_GCLK_SERCOM1_CORE_FREQUENCY - (CONF_SERCOM_1_I2CM_BAUD * 10) \ + - (CONF_SERCOM_1_I2CM_TRISE * (CONF_SERCOM_1_I2CM_BAUD / 100) * (CONF_GCLK_SERCOM1_CORE_FREQUENCY / 10000) \ + / 1000)) \ + * 10 \ + + 5) \ + / (CONF_SERCOM_1_I2CM_BAUD * 10)) #ifndef CONF_SERCOM_1_I2CM_BAUD_RATE #if CONF_SERCOM_1_I2CM_BAUD_BAUDLOW > (0xFF * 2) #warning Requested I2C baudrate too low, please check @@ -309,9 +309,9 @@ #define CONF_SERCOM_1_I2CM_BAUD_RATE 1 #else #define CONF_SERCOM_1_I2CM_BAUD_RATE \ - ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW & 0x1) \ - ? (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2 + 1) << 8) \ - : (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2)) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW & 0x1) \ + ? (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2 + 1) << 8) \ + : (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2)) #endif #endif @@ -506,7 +506,7 @@ #if CONF_SERCOM_2_USART_SAMPR == 0 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 16.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 16.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -514,7 +514,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 1 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 16)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) + ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 16)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -522,7 +522,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 2 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 8.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 8.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -530,7 +530,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 3 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 8)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) + ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 8)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -538,7 +538,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 4 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 3.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 3.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -552,9 +552,9 @@ #define CONF_SERCOM_3_SPI_ENABLE 1 #endif -// SPI DMA TX Channel <0-32> -// This defines DMA channel to be used -// spi_master_dma_tx_channel +// SPI DMA TX Channel <0-32> +// This defines DMA channel to be used +// spi_master_dma_tx_channel #ifndef CONF_SERCOM_3_SPI_M_DMA_TX_CHANNEL #define CONF_SERCOM_3_SPI_M_DMA_TX_CHANNEL 0 #endif @@ -565,9 +565,9 @@ #define CONF_SERCOM_3_SPI_RX_CHANNEL 1 #endif -// DMA Channel <0-32> -// This defines DMA channel to be used -// spi_master_dma_rx_channel +// DMA Channel <0-32> +// This defines DMA channel to be used +// spi_master_dma_rx_channel #ifndef CONF_SERCOM_3_SPI_M_DMA_RX_CHANNEL #define CONF_SERCOM_3_SPI_M_DMA_RX_CHANNEL 1 #endif diff --git a/ports/atmel-samd/asf4_conf/samd21/hpl_sysctrl_config.h b/ports/atmel-samd/asf4_conf/samd21/hpl_sysctrl_config.h index 74ec2bee95..193298ed91 100644 --- a/ports/atmel-samd/asf4_conf/samd21/hpl_sysctrl_config.h +++ b/ports/atmel-samd/asf4_conf/samd21/hpl_sysctrl_config.h @@ -95,7 +95,7 @@ #endif // Osc Calibration Value <0-65535> -// Set the Oscillator Calibration Value +// Set the Oscillator Calibration Value // Default: 1 // osc8m_arch_calib #ifndef CONF_OSC8M_CALIB @@ -183,7 +183,7 @@ #endif // Osc Calibration Value <0-65535> -// Set the Oscillator Calibration Value +// Set the Oscillator Calibration Value // Default: 0 // osc32k_arch_calib #ifndef CONF_OSC32K_CALIB @@ -396,7 +396,7 @@ #endif // Osc Calibration Value <0-255> -// Set the Oscillator Calibration Value +// Set the Oscillator Calibration Value // Default: 0 // osculp32k_arch_calib #ifndef CONF_OSCULP32K_CALIB @@ -536,7 +536,7 @@ #endif // DFLL Multiply Factor<0-65535> -// Set the DFLL Multiply Factor +// Set the DFLL Multiply Factor // Default: 0 // dfll48m_mul #ifndef CONF_DFLL_MUL @@ -564,17 +564,17 @@ #if CONF_DFLL_OVERWRITE_CALIBRATION == 0 #define CONF_DEFAULT_CORASE \ - ((FUSES_DFLL48M_COARSE_CAL_Msk & (*((uint32_t *)FUSES_DFLL48M_COARSE_CAL_ADDR))) >> FUSES_DFLL48M_COARSE_CAL_Pos) + ((FUSES_DFLL48M_COARSE_CAL_Msk & (*((uint32_t *)FUSES_DFLL48M_COARSE_CAL_ADDR))) >> FUSES_DFLL48M_COARSE_CAL_Pos) #define CONF_DFLLVAL \ - SYSCTRL_DFLLVAL_COARSE(((CONF_DEFAULT_CORASE) == 0x3F) ? 0x1F : (CONF_DEFAULT_CORASE)) \ - | SYSCTRL_DFLLVAL_FINE(512) + SYSCTRL_DFLLVAL_COARSE(((CONF_DEFAULT_CORASE) == 0x3F) ? 0x1F : (CONF_DEFAULT_CORASE)) \ + | SYSCTRL_DFLLVAL_FINE(512) #else #define CONF_DFLLVAL SYSCTRL_DFLLVAL_COARSE(CONF_DFLL_COARSE) | SYSCTRL_DFLLVAL_FINE(CONF_DFLL_FINE) #endif -// +// // // diff --git a/ports/atmel-samd/asf4_conf/samd21/hpl_tc_config.h b/ports/atmel-samd/asf4_conf/samd21/hpl_tc_config.h index 90e9b07357..d651ca33a8 100644 --- a/ports/atmel-samd/asf4_conf/samd21/hpl_tc_config.h +++ b/ports/atmel-samd/asf4_conf/samd21/hpl_tc_config.h @@ -27,7 +27,7 @@ #define CONF_TC3_PRESCALER TC_CTRLA_PRESCALER_DIV8_Val #endif -// Period Value <0x00000000-0xFFFFFFFF> +// Period Value <0x00000000-0xFFFFFFFF> // tc_per #ifndef CONF_TC3_PER #define CONF_TC3_PER 0x32 @@ -52,7 +52,7 @@ /* Caculate pwm ccx register value based on WAVE_PER_VAL and Waveform Duty Value */ #if CONF_TC3_PRESCALER < TC_CTRLA_PRESCALER_DIV64_Val #define CONF_TC3_CC0 \ - ((uint32_t)(((double)CONF_TC3_WAVE_PER_VAL * CONF_GCLK_TC3_FREQUENCY) / 1000000 / (1 << CONF_TC3_PRESCALER) - 1)) + ((uint32_t)(((double)CONF_TC3_WAVE_PER_VAL * CONF_GCLK_TC3_FREQUENCY) / 1000000 / (1 << CONF_TC3_PRESCALER) - 1)) #define CONF_TC3_CC1 ((CONF_TC3_CC0 * CONF_TC3_WAVE_DUTY_VAL) / 1000) #elif CONF_TC3_PRESCALER == TC_CTRLA_PRESCALER_DIV64_Val @@ -83,7 +83,7 @@ // Advanced settings /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC3_WAVEGEN TC_CTRLA_WAVEGEN_MFRQ_Val +// #define CONF_TC3_WAVEGEN TC_CTRLA_WAVEGEN_MFRQ_Val // Run in standby // Indicates whether the will continue running in standby sleep mode or not @@ -103,14 +103,14 @@ #endif /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC3_DIR 0 -//#define CONF_TC3_ONESHOT 0 +// #define CONF_TC3_DIR 0 +// #define CONF_TC3_ONESHOT 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC3_INVEN0 0 -//#define CONF_TC3_INVEN1 0 -//#define CONF_TC3_CPTEN0 0 -//#define CONF_TC3_CPTEN1 0 +// #define CONF_TC3_INVEN0 0 +// #define CONF_TC3_INVEN1 0 +// #define CONF_TC3_CPTEN0 0 +// #define CONF_TC3_CPTEN1 0 // Debug Running Mode // Indicates whether the Debug Running Mode is enabled or not diff --git a/ports/atmel-samd/asf4_conf/samd21/usbd_config.h b/ports/atmel-samd/asf4_conf/samd21/usbd_config.h index df6dac3f78..b0f570b5e5 100644 --- a/ports/atmel-samd/asf4_conf/samd21/usbd_config.h +++ b/ports/atmel-samd/asf4_conf/samd21/usbd_config.h @@ -101,7 +101,7 @@ #ifndef CONF_USB_COMPOSITE_IPRODUCT #define CONF_USB_COMPOSITE_IPRODUCT \ - (CONF_USB_COMPOSITE_IPRODUCT_EN * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN)) + (CONF_USB_COMPOSITE_IPRODUCT_EN * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN)) #endif // Unicode string of iProduct @@ -124,8 +124,8 @@ #ifndef CONF_USB_COMPOSITE_ISERIALNUM #define CONF_USB_COMPOSITE_ISERIALNUM \ - (CONF_USB_COMPOSITE_ISERIALNUM_EN \ - * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN)) + (CONF_USB_COMPOSITE_ISERIALNUM_EN \ + * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN)) #endif // Unicode string of iSerialNum @@ -162,9 +162,9 @@ #ifndef CONF_USB_COMPOSITE_ICONFIG #define CONF_USB_COMPOSITE_ICONFIG \ - (CONF_USB_COMPOSITE_ICONFIG_EN \ - * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN \ - + CONF_USB_COMPOSITE_ICONFIG_EN)) + (CONF_USB_COMPOSITE_ICONFIG_EN \ + * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN \ + + CONF_USB_COMPOSITE_ICONFIG_EN)) #endif // Unicode string of iConfig @@ -453,9 +453,9 @@ #ifndef CONF_USB_COMPOSITE_HID_GENERIC_REPORT #define CONF_USB_COMPOSITE_HID_GENERIC_REPORT \ - 0x06, 0xFF, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, \ - 0x40, 0x81, 0x02, 0x09, 0x04, 0x09, 0x05, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, \ - 0x09, 0x06, 0x09, 0x07, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0xB1, 0x02, 0xC0 + 0x06, 0xFF, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, \ + 0x40, 0x81, 0x02, 0x09, 0x04, 0x09, 0x05, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, \ + 0x09, 0x06, 0x09, 0x07, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0xB1, 0x02, 0xC0 #endif // HID Generic INTERRUPT IN Endpoint Address @@ -650,7 +650,7 @@ #ifndef CONF_USB_MSC_LUN0_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN0_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN0_CAPACITY * 1024 / CONF_USB_MSC_LUN0_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN0_CAPACITY * 1024 / CONF_USB_MSC_LUN0_BLOCK_SIZE - 1) #endif // @@ -713,7 +713,7 @@ #ifndef CONF_USB_MSC_LUN1_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN1_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN1_CAPACITY * 1024 / CONF_USB_MSC_LUN1_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN1_CAPACITY * 1024 / CONF_USB_MSC_LUN1_BLOCK_SIZE - 1) #endif // @@ -775,7 +775,7 @@ #ifndef CONF_USB_MSC_LUN2_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN2_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN2_CAPACITY * 1024 / CONF_USB_MSC_LUN2_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN2_CAPACITY * 1024 / CONF_USB_MSC_LUN2_BLOCK_SIZE - 1) #endif // @@ -837,7 +837,7 @@ #ifndef CONF_USB_MSC_LUN3_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN3_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN3_CAPACITY * 1024 / CONF_USB_MSC_LUN3_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN3_CAPACITY * 1024 / CONF_USB_MSC_LUN3_BLOCK_SIZE - 1) #endif // diff --git a/ports/atmel-samd/asf4_conf/samd51/hpl_gclk_config.h b/ports/atmel-samd/asf4_conf/samd51/hpl_gclk_config.h index 6f4f01a7e6..1dda85a693 100644 --- a/ports/atmel-samd/asf4_conf/samd51/hpl_gclk_config.h +++ b/ports/atmel-samd/asf4_conf/samd51/hpl_gclk_config.h @@ -11,7 +11,7 @@ // Used in hpl/core/hpl_init.c to define which clocks should be initialized first. // Not clear why all these need to be specified, but it doesn't work properly otherwise. -//#define CIRCUITPY_GCLK_INIT_1ST (1 << 0 | 1 << 1 | 1 << 3 | 1 <<5) +// #define CIRCUITPY_GCLK_INIT_1ST (1 << 0 | 1 << 1 | 1 << 3 | 1 <<5) #define CIRCUITPY_GCLK_INIT_1ST 0xffff /* Auto-generated config file hpl_gclk_config.h */ @@ -52,7 +52,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_0_div_sel +// gclk_gen_0_div_sel #ifndef CONF_GCLK_GEN_0_DIVSEL #define CONF_GCLK_GEN_0_DIVSEL 0 #endif @@ -86,8 +86,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 0 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 0 division <0x0000-0xFFFF> // gclk_gen_0_div #ifndef CONF_GCLK_GEN_0_DIV #define CONF_GCLK_GEN_0_DIV 1 @@ -126,7 +126,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_1_div_sel +// gclk_gen_1_div_sel #ifndef CONF_GCLK_GEN_1_DIVSEL #define CONF_GCLK_GEN_1_DIVSEL 0 #endif @@ -160,8 +160,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 1 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 1 division <0x0000-0xFFFF> // gclk_gen_1_div #ifndef CONF_GCLK_GEN_1_DIV #define CONF_GCLK_GEN_1_DIV 1 @@ -201,7 +201,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_2_div_sel +// gclk_gen_2_div_sel #ifndef CONF_GCLK_GEN_2_DIVSEL #define CONF_GCLK_GEN_2_DIVSEL 1 #endif @@ -235,8 +235,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 2 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 2 division <0x0000-0xFFFF> // gclk_gen_2_div #ifndef CONF_GCLK_GEN_2_DIV #define CONF_GCLK_GEN_2_DIV 4 @@ -276,7 +276,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_3_div_sel +// gclk_gen_3_div_sel #ifndef CONF_GCLK_GEN_3_DIVSEL #define CONF_GCLK_GEN_3_DIVSEL 0 #endif @@ -310,8 +310,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 3 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 3 division <0x0000-0xFFFF> // gclk_gen_3_div #ifndef CONF_GCLK_GEN_3_DIV #define CONF_GCLK_GEN_3_DIV 1 @@ -351,7 +351,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_4_div_sel +// gclk_gen_4_div_sel #ifndef CONF_GCLK_GEN_4_DIVSEL #define CONF_GCLK_GEN_4_DIVSEL 0 #endif @@ -385,8 +385,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 4 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 4 division <0x0000-0xFFFF> // gclk_gen_4_div #ifndef CONF_GCLK_GEN_4_DIV #define CONF_GCLK_GEN_4_DIV 1 @@ -426,7 +426,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_5_div_sel +// gclk_gen_5_div_sel #ifndef CONF_GCLK_GEN_5_DIVSEL #define CONF_GCLK_GEN_5_DIVSEL 0 #endif @@ -460,8 +460,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 5 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 5 division <0x0000-0xFFFF> // gclk_gen_5_div #ifndef CONF_GCLK_GEN_5_DIV #define CONF_GCLK_GEN_5_DIV 24 @@ -501,7 +501,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_6_div_sel +// gclk_gen_6_div_sel #ifndef CONF_GCLK_GEN_6_DIVSEL #define CONF_GCLK_GEN_6_DIVSEL 0 #endif @@ -535,8 +535,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 6 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 6 division <0x0000-0xFFFF> // gclk_gen_6_div #ifndef CONF_GCLK_GEN_6_DIV #define CONF_GCLK_GEN_6_DIV 4 @@ -576,7 +576,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_7_div_sel +// gclk_gen_7_div_sel #ifndef CONF_GCLK_GEN_7_DIVSEL #define CONF_GCLK_GEN_7_DIVSEL 0 #endif @@ -610,8 +610,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 7 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 7 division <0x0000-0xFFFF> // gclk_gen_7_div #ifndef CONF_GCLK_GEN_7_DIV #define CONF_GCLK_GEN_7_DIV 1 @@ -651,7 +651,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_8_div_sel +// gclk_gen_8_div_sel #ifndef CONF_GCLK_GEN_8_DIVSEL #define CONF_GCLK_GEN_8_DIVSEL 0 #endif @@ -685,8 +685,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 8 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 8 division <0x0000-0xFFFF> // gclk_gen_8_div #ifndef CONF_GCLK_GEN_8_DIV #define CONF_GCLK_GEN_8_DIV 1 @@ -726,7 +726,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_9_div_sel +// gclk_gen_9_div_sel #ifndef CONF_GCLK_GEN_9_DIVSEL #define CONF_GCLK_GEN_9_DIVSEL 0 #endif @@ -760,8 +760,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 9 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 9 division <0x0000-0xFFFF> // gclk_gen_9_div #ifndef CONF_GCLK_GEN_9_DIV #define CONF_GCLK_GEN_9_DIV 1 @@ -801,7 +801,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_10_div_sel +// gclk_gen_10_div_sel #ifndef CONF_GCLK_GEN_10_DIVSEL #define CONF_GCLK_GEN_10_DIVSEL 0 #endif @@ -835,8 +835,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 10 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 10 division <0x0000-0xFFFF> // gclk_gen_10_div #ifndef CONF_GCLK_GEN_10_DIV #define CONF_GCLK_GEN_10_DIV 1 @@ -876,7 +876,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_11_div_sel +// gclk_gen_11_div_sel #ifndef CONF_GCLK_GEN_11_DIVSEL #define CONF_GCLK_GEN_11_DIVSEL 0 #endif @@ -910,8 +910,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 11 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 11 division <0x0000-0xFFFF> // gclk_gen_11_div #ifndef CONF_GCLK_GEN_11_DIV #define CONF_GCLK_GEN_11_DIV 1 diff --git a/ports/atmel-samd/asf4_conf/samd51/hpl_oscctrl_config.h b/ports/atmel-samd/asf4_conf/samd51/hpl_oscctrl_config.h index cd11866059..f7f79fada1 100644 --- a/ports/atmel-samd/asf4_conf/samd51/hpl_oscctrl_config.h +++ b/ports/atmel-samd/asf4_conf/samd51/hpl_oscctrl_config.h @@ -96,8 +96,8 @@ #ifndef CONF_XOSC0_XTALEN #define CONF_XOSC0_XTALEN 0 #endif -// -// +// +// #if CONF_XOSC0_FREQUENCY >= 32000000 #define CONF_XOSC0_CFDPRESC 0x0 @@ -209,8 +209,8 @@ #ifndef CONF_XOSC1_XTALEN #define CONF_XOSC1_XTALEN 0 #endif -// -// +// +// #if CONF_XOSC1_FREQUENCY >= 32000000 #define CONF_XOSC1_CFDPRESC 0x0 @@ -372,11 +372,11 @@ #define CONF_DFLL_FINE (0x80) #endif -// +// -// +// -// +// // FDPLL0 Configuration // Indicates whether configuration for FDPLL0 is enabled or not @@ -501,8 +501,8 @@ #define CONF_FDPLL0_FILTER 0x0 #endif -// -// +// +// // FDPLL1 Configuration // Indicates whether configuration for FDPLL1 is enabled or not // enable_fdpll1 @@ -626,8 +626,8 @@ #define CONF_FDPLL1_FILTER 0x0 #endif -// -// +// +// // <<< end of configuration section >>> diff --git a/ports/atmel-samd/asf4_conf/samd51/hpl_sercom_config.h b/ports/atmel-samd/asf4_conf/samd51/hpl_sercom_config.h index cd411154c7..b438619773 100644 --- a/ports/atmel-samd/asf4_conf/samd51/hpl_sercom_config.h +++ b/ports/atmel-samd/asf4_conf/samd51/hpl_sercom_config.h @@ -294,12 +294,12 @@ // BAUD: register value low [7:0] // BAUDLOW: register value high [15:8], only used for odd BAUD + BAUDLOW #define CONF_SERCOM_1_I2CM_BAUD_BAUDLOW \ - (((CONF_GCLK_SERCOM1_CORE_FREQUENCY - (CONF_SERCOM_1_I2CM_BAUD * 10) \ - - (CONF_SERCOM_1_I2CM_TRISE * (CONF_SERCOM_1_I2CM_BAUD / 100) * (CONF_GCLK_SERCOM1_CORE_FREQUENCY / 10000) \ - / 1000)) \ - * 10 \ - + 5) \ - / (CONF_SERCOM_1_I2CM_BAUD * 10)) + (((CONF_GCLK_SERCOM1_CORE_FREQUENCY - (CONF_SERCOM_1_I2CM_BAUD * 10) \ + - (CONF_SERCOM_1_I2CM_TRISE * (CONF_SERCOM_1_I2CM_BAUD / 100) * (CONF_GCLK_SERCOM1_CORE_FREQUENCY / 10000) \ + / 1000)) \ + * 10 \ + + 5) \ + / (CONF_SERCOM_1_I2CM_BAUD * 10)) #ifndef CONF_SERCOM_1_I2CM_BAUD_RATE #if CONF_SERCOM_1_I2CM_BAUD_BAUDLOW > (0xFF * 2) #warning Requested I2C baudrate too low, please check @@ -309,9 +309,9 @@ #define CONF_SERCOM_1_I2CM_BAUD_RATE 1 #else #define CONF_SERCOM_1_I2CM_BAUD_RATE \ - ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW & 0x1) \ - ? (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2 + 1) << 8) \ - : (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2)) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW & 0x1) \ + ? (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2 + 1) << 8) \ + : (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2)) #endif #endif @@ -525,7 +525,7 @@ #if CONF_SERCOM_2_USART_SAMPR == 0 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 16.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 16.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -533,7 +533,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 1 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 16)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) + ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 16)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -541,7 +541,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 2 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 8.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 8.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -549,7 +549,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 3 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 8)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) + ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 8)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -557,7 +557,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 4 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 3.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 3.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -571,9 +571,9 @@ #define CONF_SERCOM_3_SPI_ENABLE 1 #endif -// SPI DMA TX Channel <0-32> -// This defines DMA channel to be used -// spi_master_dma_tx_channel +// SPI DMA TX Channel <0-32> +// This defines DMA channel to be used +// spi_master_dma_tx_channel #ifndef CONF_SERCOM_3_SPI_M_DMA_TX_CHANNEL #define CONF_SERCOM_3_SPI_M_DMA_TX_CHANNEL 0 #endif @@ -584,9 +584,9 @@ #define CONF_SERCOM_3_SPI_RX_CHANNEL 1 #endif -// DMA Channel <0-32> -// This defines DMA channel to be used -// spi_master_dma_rx_channel +// DMA Channel <0-32> +// This defines DMA channel to be used +// spi_master_dma_rx_channel #ifndef CONF_SERCOM_3_SPI_M_DMA_RX_CHANNEL #define CONF_SERCOM_3_SPI_M_DMA_RX_CHANNEL 1 #endif diff --git a/ports/atmel-samd/asf4_conf/samd51/hpl_tc_config.h b/ports/atmel-samd/asf4_conf/samd51/hpl_tc_config.h index 38d48e9b67..3bc688295b 100644 --- a/ports/atmel-samd/asf4_conf/samd51/hpl_tc_config.h +++ b/ports/atmel-samd/asf4_conf/samd51/hpl_tc_config.h @@ -45,7 +45,7 @@ /* Caculate pwm ccx register value based on WAVE_PER_VAL and Waveform Duty Value */ #if CONF_TC0_PRESCALER < TC_CTRLA_PRESCALER_DIV64_Val #define CONF_TC0_CC0 \ - ((uint32_t)(((double)CONF_TC0_WAVE_PER_VAL * CONF_GCLK_TC0_FREQUENCY) / 1000000 / (1 << CONF_TC0_PRESCALER) - 1)) + ((uint32_t)(((double)CONF_TC0_WAVE_PER_VAL * CONF_GCLK_TC0_FREQUENCY) / 1000000 / (1 << CONF_TC0_PRESCALER) - 1)) #define CONF_TC0_CC1 ((CONF_TC0_CC0 * CONF_TC0_WAVE_DUTY_VAL) / 1000) #elif CONF_TC0_PRESCALER == TC_CTRLA_PRESCALER_DIV64_Val @@ -114,15 +114,15 @@ #endif /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_CAPTEN0 0 -//#define CONF_TC0_CAPTEN1 0 -//#define CONF_TC0_COPEN0 0 -//#define CONF_TC0_COPEN1 0 +// #define CONF_TC0_CAPTEN0 0 +// #define CONF_TC0_CAPTEN1 0 +// #define CONF_TC0_COPEN0 0 +// #define CONF_TC0_COPEN1 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_DIR 0 -//#define CONF_TC0_ONESHOT 0 -//#define CONF_TC0_LUPD 0 +// #define CONF_TC0_DIR 0 +// #define CONF_TC0_ONESHOT 0 +// #define CONF_TC0_LUPD 0 // Debug Running Mode // Indicates whether the Debug Running Mode is enabled or not @@ -182,25 +182,25 @@ // <6=> Period captured in CC1, pulse width in CC0 // <7=> Pulse width capture // Event which will be performed on an event -// tc_arch_evact +// tc_arch_evact #ifndef CONF_TC0_EVACT #define CONF_TC0_EVACT 0 #endif // /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_WAVEGEN TC_CTRLA_WAVEGEN_MFRQ_Val +// #define CONF_TC0_WAVEGEN TC_CTRLA_WAVEGEN_MFRQ_Val /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_INVEN0 0 -//#define CONF_TC0_INVEN1 0 +// #define CONF_TC0_INVEN0 0 +// #define CONF_TC0_INVEN1 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_PERBUF 0 +// #define CONF_TC0_PERBUF 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_CCBUF0 0 -//#define CONF_TC0_CCBUF1 0 +// #define CONF_TC0_CCBUF0 0 +// #define CONF_TC0_CCBUF1 0 // diff --git a/ports/atmel-samd/asf4_conf/samd51/usbd_config.h b/ports/atmel-samd/asf4_conf/samd51/usbd_config.h index be1fa3c9e0..b2629e1239 100644 --- a/ports/atmel-samd/asf4_conf/samd51/usbd_config.h +++ b/ports/atmel-samd/asf4_conf/samd51/usbd_config.h @@ -101,7 +101,7 @@ #ifndef CONF_USB_COMPOSITE_IPRODUCT #define CONF_USB_COMPOSITE_IPRODUCT \ - (CONF_USB_COMPOSITE_IPRODUCT_EN * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN)) + (CONF_USB_COMPOSITE_IPRODUCT_EN * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN)) #endif // Unicode string of iProduct @@ -124,8 +124,8 @@ #ifndef CONF_USB_COMPOSITE_ISERIALNUM #define CONF_USB_COMPOSITE_ISERIALNUM \ - (CONF_USB_COMPOSITE_ISERIALNUM_EN \ - * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN)) + (CONF_USB_COMPOSITE_ISERIALNUM_EN \ + * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN)) #endif // Unicode string of iSerialNum @@ -162,9 +162,9 @@ #ifndef CONF_USB_COMPOSITE_ICONFIG #define CONF_USB_COMPOSITE_ICONFIG \ - (CONF_USB_COMPOSITE_ICONFIG_EN \ - * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN \ - + CONF_USB_COMPOSITE_ICONFIG_EN)) + (CONF_USB_COMPOSITE_ICONFIG_EN \ + * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN \ + + CONF_USB_COMPOSITE_ICONFIG_EN)) #endif // Unicode string of iConfig @@ -453,9 +453,9 @@ #ifndef CONF_USB_COMPOSITE_HID_GENERIC_REPORT #define CONF_USB_COMPOSITE_HID_GENERIC_REPORT \ - 0x06, 0xFF, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, \ - 0x40, 0x81, 0x02, 0x09, 0x04, 0x09, 0x05, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, \ - 0x09, 0x06, 0x09, 0x07, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0xB1, 0x02, 0xC0 + 0x06, 0xFF, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, \ + 0x40, 0x81, 0x02, 0x09, 0x04, 0x09, 0x05, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, \ + 0x09, 0x06, 0x09, 0x07, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0xB1, 0x02, 0xC0 #endif // HID Generic INTERRUPT IN Endpoint Address @@ -650,7 +650,7 @@ #ifndef CONF_USB_MSC_LUN0_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN0_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN0_CAPACITY * 1024 / CONF_USB_MSC_LUN0_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN0_CAPACITY * 1024 / CONF_USB_MSC_LUN0_BLOCK_SIZE - 1) #endif // @@ -713,7 +713,7 @@ #ifndef CONF_USB_MSC_LUN1_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN1_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN1_CAPACITY * 1024 / CONF_USB_MSC_LUN1_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN1_CAPACITY * 1024 / CONF_USB_MSC_LUN1_BLOCK_SIZE - 1) #endif // @@ -775,7 +775,7 @@ #ifndef CONF_USB_MSC_LUN2_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN2_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN2_CAPACITY * 1024 / CONF_USB_MSC_LUN2_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN2_CAPACITY * 1024 / CONF_USB_MSC_LUN2_BLOCK_SIZE - 1) #endif // @@ -837,7 +837,7 @@ #ifndef CONF_USB_MSC_LUN3_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN3_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN3_CAPACITY * 1024 / CONF_USB_MSC_LUN3_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN3_CAPACITY * 1024 / CONF_USB_MSC_LUN3_BLOCK_SIZE - 1) #endif // diff --git a/ports/atmel-samd/asf4_conf/same51/hpl_gclk_config.h b/ports/atmel-samd/asf4_conf/same51/hpl_gclk_config.h index 6f4f01a7e6..1dda85a693 100644 --- a/ports/atmel-samd/asf4_conf/same51/hpl_gclk_config.h +++ b/ports/atmel-samd/asf4_conf/same51/hpl_gclk_config.h @@ -11,7 +11,7 @@ // Used in hpl/core/hpl_init.c to define which clocks should be initialized first. // Not clear why all these need to be specified, but it doesn't work properly otherwise. -//#define CIRCUITPY_GCLK_INIT_1ST (1 << 0 | 1 << 1 | 1 << 3 | 1 <<5) +// #define CIRCUITPY_GCLK_INIT_1ST (1 << 0 | 1 << 1 | 1 << 3 | 1 <<5) #define CIRCUITPY_GCLK_INIT_1ST 0xffff /* Auto-generated config file hpl_gclk_config.h */ @@ -52,7 +52,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_0_div_sel +// gclk_gen_0_div_sel #ifndef CONF_GCLK_GEN_0_DIVSEL #define CONF_GCLK_GEN_0_DIVSEL 0 #endif @@ -86,8 +86,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 0 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 0 division <0x0000-0xFFFF> // gclk_gen_0_div #ifndef CONF_GCLK_GEN_0_DIV #define CONF_GCLK_GEN_0_DIV 1 @@ -126,7 +126,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_1_div_sel +// gclk_gen_1_div_sel #ifndef CONF_GCLK_GEN_1_DIVSEL #define CONF_GCLK_GEN_1_DIVSEL 0 #endif @@ -160,8 +160,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 1 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 1 division <0x0000-0xFFFF> // gclk_gen_1_div #ifndef CONF_GCLK_GEN_1_DIV #define CONF_GCLK_GEN_1_DIV 1 @@ -201,7 +201,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_2_div_sel +// gclk_gen_2_div_sel #ifndef CONF_GCLK_GEN_2_DIVSEL #define CONF_GCLK_GEN_2_DIVSEL 1 #endif @@ -235,8 +235,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 2 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 2 division <0x0000-0xFFFF> // gclk_gen_2_div #ifndef CONF_GCLK_GEN_2_DIV #define CONF_GCLK_GEN_2_DIV 4 @@ -276,7 +276,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_3_div_sel +// gclk_gen_3_div_sel #ifndef CONF_GCLK_GEN_3_DIVSEL #define CONF_GCLK_GEN_3_DIVSEL 0 #endif @@ -310,8 +310,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 3 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 3 division <0x0000-0xFFFF> // gclk_gen_3_div #ifndef CONF_GCLK_GEN_3_DIV #define CONF_GCLK_GEN_3_DIV 1 @@ -351,7 +351,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_4_div_sel +// gclk_gen_4_div_sel #ifndef CONF_GCLK_GEN_4_DIVSEL #define CONF_GCLK_GEN_4_DIVSEL 0 #endif @@ -385,8 +385,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 4 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 4 division <0x0000-0xFFFF> // gclk_gen_4_div #ifndef CONF_GCLK_GEN_4_DIV #define CONF_GCLK_GEN_4_DIV 1 @@ -426,7 +426,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_5_div_sel +// gclk_gen_5_div_sel #ifndef CONF_GCLK_GEN_5_DIVSEL #define CONF_GCLK_GEN_5_DIVSEL 0 #endif @@ -460,8 +460,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 5 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 5 division <0x0000-0xFFFF> // gclk_gen_5_div #ifndef CONF_GCLK_GEN_5_DIV #define CONF_GCLK_GEN_5_DIV 24 @@ -501,7 +501,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_6_div_sel +// gclk_gen_6_div_sel #ifndef CONF_GCLK_GEN_6_DIVSEL #define CONF_GCLK_GEN_6_DIVSEL 0 #endif @@ -535,8 +535,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 6 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 6 division <0x0000-0xFFFF> // gclk_gen_6_div #ifndef CONF_GCLK_GEN_6_DIV #define CONF_GCLK_GEN_6_DIV 4 @@ -576,7 +576,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_7_div_sel +// gclk_gen_7_div_sel #ifndef CONF_GCLK_GEN_7_DIVSEL #define CONF_GCLK_GEN_7_DIVSEL 0 #endif @@ -610,8 +610,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 7 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 7 division <0x0000-0xFFFF> // gclk_gen_7_div #ifndef CONF_GCLK_GEN_7_DIV #define CONF_GCLK_GEN_7_DIV 1 @@ -651,7 +651,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_8_div_sel +// gclk_gen_8_div_sel #ifndef CONF_GCLK_GEN_8_DIVSEL #define CONF_GCLK_GEN_8_DIVSEL 0 #endif @@ -685,8 +685,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 8 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 8 division <0x0000-0xFFFF> // gclk_gen_8_div #ifndef CONF_GCLK_GEN_8_DIV #define CONF_GCLK_GEN_8_DIV 1 @@ -726,7 +726,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_9_div_sel +// gclk_gen_9_div_sel #ifndef CONF_GCLK_GEN_9_DIVSEL #define CONF_GCLK_GEN_9_DIVSEL 0 #endif @@ -760,8 +760,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 9 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 9 division <0x0000-0xFFFF> // gclk_gen_9_div #ifndef CONF_GCLK_GEN_9_DIV #define CONF_GCLK_GEN_9_DIV 1 @@ -801,7 +801,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_10_div_sel +// gclk_gen_10_div_sel #ifndef CONF_GCLK_GEN_10_DIVSEL #define CONF_GCLK_GEN_10_DIVSEL 0 #endif @@ -835,8 +835,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 10 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 10 division <0x0000-0xFFFF> // gclk_gen_10_div #ifndef CONF_GCLK_GEN_10_DIV #define CONF_GCLK_GEN_10_DIV 1 @@ -876,7 +876,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_11_div_sel +// gclk_gen_11_div_sel #ifndef CONF_GCLK_GEN_11_DIVSEL #define CONF_GCLK_GEN_11_DIVSEL 0 #endif @@ -910,8 +910,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 11 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 11 division <0x0000-0xFFFF> // gclk_gen_11_div #ifndef CONF_GCLK_GEN_11_DIV #define CONF_GCLK_GEN_11_DIV 1 diff --git a/ports/atmel-samd/asf4_conf/same51/hpl_oscctrl_config.h b/ports/atmel-samd/asf4_conf/same51/hpl_oscctrl_config.h index cd11866059..f7f79fada1 100644 --- a/ports/atmel-samd/asf4_conf/same51/hpl_oscctrl_config.h +++ b/ports/atmel-samd/asf4_conf/same51/hpl_oscctrl_config.h @@ -96,8 +96,8 @@ #ifndef CONF_XOSC0_XTALEN #define CONF_XOSC0_XTALEN 0 #endif -// -// +// +// #if CONF_XOSC0_FREQUENCY >= 32000000 #define CONF_XOSC0_CFDPRESC 0x0 @@ -209,8 +209,8 @@ #ifndef CONF_XOSC1_XTALEN #define CONF_XOSC1_XTALEN 0 #endif -// -// +// +// #if CONF_XOSC1_FREQUENCY >= 32000000 #define CONF_XOSC1_CFDPRESC 0x0 @@ -372,11 +372,11 @@ #define CONF_DFLL_FINE (0x80) #endif -// +// -// +// -// +// // FDPLL0 Configuration // Indicates whether configuration for FDPLL0 is enabled or not @@ -501,8 +501,8 @@ #define CONF_FDPLL0_FILTER 0x0 #endif -// -// +// +// // FDPLL1 Configuration // Indicates whether configuration for FDPLL1 is enabled or not // enable_fdpll1 @@ -626,8 +626,8 @@ #define CONF_FDPLL1_FILTER 0x0 #endif -// -// +// +// // <<< end of configuration section >>> diff --git a/ports/atmel-samd/asf4_conf/same51/hpl_sercom_config.h b/ports/atmel-samd/asf4_conf/same51/hpl_sercom_config.h index cd411154c7..b438619773 100644 --- a/ports/atmel-samd/asf4_conf/same51/hpl_sercom_config.h +++ b/ports/atmel-samd/asf4_conf/same51/hpl_sercom_config.h @@ -294,12 +294,12 @@ // BAUD: register value low [7:0] // BAUDLOW: register value high [15:8], only used for odd BAUD + BAUDLOW #define CONF_SERCOM_1_I2CM_BAUD_BAUDLOW \ - (((CONF_GCLK_SERCOM1_CORE_FREQUENCY - (CONF_SERCOM_1_I2CM_BAUD * 10) \ - - (CONF_SERCOM_1_I2CM_TRISE * (CONF_SERCOM_1_I2CM_BAUD / 100) * (CONF_GCLK_SERCOM1_CORE_FREQUENCY / 10000) \ - / 1000)) \ - * 10 \ - + 5) \ - / (CONF_SERCOM_1_I2CM_BAUD * 10)) + (((CONF_GCLK_SERCOM1_CORE_FREQUENCY - (CONF_SERCOM_1_I2CM_BAUD * 10) \ + - (CONF_SERCOM_1_I2CM_TRISE * (CONF_SERCOM_1_I2CM_BAUD / 100) * (CONF_GCLK_SERCOM1_CORE_FREQUENCY / 10000) \ + / 1000)) \ + * 10 \ + + 5) \ + / (CONF_SERCOM_1_I2CM_BAUD * 10)) #ifndef CONF_SERCOM_1_I2CM_BAUD_RATE #if CONF_SERCOM_1_I2CM_BAUD_BAUDLOW > (0xFF * 2) #warning Requested I2C baudrate too low, please check @@ -309,9 +309,9 @@ #define CONF_SERCOM_1_I2CM_BAUD_RATE 1 #else #define CONF_SERCOM_1_I2CM_BAUD_RATE \ - ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW & 0x1) \ - ? (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2 + 1) << 8) \ - : (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2)) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW & 0x1) \ + ? (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2 + 1) << 8) \ + : (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2)) #endif #endif @@ -525,7 +525,7 @@ #if CONF_SERCOM_2_USART_SAMPR == 0 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 16.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 16.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -533,7 +533,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 1 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 16)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) + ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 16)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -541,7 +541,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 2 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 8.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 8.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -549,7 +549,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 3 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 8)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) + ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 8)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -557,7 +557,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 4 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 3.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 3.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -571,9 +571,9 @@ #define CONF_SERCOM_3_SPI_ENABLE 1 #endif -// SPI DMA TX Channel <0-32> -// This defines DMA channel to be used -// spi_master_dma_tx_channel +// SPI DMA TX Channel <0-32> +// This defines DMA channel to be used +// spi_master_dma_tx_channel #ifndef CONF_SERCOM_3_SPI_M_DMA_TX_CHANNEL #define CONF_SERCOM_3_SPI_M_DMA_TX_CHANNEL 0 #endif @@ -584,9 +584,9 @@ #define CONF_SERCOM_3_SPI_RX_CHANNEL 1 #endif -// DMA Channel <0-32> -// This defines DMA channel to be used -// spi_master_dma_rx_channel +// DMA Channel <0-32> +// This defines DMA channel to be used +// spi_master_dma_rx_channel #ifndef CONF_SERCOM_3_SPI_M_DMA_RX_CHANNEL #define CONF_SERCOM_3_SPI_M_DMA_RX_CHANNEL 1 #endif diff --git a/ports/atmel-samd/asf4_conf/same51/hpl_tc_config.h b/ports/atmel-samd/asf4_conf/same51/hpl_tc_config.h index 38d48e9b67..3bc688295b 100644 --- a/ports/atmel-samd/asf4_conf/same51/hpl_tc_config.h +++ b/ports/atmel-samd/asf4_conf/same51/hpl_tc_config.h @@ -45,7 +45,7 @@ /* Caculate pwm ccx register value based on WAVE_PER_VAL and Waveform Duty Value */ #if CONF_TC0_PRESCALER < TC_CTRLA_PRESCALER_DIV64_Val #define CONF_TC0_CC0 \ - ((uint32_t)(((double)CONF_TC0_WAVE_PER_VAL * CONF_GCLK_TC0_FREQUENCY) / 1000000 / (1 << CONF_TC0_PRESCALER) - 1)) + ((uint32_t)(((double)CONF_TC0_WAVE_PER_VAL * CONF_GCLK_TC0_FREQUENCY) / 1000000 / (1 << CONF_TC0_PRESCALER) - 1)) #define CONF_TC0_CC1 ((CONF_TC0_CC0 * CONF_TC0_WAVE_DUTY_VAL) / 1000) #elif CONF_TC0_PRESCALER == TC_CTRLA_PRESCALER_DIV64_Val @@ -114,15 +114,15 @@ #endif /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_CAPTEN0 0 -//#define CONF_TC0_CAPTEN1 0 -//#define CONF_TC0_COPEN0 0 -//#define CONF_TC0_COPEN1 0 +// #define CONF_TC0_CAPTEN0 0 +// #define CONF_TC0_CAPTEN1 0 +// #define CONF_TC0_COPEN0 0 +// #define CONF_TC0_COPEN1 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_DIR 0 -//#define CONF_TC0_ONESHOT 0 -//#define CONF_TC0_LUPD 0 +// #define CONF_TC0_DIR 0 +// #define CONF_TC0_ONESHOT 0 +// #define CONF_TC0_LUPD 0 // Debug Running Mode // Indicates whether the Debug Running Mode is enabled or not @@ -182,25 +182,25 @@ // <6=> Period captured in CC1, pulse width in CC0 // <7=> Pulse width capture // Event which will be performed on an event -// tc_arch_evact +// tc_arch_evact #ifndef CONF_TC0_EVACT #define CONF_TC0_EVACT 0 #endif // /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_WAVEGEN TC_CTRLA_WAVEGEN_MFRQ_Val +// #define CONF_TC0_WAVEGEN TC_CTRLA_WAVEGEN_MFRQ_Val /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_INVEN0 0 -//#define CONF_TC0_INVEN1 0 +// #define CONF_TC0_INVEN0 0 +// #define CONF_TC0_INVEN1 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_PERBUF 0 +// #define CONF_TC0_PERBUF 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_CCBUF0 0 -//#define CONF_TC0_CCBUF1 0 +// #define CONF_TC0_CCBUF0 0 +// #define CONF_TC0_CCBUF1 0 // diff --git a/ports/atmel-samd/asf4_conf/same51/usbd_config.h b/ports/atmel-samd/asf4_conf/same51/usbd_config.h index be1fa3c9e0..b2629e1239 100644 --- a/ports/atmel-samd/asf4_conf/same51/usbd_config.h +++ b/ports/atmel-samd/asf4_conf/same51/usbd_config.h @@ -101,7 +101,7 @@ #ifndef CONF_USB_COMPOSITE_IPRODUCT #define CONF_USB_COMPOSITE_IPRODUCT \ - (CONF_USB_COMPOSITE_IPRODUCT_EN * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN)) + (CONF_USB_COMPOSITE_IPRODUCT_EN * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN)) #endif // Unicode string of iProduct @@ -124,8 +124,8 @@ #ifndef CONF_USB_COMPOSITE_ISERIALNUM #define CONF_USB_COMPOSITE_ISERIALNUM \ - (CONF_USB_COMPOSITE_ISERIALNUM_EN \ - * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN)) + (CONF_USB_COMPOSITE_ISERIALNUM_EN \ + * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN)) #endif // Unicode string of iSerialNum @@ -162,9 +162,9 @@ #ifndef CONF_USB_COMPOSITE_ICONFIG #define CONF_USB_COMPOSITE_ICONFIG \ - (CONF_USB_COMPOSITE_ICONFIG_EN \ - * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN \ - + CONF_USB_COMPOSITE_ICONFIG_EN)) + (CONF_USB_COMPOSITE_ICONFIG_EN \ + * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN \ + + CONF_USB_COMPOSITE_ICONFIG_EN)) #endif // Unicode string of iConfig @@ -453,9 +453,9 @@ #ifndef CONF_USB_COMPOSITE_HID_GENERIC_REPORT #define CONF_USB_COMPOSITE_HID_GENERIC_REPORT \ - 0x06, 0xFF, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, \ - 0x40, 0x81, 0x02, 0x09, 0x04, 0x09, 0x05, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, \ - 0x09, 0x06, 0x09, 0x07, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0xB1, 0x02, 0xC0 + 0x06, 0xFF, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, \ + 0x40, 0x81, 0x02, 0x09, 0x04, 0x09, 0x05, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, \ + 0x09, 0x06, 0x09, 0x07, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0xB1, 0x02, 0xC0 #endif // HID Generic INTERRUPT IN Endpoint Address @@ -650,7 +650,7 @@ #ifndef CONF_USB_MSC_LUN0_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN0_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN0_CAPACITY * 1024 / CONF_USB_MSC_LUN0_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN0_CAPACITY * 1024 / CONF_USB_MSC_LUN0_BLOCK_SIZE - 1) #endif // @@ -713,7 +713,7 @@ #ifndef CONF_USB_MSC_LUN1_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN1_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN1_CAPACITY * 1024 / CONF_USB_MSC_LUN1_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN1_CAPACITY * 1024 / CONF_USB_MSC_LUN1_BLOCK_SIZE - 1) #endif // @@ -775,7 +775,7 @@ #ifndef CONF_USB_MSC_LUN2_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN2_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN2_CAPACITY * 1024 / CONF_USB_MSC_LUN2_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN2_CAPACITY * 1024 / CONF_USB_MSC_LUN2_BLOCK_SIZE - 1) #endif // @@ -837,7 +837,7 @@ #ifndef CONF_USB_MSC_LUN3_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN3_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN3_CAPACITY * 1024 / CONF_USB_MSC_LUN3_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN3_CAPACITY * 1024 / CONF_USB_MSC_LUN3_BLOCK_SIZE - 1) #endif // diff --git a/ports/atmel-samd/asf4_conf/same54/hpl_gclk_config.h b/ports/atmel-samd/asf4_conf/same54/hpl_gclk_config.h index 6f4f01a7e6..1dda85a693 100644 --- a/ports/atmel-samd/asf4_conf/same54/hpl_gclk_config.h +++ b/ports/atmel-samd/asf4_conf/same54/hpl_gclk_config.h @@ -11,7 +11,7 @@ // Used in hpl/core/hpl_init.c to define which clocks should be initialized first. // Not clear why all these need to be specified, but it doesn't work properly otherwise. -//#define CIRCUITPY_GCLK_INIT_1ST (1 << 0 | 1 << 1 | 1 << 3 | 1 <<5) +// #define CIRCUITPY_GCLK_INIT_1ST (1 << 0 | 1 << 1 | 1 << 3 | 1 <<5) #define CIRCUITPY_GCLK_INIT_1ST 0xffff /* Auto-generated config file hpl_gclk_config.h */ @@ -52,7 +52,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_0_div_sel +// gclk_gen_0_div_sel #ifndef CONF_GCLK_GEN_0_DIVSEL #define CONF_GCLK_GEN_0_DIVSEL 0 #endif @@ -86,8 +86,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 0 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 0 division <0x0000-0xFFFF> // gclk_gen_0_div #ifndef CONF_GCLK_GEN_0_DIV #define CONF_GCLK_GEN_0_DIV 1 @@ -126,7 +126,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_1_div_sel +// gclk_gen_1_div_sel #ifndef CONF_GCLK_GEN_1_DIVSEL #define CONF_GCLK_GEN_1_DIVSEL 0 #endif @@ -160,8 +160,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 1 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 1 division <0x0000-0xFFFF> // gclk_gen_1_div #ifndef CONF_GCLK_GEN_1_DIV #define CONF_GCLK_GEN_1_DIV 1 @@ -201,7 +201,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_2_div_sel +// gclk_gen_2_div_sel #ifndef CONF_GCLK_GEN_2_DIVSEL #define CONF_GCLK_GEN_2_DIVSEL 1 #endif @@ -235,8 +235,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 2 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 2 division <0x0000-0xFFFF> // gclk_gen_2_div #ifndef CONF_GCLK_GEN_2_DIV #define CONF_GCLK_GEN_2_DIV 4 @@ -276,7 +276,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_3_div_sel +// gclk_gen_3_div_sel #ifndef CONF_GCLK_GEN_3_DIVSEL #define CONF_GCLK_GEN_3_DIVSEL 0 #endif @@ -310,8 +310,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 3 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 3 division <0x0000-0xFFFF> // gclk_gen_3_div #ifndef CONF_GCLK_GEN_3_DIV #define CONF_GCLK_GEN_3_DIV 1 @@ -351,7 +351,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_4_div_sel +// gclk_gen_4_div_sel #ifndef CONF_GCLK_GEN_4_DIVSEL #define CONF_GCLK_GEN_4_DIVSEL 0 #endif @@ -385,8 +385,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 4 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 4 division <0x0000-0xFFFF> // gclk_gen_4_div #ifndef CONF_GCLK_GEN_4_DIV #define CONF_GCLK_GEN_4_DIV 1 @@ -426,7 +426,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_5_div_sel +// gclk_gen_5_div_sel #ifndef CONF_GCLK_GEN_5_DIVSEL #define CONF_GCLK_GEN_5_DIVSEL 0 #endif @@ -460,8 +460,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 5 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 5 division <0x0000-0xFFFF> // gclk_gen_5_div #ifndef CONF_GCLK_GEN_5_DIV #define CONF_GCLK_GEN_5_DIV 24 @@ -501,7 +501,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_6_div_sel +// gclk_gen_6_div_sel #ifndef CONF_GCLK_GEN_6_DIVSEL #define CONF_GCLK_GEN_6_DIVSEL 0 #endif @@ -535,8 +535,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 6 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 6 division <0x0000-0xFFFF> // gclk_gen_6_div #ifndef CONF_GCLK_GEN_6_DIV #define CONF_GCLK_GEN_6_DIV 4 @@ -576,7 +576,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_7_div_sel +// gclk_gen_7_div_sel #ifndef CONF_GCLK_GEN_7_DIVSEL #define CONF_GCLK_GEN_7_DIVSEL 0 #endif @@ -610,8 +610,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 7 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 7 division <0x0000-0xFFFF> // gclk_gen_7_div #ifndef CONF_GCLK_GEN_7_DIV #define CONF_GCLK_GEN_7_DIV 1 @@ -651,7 +651,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_8_div_sel +// gclk_gen_8_div_sel #ifndef CONF_GCLK_GEN_8_DIVSEL #define CONF_GCLK_GEN_8_DIVSEL 0 #endif @@ -685,8 +685,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 8 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 8 division <0x0000-0xFFFF> // gclk_gen_8_div #ifndef CONF_GCLK_GEN_8_DIV #define CONF_GCLK_GEN_8_DIV 1 @@ -726,7 +726,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_9_div_sel +// gclk_gen_9_div_sel #ifndef CONF_GCLK_GEN_9_DIVSEL #define CONF_GCLK_GEN_9_DIVSEL 0 #endif @@ -760,8 +760,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 9 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 9 division <0x0000-0xFFFF> // gclk_gen_9_div #ifndef CONF_GCLK_GEN_9_DIV #define CONF_GCLK_GEN_9_DIV 1 @@ -801,7 +801,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_10_div_sel +// gclk_gen_10_div_sel #ifndef CONF_GCLK_GEN_10_DIVSEL #define CONF_GCLK_GEN_10_DIVSEL 0 #endif @@ -835,8 +835,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 10 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 10 division <0x0000-0xFFFF> // gclk_gen_10_div #ifndef CONF_GCLK_GEN_10_DIV #define CONF_GCLK_GEN_10_DIV 1 @@ -876,7 +876,7 @@ // Divide Selection // Indicates whether Divide Selection is enabled or not -// gclk_gen_11_div_sel +// gclk_gen_11_div_sel #ifndef CONF_GCLK_GEN_11_DIVSEL #define CONF_GCLK_GEN_11_DIVSEL 0 #endif @@ -910,8 +910,8 @@ #endif // -// Generic Clock Generator Division -// Generic clock generator 11 division <0x0000-0xFFFF> +// Generic Clock Generator Division +// Generic clock generator 11 division <0x0000-0xFFFF> // gclk_gen_11_div #ifndef CONF_GCLK_GEN_11_DIV #define CONF_GCLK_GEN_11_DIV 1 diff --git a/ports/atmel-samd/asf4_conf/same54/hpl_oscctrl_config.h b/ports/atmel-samd/asf4_conf/same54/hpl_oscctrl_config.h index cd11866059..f7f79fada1 100644 --- a/ports/atmel-samd/asf4_conf/same54/hpl_oscctrl_config.h +++ b/ports/atmel-samd/asf4_conf/same54/hpl_oscctrl_config.h @@ -96,8 +96,8 @@ #ifndef CONF_XOSC0_XTALEN #define CONF_XOSC0_XTALEN 0 #endif -// -// +// +// #if CONF_XOSC0_FREQUENCY >= 32000000 #define CONF_XOSC0_CFDPRESC 0x0 @@ -209,8 +209,8 @@ #ifndef CONF_XOSC1_XTALEN #define CONF_XOSC1_XTALEN 0 #endif -// -// +// +// #if CONF_XOSC1_FREQUENCY >= 32000000 #define CONF_XOSC1_CFDPRESC 0x0 @@ -372,11 +372,11 @@ #define CONF_DFLL_FINE (0x80) #endif -// +// -// +// -// +// // FDPLL0 Configuration // Indicates whether configuration for FDPLL0 is enabled or not @@ -501,8 +501,8 @@ #define CONF_FDPLL0_FILTER 0x0 #endif -// -// +// +// // FDPLL1 Configuration // Indicates whether configuration for FDPLL1 is enabled or not // enable_fdpll1 @@ -626,8 +626,8 @@ #define CONF_FDPLL1_FILTER 0x0 #endif -// -// +// +// // <<< end of configuration section >>> diff --git a/ports/atmel-samd/asf4_conf/same54/hpl_sercom_config.h b/ports/atmel-samd/asf4_conf/same54/hpl_sercom_config.h index cd411154c7..b438619773 100644 --- a/ports/atmel-samd/asf4_conf/same54/hpl_sercom_config.h +++ b/ports/atmel-samd/asf4_conf/same54/hpl_sercom_config.h @@ -294,12 +294,12 @@ // BAUD: register value low [7:0] // BAUDLOW: register value high [15:8], only used for odd BAUD + BAUDLOW #define CONF_SERCOM_1_I2CM_BAUD_BAUDLOW \ - (((CONF_GCLK_SERCOM1_CORE_FREQUENCY - (CONF_SERCOM_1_I2CM_BAUD * 10) \ - - (CONF_SERCOM_1_I2CM_TRISE * (CONF_SERCOM_1_I2CM_BAUD / 100) * (CONF_GCLK_SERCOM1_CORE_FREQUENCY / 10000) \ - / 1000)) \ - * 10 \ - + 5) \ - / (CONF_SERCOM_1_I2CM_BAUD * 10)) + (((CONF_GCLK_SERCOM1_CORE_FREQUENCY - (CONF_SERCOM_1_I2CM_BAUD * 10) \ + - (CONF_SERCOM_1_I2CM_TRISE * (CONF_SERCOM_1_I2CM_BAUD / 100) * (CONF_GCLK_SERCOM1_CORE_FREQUENCY / 10000) \ + / 1000)) \ + * 10 \ + + 5) \ + / (CONF_SERCOM_1_I2CM_BAUD * 10)) #ifndef CONF_SERCOM_1_I2CM_BAUD_RATE #if CONF_SERCOM_1_I2CM_BAUD_BAUDLOW > (0xFF * 2) #warning Requested I2C baudrate too low, please check @@ -309,9 +309,9 @@ #define CONF_SERCOM_1_I2CM_BAUD_RATE 1 #else #define CONF_SERCOM_1_I2CM_BAUD_RATE \ - ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW & 0x1) \ - ? (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2 + 1) << 8) \ - : (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2)) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW & 0x1) \ + ? (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2) + ((CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2 + 1) << 8) \ + : (CONF_SERCOM_1_I2CM_BAUD_BAUDLOW / 2)) #endif #endif @@ -525,7 +525,7 @@ #if CONF_SERCOM_2_USART_SAMPR == 0 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 16.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 16.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -533,7 +533,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 1 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 16)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) + ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 16)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -541,7 +541,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 2 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 8.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 8.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -549,7 +549,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 3 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 8)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) + ((CONF_GCLK_SERCOM2_CORE_FREQUENCY) / (CONF_SERCOM_2_USART_BAUD * 8)) - (CONF_SERCOM_2_USART_FRACTIONAL / 8) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -557,7 +557,7 @@ #elif CONF_SERCOM_2_USART_SAMPR == 4 #ifndef CONF_SERCOM_2_USART_BAUD_RATE #define CONF_SERCOM_2_USART_BAUD_RATE \ - 65536 - ((65536 * 3.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) + 65536 - ((65536 * 3.0f * CONF_SERCOM_2_USART_BAUD) / CONF_GCLK_SERCOM2_CORE_FREQUENCY) #endif #ifndef CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH #define CONF_SERCOM_2_USART_RECEIVE_PULSE_LENGTH 0 @@ -571,9 +571,9 @@ #define CONF_SERCOM_3_SPI_ENABLE 1 #endif -// SPI DMA TX Channel <0-32> -// This defines DMA channel to be used -// spi_master_dma_tx_channel +// SPI DMA TX Channel <0-32> +// This defines DMA channel to be used +// spi_master_dma_tx_channel #ifndef CONF_SERCOM_3_SPI_M_DMA_TX_CHANNEL #define CONF_SERCOM_3_SPI_M_DMA_TX_CHANNEL 0 #endif @@ -584,9 +584,9 @@ #define CONF_SERCOM_3_SPI_RX_CHANNEL 1 #endif -// DMA Channel <0-32> -// This defines DMA channel to be used -// spi_master_dma_rx_channel +// DMA Channel <0-32> +// This defines DMA channel to be used +// spi_master_dma_rx_channel #ifndef CONF_SERCOM_3_SPI_M_DMA_RX_CHANNEL #define CONF_SERCOM_3_SPI_M_DMA_RX_CHANNEL 1 #endif diff --git a/ports/atmel-samd/asf4_conf/same54/hpl_tc_config.h b/ports/atmel-samd/asf4_conf/same54/hpl_tc_config.h index 38d48e9b67..3bc688295b 100644 --- a/ports/atmel-samd/asf4_conf/same54/hpl_tc_config.h +++ b/ports/atmel-samd/asf4_conf/same54/hpl_tc_config.h @@ -45,7 +45,7 @@ /* Caculate pwm ccx register value based on WAVE_PER_VAL and Waveform Duty Value */ #if CONF_TC0_PRESCALER < TC_CTRLA_PRESCALER_DIV64_Val #define CONF_TC0_CC0 \ - ((uint32_t)(((double)CONF_TC0_WAVE_PER_VAL * CONF_GCLK_TC0_FREQUENCY) / 1000000 / (1 << CONF_TC0_PRESCALER) - 1)) + ((uint32_t)(((double)CONF_TC0_WAVE_PER_VAL * CONF_GCLK_TC0_FREQUENCY) / 1000000 / (1 << CONF_TC0_PRESCALER) - 1)) #define CONF_TC0_CC1 ((CONF_TC0_CC0 * CONF_TC0_WAVE_DUTY_VAL) / 1000) #elif CONF_TC0_PRESCALER == TC_CTRLA_PRESCALER_DIV64_Val @@ -114,15 +114,15 @@ #endif /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_CAPTEN0 0 -//#define CONF_TC0_CAPTEN1 0 -//#define CONF_TC0_COPEN0 0 -//#define CONF_TC0_COPEN1 0 +// #define CONF_TC0_CAPTEN0 0 +// #define CONF_TC0_CAPTEN1 0 +// #define CONF_TC0_COPEN0 0 +// #define CONF_TC0_COPEN1 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_DIR 0 -//#define CONF_TC0_ONESHOT 0 -//#define CONF_TC0_LUPD 0 +// #define CONF_TC0_DIR 0 +// #define CONF_TC0_ONESHOT 0 +// #define CONF_TC0_LUPD 0 // Debug Running Mode // Indicates whether the Debug Running Mode is enabled or not @@ -182,25 +182,25 @@ // <6=> Period captured in CC1, pulse width in CC0 // <7=> Pulse width capture // Event which will be performed on an event -// tc_arch_evact +// tc_arch_evact #ifndef CONF_TC0_EVACT #define CONF_TC0_EVACT 0 #endif // /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_WAVEGEN TC_CTRLA_WAVEGEN_MFRQ_Val +// #define CONF_TC0_WAVEGEN TC_CTRLA_WAVEGEN_MFRQ_Val /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_INVEN0 0 -//#define CONF_TC0_INVEN1 0 +// #define CONF_TC0_INVEN0 0 +// #define CONF_TC0_INVEN1 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_PERBUF 0 +// #define CONF_TC0_PERBUF 0 /* Commented intentionally. Timer uses fixed value. May be used by other abstractions based on TC. */ -//#define CONF_TC0_CCBUF0 0 -//#define CONF_TC0_CCBUF1 0 +// #define CONF_TC0_CCBUF0 0 +// #define CONF_TC0_CCBUF1 0 // diff --git a/ports/atmel-samd/asf4_conf/same54/usbd_config.h b/ports/atmel-samd/asf4_conf/same54/usbd_config.h index be1fa3c9e0..b2629e1239 100644 --- a/ports/atmel-samd/asf4_conf/same54/usbd_config.h +++ b/ports/atmel-samd/asf4_conf/same54/usbd_config.h @@ -101,7 +101,7 @@ #ifndef CONF_USB_COMPOSITE_IPRODUCT #define CONF_USB_COMPOSITE_IPRODUCT \ - (CONF_USB_COMPOSITE_IPRODUCT_EN * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN)) + (CONF_USB_COMPOSITE_IPRODUCT_EN * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN)) #endif // Unicode string of iProduct @@ -124,8 +124,8 @@ #ifndef CONF_USB_COMPOSITE_ISERIALNUM #define CONF_USB_COMPOSITE_ISERIALNUM \ - (CONF_USB_COMPOSITE_ISERIALNUM_EN \ - * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN)) + (CONF_USB_COMPOSITE_ISERIALNUM_EN \ + * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN)) #endif // Unicode string of iSerialNum @@ -162,9 +162,9 @@ #ifndef CONF_USB_COMPOSITE_ICONFIG #define CONF_USB_COMPOSITE_ICONFIG \ - (CONF_USB_COMPOSITE_ICONFIG_EN \ - * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN \ - + CONF_USB_COMPOSITE_ICONFIG_EN)) + (CONF_USB_COMPOSITE_ICONFIG_EN \ + * (CONF_USB_COMPOSITE_IMANUFACT_EN + CONF_USB_COMPOSITE_IPRODUCT_EN + CONF_USB_COMPOSITE_ISERIALNUM_EN \ + + CONF_USB_COMPOSITE_ICONFIG_EN)) #endif // Unicode string of iConfig @@ -453,9 +453,9 @@ #ifndef CONF_USB_COMPOSITE_HID_GENERIC_REPORT #define CONF_USB_COMPOSITE_HID_GENERIC_REPORT \ - 0x06, 0xFF, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, \ - 0x40, 0x81, 0x02, 0x09, 0x04, 0x09, 0x05, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, \ - 0x09, 0x06, 0x09, 0x07, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0xB1, 0x02, 0xC0 + 0x06, 0xFF, 0xFF, 0x09, 0x01, 0xA1, 0x01, 0x09, 0x02, 0x09, 0x03, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, \ + 0x40, 0x81, 0x02, 0x09, 0x04, 0x09, 0x05, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x40, 0x91, 0x02, \ + 0x09, 0x06, 0x09, 0x07, 0x15, 0x00, 0x26, 0xFF, 0x00, 0x75, 0x08, 0x95, 0x04, 0xB1, 0x02, 0xC0 #endif // HID Generic INTERRUPT IN Endpoint Address @@ -650,7 +650,7 @@ #ifndef CONF_USB_MSC_LUN0_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN0_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN0_CAPACITY * 1024 / CONF_USB_MSC_LUN0_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN0_CAPACITY * 1024 / CONF_USB_MSC_LUN0_BLOCK_SIZE - 1) #endif // @@ -713,7 +713,7 @@ #ifndef CONF_USB_MSC_LUN1_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN1_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN1_CAPACITY * 1024 / CONF_USB_MSC_LUN1_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN1_CAPACITY * 1024 / CONF_USB_MSC_LUN1_BLOCK_SIZE - 1) #endif // @@ -775,7 +775,7 @@ #ifndef CONF_USB_MSC_LUN2_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN2_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN2_CAPACITY * 1024 / CONF_USB_MSC_LUN2_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN2_CAPACITY * 1024 / CONF_USB_MSC_LUN2_BLOCK_SIZE - 1) #endif // @@ -837,7 +837,7 @@ #ifndef CONF_USB_MSC_LUN3_LAST_BLOCK_ADDR #define CONF_USB_MSC_LUN3_LAST_BLOCK_ADDR \ - ((uint32_t)CONF_USB_MSC_LUN3_CAPACITY * 1024 / CONF_USB_MSC_LUN3_BLOCK_SIZE - 1) + ((uint32_t)CONF_USB_MSC_LUN3_CAPACITY * 1024 / CONF_USB_MSC_LUN3_BLOCK_SIZE - 1) #endif // diff --git a/ports/atmel-samd/audio_dma.c b/ports/atmel-samd/audio_dma.c index c6c636160d..0fe71e6d5d 100644 --- a/ports/atmel-samd/audio_dma.c +++ b/ports/atmel-samd/audio_dma.c @@ -38,7 +38,7 @@ #if CIRCUITPY_AUDIOIO || CIRCUITPY_AUDIOBUSIO -static audio_dma_t* audio_dma_state[AUDIO_DMA_CHANNEL_COUNT]; +static audio_dma_t *audio_dma_state[AUDIO_DMA_CHANNEL_COUNT]; // This cannot be in audio_dma_state because it's volatile. static volatile bool audio_dma_pending[AUDIO_DMA_CHANNEL_COUNT]; @@ -64,20 +64,22 @@ void audio_dma_free_channel(uint8_t channel) { } void audio_dma_disable_channel(uint8_t channel) { - if (channel >= AUDIO_DMA_CHANNEL_COUNT) + if (channel >= AUDIO_DMA_CHANNEL_COUNT) { return; + } dma_disable_channel(channel); } void audio_dma_enable_channel(uint8_t channel) { - if (channel >= AUDIO_DMA_CHANNEL_COUNT) + if (channel >= AUDIO_DMA_CHANNEL_COUNT) { return; + } dma_enable_channel(channel); } -void audio_dma_convert_signed(audio_dma_t* dma, uint8_t* buffer, uint32_t buffer_length, - uint8_t** output_buffer, uint32_t* output_buffer_length, - uint8_t* output_spacing) { +void audio_dma_convert_signed(audio_dma_t *dma, uint8_t *buffer, uint32_t buffer_length, + uint8_t **output_buffer, uint32_t *output_buffer_length, + uint8_t *output_spacing) { if (dma->first_buffer_free) { *output_buffer = dma->first_buffer; } else { @@ -92,18 +94,18 @@ void audio_dma_convert_signed(audio_dma_t* dma, uint8_t* buffer, uint32_t buffer if (dma->bytes_per_sample == 1) { for (uint32_t i = 0; i < buffer_length; i += dma->spacing) { if (dma->signed_to_unsigned) { - ((uint8_t*) *output_buffer)[out_i] = ((int8_t*) buffer)[i] + 0x80; + ((uint8_t *)*output_buffer)[out_i] = ((int8_t *)buffer)[i] + 0x80; } else { - ((int8_t*) *output_buffer)[out_i] = ((uint8_t*) buffer)[i] - 0x80; + ((int8_t *)*output_buffer)[out_i] = ((uint8_t *)buffer)[i] - 0x80; } out_i += 1; } } else if (dma->bytes_per_sample == 2) { for (uint32_t i = 0; i < buffer_length / 2; i += dma->spacing) { if (dma->signed_to_unsigned) { - ((uint16_t*) *output_buffer)[out_i] = ((int16_t*) buffer)[i] + 0x8000; + ((uint16_t *)*output_buffer)[out_i] = ((int16_t *)buffer)[i] + 0x8000; } else { - ((int16_t*) *output_buffer)[out_i] = ((uint16_t*) buffer)[i] - 0x8000; + ((int16_t *)*output_buffer)[out_i] = ((uint16_t *)buffer)[i] - 0x8000; } out_i += 1; } @@ -117,14 +119,14 @@ void audio_dma_convert_signed(audio_dma_t* dma, uint8_t* buffer, uint32_t buffer dma->first_buffer_free = !dma->first_buffer_free; } -void audio_dma_load_next_block(audio_dma_t* dma) { - uint8_t* buffer; +void audio_dma_load_next_block(audio_dma_t *dma) { + uint8_t *buffer; uint32_t buffer_length; audioio_get_buffer_result_t get_buffer_result = audiosample_get_buffer(dma->sample, dma->single_channel, dma->audio_channel, - &buffer, &buffer_length); + &buffer, &buffer_length); - DmacDescriptor* descriptor = dma->second_descriptor; + DmacDescriptor *descriptor = dma->second_descriptor; if (dma->first_descriptor_free) { descriptor = dma_descriptor(dma->dma_channel); } @@ -135,14 +137,14 @@ void audio_dma_load_next_block(audio_dma_t* dma) { return; } - uint8_t* output_buffer; + uint8_t *output_buffer; uint32_t output_buffer_length; uint8_t output_spacing; audio_dma_convert_signed(dma, buffer, buffer_length, &output_buffer, &output_buffer_length, &output_spacing); descriptor->BTCNT.reg = output_buffer_length / dma->beat_size / output_spacing; - descriptor->SRCADDR.reg = ((uint32_t) output_buffer) + output_buffer_length; + descriptor->SRCADDR.reg = ((uint32_t)output_buffer) + output_buffer_length; if (get_buffer_result == GET_BUFFER_DONE) { if (dma->loop) { audiosample_reset_buffer(dma->sample, dma->single_channel, dma->audio_channel); @@ -153,8 +155,8 @@ void audio_dma_load_next_block(audio_dma_t* dma) { descriptor->BTCTRL.bit.VALID = true; } -static void setup_audio_descriptor(DmacDescriptor* descriptor, uint8_t beat_size, - uint8_t spacing, uint32_t output_register_address) { +static void setup_audio_descriptor(DmacDescriptor *descriptor, uint8_t beat_size, + uint8_t spacing, uint32_t output_register_address) { uint32_t beat_size_reg = DMAC_BTCTRL_BEATSIZE_BYTE; if (beat_size == 2) { beat_size_reg = DMAC_BTCTRL_BEATSIZE_HWORD; @@ -162,22 +164,22 @@ static void setup_audio_descriptor(DmacDescriptor* descriptor, uint8_t beat_size beat_size_reg = DMAC_BTCTRL_BEATSIZE_WORD; } descriptor->BTCTRL.reg = beat_size_reg | - DMAC_BTCTRL_SRCINC | - DMAC_BTCTRL_EVOSEL_BLOCK | - DMAC_BTCTRL_STEPSIZE(spacing - 1) | - DMAC_BTCTRL_STEPSEL_SRC; + DMAC_BTCTRL_SRCINC | + DMAC_BTCTRL_EVOSEL_BLOCK | + DMAC_BTCTRL_STEPSIZE(spacing - 1) | + DMAC_BTCTRL_STEPSEL_SRC; descriptor->DSTADDR.reg = output_register_address; } // Playback should be shutdown before calling this. -audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, - mp_obj_t sample, - bool loop, - bool single_channel, - uint8_t audio_channel, - bool output_signed, - uint32_t output_register_address, - uint8_t dma_trigger_source) { +audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, + mp_obj_t sample, + bool loop, + bool single_channel, + uint8_t audio_channel, + bool output_signed, + uint32_t output_register_address, + uint8_t dma_trigger_source) { uint8_t dma_channel = audio_dma_allocate_channel(); if (dma_channel >= AUDIO_DMA_CHANNEL_COUNT) { return AUDIO_DMA_DMA_BUSY; @@ -199,18 +201,18 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, bool samples_signed; uint32_t max_buffer_length; audiosample_get_buffer_structure(sample, single_channel, &single_buffer, &samples_signed, - &max_buffer_length, &dma->spacing); + &max_buffer_length, &dma->spacing); uint8_t output_spacing = dma->spacing; if (output_signed != samples_signed) { output_spacing = 1; max_buffer_length /= dma->spacing; - dma->first_buffer = (uint8_t*) m_realloc(dma->first_buffer, max_buffer_length); + dma->first_buffer = (uint8_t *)m_realloc(dma->first_buffer, max_buffer_length); if (dma->first_buffer == NULL) { return AUDIO_DMA_MEMORY_ERROR; } dma->first_buffer_free = true; if (!single_buffer) { - dma->second_buffer = (uint8_t*) m_realloc(dma->second_buffer, max_buffer_length); + dma->second_buffer = (uint8_t *)m_realloc(dma->second_buffer, max_buffer_length); if (dma->second_buffer == NULL) { return AUDIO_DMA_MEMORY_ERROR; } @@ -221,7 +223,7 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, dma->event_channel = 0xff; if (!single_buffer) { - dma->second_descriptor = (DmacDescriptor*) m_malloc(sizeof(DmacDescriptor), false); + dma->second_descriptor = (DmacDescriptor *)m_malloc(sizeof(DmacDescriptor), false); if (dma->second_descriptor == NULL) { return AUDIO_DMA_MEMORY_ERROR; } @@ -257,26 +259,26 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, dma->beat_size *= 2; } -#ifdef SAM_D5X_E5X + #ifdef SAM_D5X_E5X int irq = dma->event_channel < 4 ? EVSYS_0_IRQn + dma->event_channel : EVSYS_4_IRQn; -#else + #else int irq = EVSYS_IRQn; -#endif + #endif NVIC_DisableIRQ(irq); NVIC_ClearPendingIRQ(irq); - DmacDescriptor* first_descriptor = dma_descriptor(dma_channel); + DmacDescriptor *first_descriptor = dma_descriptor(dma_channel); setup_audio_descriptor(first_descriptor, dma->beat_size, output_spacing, output_register_address); if (single_buffer) { first_descriptor->DESCADDR.reg = 0; if (dma->loop) { - first_descriptor->DESCADDR.reg = (uint32_t) first_descriptor; + first_descriptor->DESCADDR.reg = (uint32_t)first_descriptor; } } else { - first_descriptor->DESCADDR.reg = (uint32_t) dma->second_descriptor; + first_descriptor->DESCADDR.reg = (uint32_t)dma->second_descriptor; setup_audio_descriptor(dma->second_descriptor, dma->beat_size, output_spacing, output_register_address); - dma->second_descriptor->DESCADDR.reg = (uint32_t) first_descriptor; + dma->second_descriptor->DESCADDR.reg = (uint32_t)first_descriptor; } // Load the first two blocks up front. @@ -293,7 +295,7 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, return AUDIO_DMA_OK; } -void audio_dma_stop(audio_dma_t* dma) { +void audio_dma_stop(audio_dma_t *dma) { uint8_t channel = dma->dma_channel; if (channel < AUDIO_DMA_CHANNEL_COUNT) { audio_dma_disable_channel(channel); @@ -305,15 +307,15 @@ void audio_dma_stop(audio_dma_t* dma) { dma->dma_channel = AUDIO_DMA_CHANNEL_COUNT; } -void audio_dma_pause(audio_dma_t* dma) { +void audio_dma_pause(audio_dma_t *dma) { dma_suspend_channel(dma->dma_channel); } -void audio_dma_resume(audio_dma_t* dma) { +void audio_dma_resume(audio_dma_t *dma) { dma_resume_channel(dma->dma_channel); } -bool audio_dma_get_paused(audio_dma_t* dma) { +bool audio_dma_get_paused(audio_dma_t *dma) { if (dma->dma_channel >= AUDIO_DMA_CHANNEL_COUNT) { return false; } @@ -322,7 +324,7 @@ bool audio_dma_get_paused(audio_dma_t* dma) { return (status & DMAC_CHINTFLAG_SUSP) != 0; } -void audio_dma_init(audio_dma_t* dma) { +void audio_dma_init(audio_dma_t *dma) { dma->dma_channel = AUDIO_DMA_CHANNEL_COUNT; } @@ -337,7 +339,7 @@ void audio_dma_reset(void) { } } -bool audio_dma_get_playing(audio_dma_t* dma) { +bool audio_dma_get_playing(audio_dma_t *dma) { if (dma->dma_channel >= AUDIO_DMA_CHANNEL_COUNT) { return false; } @@ -352,7 +354,7 @@ bool audio_dma_get_playing(audio_dma_t* dma) { // WARN(tannewt): DO NOT print from here, or anything it calls. Printing calls // background tasks such as this and causes a stack overflow. STATIC void dma_callback_fun(void *arg) { - audio_dma_t* dma = arg; + audio_dma_t *dma = arg; if (dma == NULL) { return; } @@ -362,7 +364,7 @@ STATIC void dma_callback_fun(void *arg) { void evsyshandler_common(void) { for (uint8_t i = 0; i < AUDIO_DMA_CHANNEL_COUNT; i++) { - audio_dma_t* dma = audio_dma_state[i]; + audio_dma_t *dma = audio_dma_state[i]; if (dma == NULL) { continue; } @@ -370,18 +372,30 @@ void evsyshandler_common(void) { if (!block_done) { continue; } - background_callback_add(&dma->callback, dma_callback_fun, (void*)dma); + background_callback_add(&dma->callback, dma_callback_fun, (void *)dma); } } #ifdef SAM_D5X_E5X -void EVSYS_0_Handler(void) { evsyshandler_common(); } -void EVSYS_1_Handler(void) { evsyshandler_common(); } -void EVSYS_2_Handler(void) { evsyshandler_common(); } -void EVSYS_3_Handler(void) { evsyshandler_common(); } -void EVSYS_4_Handler(void) { evsyshandler_common(); } +void EVSYS_0_Handler(void) { + evsyshandler_common(); +} +void EVSYS_1_Handler(void) { + evsyshandler_common(); +} +void EVSYS_2_Handler(void) { + evsyshandler_common(); +} +void EVSYS_3_Handler(void) { + evsyshandler_common(); +} +void EVSYS_4_Handler(void) { + evsyshandler_common(); +} #else -void EVSYS_Handler(void) { evsyshandler_common(); } +void EVSYS_Handler(void) { + evsyshandler_common(); +} #endif #endif diff --git a/ports/atmel-samd/audio_dma.h b/ports/atmel-samd/audio_dma.h index 4fffd06b8f..5506cff628 100644 --- a/ports/atmel-samd/audio_dma.h +++ b/ports/atmel-samd/audio_dma.h @@ -46,10 +46,10 @@ typedef struct { bool signed_to_unsigned; bool unsigned_to_signed; bool first_buffer_free; - uint8_t* first_buffer; - uint8_t* second_buffer; + uint8_t *first_buffer; + uint8_t *second_buffer; bool first_descriptor_free; - DmacDescriptor* second_descriptor; + DmacDescriptor *second_descriptor; background_callback_t callback; } audio_dma_t; @@ -63,7 +63,7 @@ uint32_t audiosample_sample_rate(mp_obj_t sample_obj); uint8_t audiosample_bits_per_sample(mp_obj_t sample_obj); uint8_t audiosample_channel_count(mp_obj_t sample_obj); -void audio_dma_init(audio_dma_t* dma); +void audio_dma_init(audio_dma_t *dma); void audio_dma_reset(void); uint8_t audio_dma_allocate_channel(void); @@ -78,22 +78,22 @@ void audio_dma_free_channel(uint8_t channel); // output_signed is true if the dma'd data should be signed. False and it will be unsigned. // output_register_address is the address to copy data to. // dma_trigger_source is the DMA trigger source which cause another copy -audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, - mp_obj_t sample, - bool loop, - bool single_channel, - uint8_t audio_channel, - bool output_signed, - uint32_t output_register_address, - uint8_t dma_trigger_source); +audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, + mp_obj_t sample, + bool loop, + bool single_channel, + uint8_t audio_channel, + bool output_signed, + uint32_t output_register_address, + uint8_t dma_trigger_source); void audio_dma_disable_channel(uint8_t channel); void audio_dma_enable_channel(uint8_t channel); -void audio_dma_stop(audio_dma_t* dma); -bool audio_dma_get_playing(audio_dma_t* dma); -void audio_dma_pause(audio_dma_t* dma); -void audio_dma_resume(audio_dma_t* dma); -bool audio_dma_get_paused(audio_dma_t* dma); +void audio_dma_stop(audio_dma_t *dma); +bool audio_dma_get_playing(audio_dma_t *dma); +void audio_dma_pause(audio_dma_t *dma); +void audio_dma_resume(audio_dma_t *dma); +bool audio_dma_get_paused(audio_dma_t *dma); void audio_dma_background(void); diff --git a/ports/atmel-samd/background.c b/ports/atmel-samd/background.c index 62c233a3f8..237395b6b9 100644 --- a/ports/atmel-samd/background.c +++ b/ports/atmel-samd/background.c @@ -44,16 +44,19 @@ // so you can't use this code AND an i2c peripheral // at the same time unless you change this void port_start_background_task(void) { - REG_PORT_DIRSET1 = (1<<3); - REG_PORT_OUTSET1 = (1<<3); + REG_PORT_DIRSET1 = (1 << 3); + REG_PORT_OUTSET1 = (1 << 3); } void port_finish_background_task(void) { - REG_PORT_OUTCLR1 = (1<<3); + REG_PORT_OUTCLR1 = (1 << 3); } #else -void port_start_background_task(void) {} -void port_finish_background_task(void) {} +void port_start_background_task(void) { +} +void port_finish_background_task(void) { +} #endif -void port_background_task(void) {} +void port_background_task(void) { +} diff --git a/ports/atmel-samd/bindings/samd/Clock.c b/ports/atmel-samd/bindings/samd/Clock.c index 478a10fcd4..9375a7a848 100644 --- a/ports/atmel-samd/bindings/samd/Clock.c +++ b/ports/atmel-samd/bindings/samd/Clock.c @@ -57,8 +57,7 @@ const mp_obj_property_t samd_clock_enabled_obj = { .base.type = &mp_type_property, .proxy = {(mp_obj_t)&samd_clock_get_enabled_obj, (mp_obj_t)&mp_const_none_obj, - (mp_obj_t)&mp_const_none_obj, - }, + (mp_obj_t)&mp_const_none_obj,}, }; //| parent: Union[Clock, None] @@ -67,14 +66,16 @@ const mp_obj_property_t samd_clock_enabled_obj = { STATIC mp_obj_t samd_clock_get_parent(mp_obj_t self_in) { samd_clock_obj_t *self = MP_OBJ_TO_PTR(self_in); uint8_t p_type, p_index; - if (!clock_get_parent(self->type, self->index, &p_type, &p_index)) + if (!clock_get_parent(self->type, self->index, &p_type, &p_index)) { return mp_const_none; + } - const mp_map_t* samd_map = &samd_clock_globals.map; + const mp_map_t *samd_map = &samd_clock_globals.map; for (uint8_t i = 0; i < samd_map->alloc; i++) { samd_clock_obj_t *iter = samd_map->table[i].value; - if (iter->type == p_type && iter->index == p_index) + if (iter->type == p_type && iter->index == p_index) { return iter; + } } return mp_const_none; } @@ -85,8 +86,7 @@ const mp_obj_property_t samd_clock_parent_obj = { .base.type = &mp_type_property, .proxy = {(mp_obj_t)&samd_clock_get_parent_obj, (mp_obj_t)&mp_const_none_obj, - (mp_obj_t)&mp_const_none_obj, - }, + (mp_obj_t)&mp_const_none_obj,}, }; //| frequency: int @@ -103,8 +103,7 @@ const mp_obj_property_t samd_clock_frequency_obj = { .base.type = &mp_type_property, .proxy = {(mp_obj_t)&samd_clock_get_frequency_obj, (mp_obj_t)&mp_const_none_obj, - (mp_obj_t)&mp_const_none_obj, - }, + (mp_obj_t)&mp_const_none_obj,}, }; //| calibration: int @@ -120,10 +119,12 @@ MP_DEFINE_CONST_FUN_OBJ_1(samd_clock_get_calibration_obj, samd_clock_get_calibra STATIC mp_obj_t samd_clock_set_calibration(mp_obj_t self_in, mp_obj_t calibration) { samd_clock_obj_t *self = MP_OBJ_TO_PTR(self_in); int ret = clock_set_calibration(self->type, self->index, mp_obj_get_int(calibration)); - if (ret == -2) + if (ret == -2) { mp_raise_AttributeError(translate("calibration is read only")); - if (ret == -1) + } + if (ret == -1) { mp_raise_ValueError(translate("calibration is out of range")); + } return mp_const_none; } @@ -133,8 +134,7 @@ const mp_obj_property_t samd_clock_calibration_obj = { .base.type = &mp_type_property, .proxy = {(mp_obj_t)&samd_clock_get_calibration_obj, (mp_obj_t)&samd_clock_set_calibration_obj, - (mp_obj_t)&mp_const_none_obj, - }, + (mp_obj_t)&mp_const_none_obj,}, }; STATIC const mp_rom_map_elem_t samd_clock_locals_dict_table[] = { @@ -212,15 +212,15 @@ CLOCK(SYSTICK, 2, 0); #endif STATIC const mp_rom_map_elem_t samd_clock_global_dict_table[] = { -#ifdef SAMD21_EXPOSE_ALL_CLOCKS + #ifdef SAMD21_EXPOSE_ALL_CLOCKS CLOCK_ENTRY(XOSC), CLOCK_ENTRY(GCLKIN), CLOCK_ENTRY(GCLKGEN1), CLOCK_ENTRY(OSCULP32K), -#endif + #endif CLOCK_ENTRY(OSC32K), CLOCK_ENTRY(XOSC32K), -#ifdef SAMD21_EXPOSE_ALL_CLOCKS + #ifdef SAMD21_EXPOSE_ALL_CLOCKS CLOCK_ENTRY(OSC8M), CLOCK_ENTRY(DFLL48M), CLOCK_ENTRY(DPLL96M), @@ -228,9 +228,9 @@ STATIC const mp_rom_map_elem_t samd_clock_global_dict_table[] = { CLOCK_ENTRY_(SYSCTRL, FDPLL), CLOCK_ENTRY_(SYSCTRL, FDPLL32K), CLOCK_ENTRY(WDT), -#endif + #endif CLOCK_ENTRY(RTC), -#ifdef SAMD21_EXPOSE_ALL_CLOCKS + #ifdef SAMD21_EXPOSE_ALL_CLOCKS CLOCK_ENTRY(EIC), CLOCK_ENTRY(USB), CLOCK_ENTRY_(EVSYS, 0), @@ -265,7 +265,7 @@ STATIC const mp_rom_map_elem_t samd_clock_global_dict_table[] = { CLOCK_ENTRY_(I2S, 1), CLOCK_ENTRY(SYSTICK), -#endif + #endif }; MP_DEFINE_CONST_DICT(samd_clock_globals, samd_clock_global_dict_table); diff --git a/ports/atmel-samd/bindings/samd/Clock.h b/ports/atmel-samd/bindings/samd/Clock.h index ccc8f10d10..a4c11556b3 100644 --- a/ports/atmel-samd/bindings/samd/Clock.h +++ b/ports/atmel-samd/bindings/samd/Clock.h @@ -37,39 +37,39 @@ typedef struct { } samd_clock_obj_t; #define CLOCK(_name, _type, _index) \ -const samd_clock_obj_t clock_ ## _name = { \ - { &samd_clock_type }, \ - .name = MP_QSTR_ ## _name, \ - .type = _type, \ - .index = _index, \ -} + const samd_clock_obj_t clock_##_name = { \ + { &samd_clock_type }, \ + .name = MP_QSTR_##_name, \ + .type = _type, \ + .index = _index, \ + } #define CLOCK_SOURCE(_name) \ -const samd_clock_obj_t clock_ ## _name = { \ - { &samd_clock_type }, \ - .name = MP_QSTR_ ## _name, \ - .type = 0, \ - .index = GCLK_SOURCE_ ## _name, \ -} + const samd_clock_obj_t clock_##_name = { \ + { &samd_clock_type }, \ + .name = MP_QSTR_##_name, \ + .type = 0, \ + .index = GCLK_SOURCE_##_name, \ + } #define CLOCK_GCLK(_name) \ -const samd_clock_obj_t clock_ ## _name = { \ - { &samd_clock_type }, \ - .name = MP_QSTR_ ## _name, \ - .type = 1, \ - .index = _name ## _GCLK_ID, \ -} + const samd_clock_obj_t clock_##_name = { \ + { &samd_clock_type }, \ + .name = MP_QSTR_##_name, \ + .type = 1, \ + .index = _name##_GCLK_ID, \ + } #define CLOCK_GCLK_(_name, _extra) \ -const samd_clock_obj_t clock_ ## _name ## _ ## _extra = { \ - { &samd_clock_type }, \ - .name = MP_QSTR_ ## _name ## _ ## _extra, \ - .type = 1, \ - .index = _name ## _GCLK_ID_ ## _extra, \ -} + const samd_clock_obj_t clock_##_name##_##_extra = { \ + { &samd_clock_type }, \ + .name = MP_QSTR_##_name##_##_extra, \ + .type = 1, \ + .index = _name##_GCLK_ID_##_extra, \ + } -#define CLOCK_ENTRY(_name) { MP_ROM_QSTR(MP_QSTR_ ## _name), MP_ROM_PTR(&clock_ ## _name) } -#define CLOCK_ENTRY_(_name, _extra) { MP_ROM_QSTR(MP_QSTR_ ## _name ## _ ## _extra), MP_ROM_PTR(&clock_ ## _name ## _ ## _extra) } +#define CLOCK_ENTRY(_name) { MP_ROM_QSTR(MP_QSTR_##_name), MP_ROM_PTR(&clock_##_name) } +#define CLOCK_ENTRY_(_name, _extra) { MP_ROM_QSTR(MP_QSTR_##_name##_##_extra), MP_ROM_PTR(&clock_##_name##_##_extra) } extern const mp_obj_type_t samd_clock_type; extern const mp_obj_dict_t samd_clock_globals; diff --git a/ports/atmel-samd/bindings/samd/__init__.c b/ports/atmel-samd/bindings/samd/__init__.c index 6e9b68ccc6..207a6d52e6 100644 --- a/ports/atmel-samd/bindings/samd/__init__.c +++ b/ports/atmel-samd/bindings/samd/__init__.c @@ -43,7 +43,7 @@ //| const mp_obj_module_t samd_clock_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&samd_clock_globals, + .globals = (mp_obj_dict_t *)&samd_clock_globals, }; STATIC const mp_rom_map_elem_t samd_module_globals_table[] = { @@ -55,5 +55,5 @@ STATIC MP_DEFINE_CONST_DICT(samd_module_globals, samd_module_globals_table); const mp_obj_module_t samd_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&samd_module_globals, + .globals = (mp_obj_dict_t *)&samd_module_globals, }; diff --git a/ports/atmel-samd/boards/8086_commander/mpconfigboard.h b/ports/atmel-samd/boards/8086_commander/mpconfigboard.h index 9e3be4e6a0..0b5d3a267d 100644 --- a/ports/atmel-samd/boards/8086_commander/mpconfigboard.h +++ b/ports/atmel-samd/boards/8086_commander/mpconfigboard.h @@ -6,9 +6,9 @@ #define MICROPY_HW_LED_STATUS (&pin_PA06) -#define MICROPY_PORT_A (0) -#define MICROPY_PORT_B (0) -#define MICROPY_PORT_C (0) +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) // USB is always used internally so skip the pin objects for it. #define IGNORE_PIN_PA24 1 diff --git a/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c b/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c index 5973eeec1b..c67701512f 100644 --- a/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c +++ b/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c @@ -32,21 +32,20 @@ #include "mpconfigboard.h" void board_init(void) { - REG_PORT_DIRSET1 = PORT_PB20; // PB20 as output - REG_PORT_OUTCLR1 = PORT_PB20; // PB20 cleared - PORT->Group[1].PINCFG[20].reg |= PORT_PINCFG_PMUXEN; // Mux enabled on PB20 - PORT->Group[1].PMUX[10].reg = 0x0C; // PB20 as mux function "M" - // Gclk[6] is on PB20 - GCLK->GENCTRL[6].reg = GCLK_GENCTRL_SRC(GCLK_GENCTRL_SRC_DPLL0) | - GCLK_GENCTRL_IDC | - GCLK_GENCTRL_DIV(10) | - //GCLK_GENCTRL_DIVSEL | - GCLK_GENCTRL_OE | - GCLK_GENCTRL_GENEN; - while ( GCLK->SYNCBUSY.reg & GCLK_SYNCBUSY_GENCTRL6) - { - // Wait for synchronization - } + REG_PORT_DIRSET1 = PORT_PB20; // PB20 as output + REG_PORT_OUTCLR1 = PORT_PB20; // PB20 cleared + PORT->Group[1].PINCFG[20].reg |= PORT_PINCFG_PMUXEN; // Mux enabled on PB20 + PORT->Group[1].PMUX[10].reg = 0x0C; // PB20 as mux function "M" + // Gclk[6] is on PB20 + GCLK->GENCTRL[6].reg = GCLK_GENCTRL_SRC(GCLK_GENCTRL_SRC_DPLL0) | + GCLK_GENCTRL_IDC | + GCLK_GENCTRL_DIV(10) | + // GCLK_GENCTRL_DIVSEL | + GCLK_GENCTRL_OE | + GCLK_GENCTRL_GENEN; + while (GCLK->SYNCBUSY.reg & GCLK_SYNCBUSY_GENCTRL6) { + // Wait for synchronization + } } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/aloriumtech_evo_m51/mpconfigboard.h b/ports/atmel-samd/boards/aloriumtech_evo_m51/mpconfigboard.h index cafc82605d..3882c2b6db 100644 --- a/ports/atmel-samd/boards/aloriumtech_evo_m51/mpconfigboard.h +++ b/ports/atmel-samd/boards/aloriumtech_evo_m51/mpconfigboard.h @@ -17,21 +17,21 @@ #define MICROPY_PORT_D (0) // BC needed? -//#define AUTORESET_DELAY_MS 500 +// #define AUTORESET_DELAY_MS 500 // If you change this, then make sure to update the linker scripts as well to // make sure you don't overwrite code -//#define CIRCUITPY_INTERNAL_NVM_SIZE 8192 +// #define CIRCUITPY_INTERNAL_NVM_SIZE 8192 -//#define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) +// #define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) // End BC #define EXTERNAL_FLASH_QSPI_DUAL #define BOARD_HAS_CRYSTAL 1 -//#define DEFAULT_I2C_BUS_SCL (&pin_PA13) -//#define DEFAULT_I2C_BUS_SDA (&pin_PA12) +// #define DEFAULT_I2C_BUS_SCL (&pin_PA13) +// #define DEFAULT_I2C_BUS_SDA (&pin_PA12) #define DEFAULT_I2C_BUS_SCL (&pin_PA13) #define DEFAULT_I2C_BUS_SDA (&pin_PA12) diff --git a/ports/atmel-samd/boards/arduino_mkr1300/board.c b/ports/atmel-samd/boards/arduino_mkr1300/board.c index 112b173ecc..7af05ba45a 100644 --- a/ports/atmel-samd/boards/arduino_mkr1300/board.c +++ b/ports/atmel-samd/boards/arduino_mkr1300/board.c @@ -28,8 +28,7 @@ #include "mpconfigboard.h" #include "hal/include/hal_gpio.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/arduino_nano_33_iot/board.c b/ports/atmel-samd/boards/arduino_nano_33_iot/board.c index 112b173ecc..7af05ba45a 100644 --- a/ports/atmel-samd/boards/arduino_nano_33_iot/board.c +++ b/ports/atmel-samd/boards/arduino_nano_33_iot/board.c @@ -28,8 +28,7 @@ #include "mpconfigboard.h" #include "hal/include/hal_gpio.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/arduino_zero/board.c b/ports/atmel-samd/boards/arduino_zero/board.c index 112b173ecc..7af05ba45a 100644 --- a/ports/atmel-samd/boards/arduino_zero/board.c +++ b/ports/atmel-samd/boards/arduino_zero/board.c @@ -28,8 +28,7 @@ #include "mpconfigboard.h" #include "hal/include/hal_gpio.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/bast_pro_mini_m0/board.c b/ports/atmel-samd/boards/bast_pro_mini_m0/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/bast_pro_mini_m0/board.c +++ b/ports/atmel-samd/boards/bast_pro_mini_m0/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/bdmicro_vina_d21/board.c b/ports/atmel-samd/boards/bdmicro_vina_d21/board.c index bb1c5335c1..bb6ad8bc0d 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d21/board.c +++ b/ports/atmel-samd/boards/bdmicro_vina_d21/board.c @@ -27,8 +27,7 @@ #include "supervisor/board.h" #include "mpconfigboard.h" -void board_init(void) -{ +void board_init(void) { // struct port_config pin_conf; // port_get_config_defaults(&pin_conf); // diff --git a/ports/atmel-samd/boards/bdmicro_vina_d51/board.c b/ports/atmel-samd/boards/bdmicro_vina_d51/board.c index bb1c5335c1..bb6ad8bc0d 100644 --- a/ports/atmel-samd/boards/bdmicro_vina_d51/board.c +++ b/ports/atmel-samd/boards/bdmicro_vina_d51/board.c @@ -27,8 +27,7 @@ #include "supervisor/board.h" #include "mpconfigboard.h" -void board_init(void) -{ +void board_init(void) { // struct port_config pin_conf; // port_get_config_defaults(&pin_conf); // diff --git a/ports/atmel-samd/boards/catwan_usbstick/board.c b/ports/atmel-samd/boards/catwan_usbstick/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/catwan_usbstick/board.c +++ b/ports/atmel-samd/boards/catwan_usbstick/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/circuitbrains_basic_m0/pins.c b/ports/atmel-samd/boards/circuitbrains_basic_m0/pins.c old mode 100755 new mode 100644 diff --git a/ports/atmel-samd/boards/circuitplayground_express/board.c b/ports/atmel-samd/boards/circuitplayground_express/board.c index f771c214b3..39e39b0d4b 100644 --- a/ports/atmel-samd/boards/circuitplayground_express/board.c +++ b/ports/atmel-samd/boards/circuitplayground_express/board.c @@ -31,8 +31,7 @@ #include "supervisor/shared/board.h" #include "hal/include/hal_gpio.h" -void board_init(void) -{ +void board_init(void) { } // Check the status of the two buttons on CircuitPlayground Express. If both are diff --git a/ports/atmel-samd/boards/circuitplayground_express/mpconfigboard.h b/ports/atmel-samd/boards/circuitplayground_express/mpconfigboard.h index e46e477e4e..a32133e353 100644 --- a/ports/atmel-samd/boards/circuitplayground_express/mpconfigboard.h +++ b/ports/atmel-samd/boards/circuitplayground_express/mpconfigboard.h @@ -28,7 +28,7 @@ #define BOARD_USER_SAFE_MODE_ACTION translate("pressing both buttons at start up.\n") // Increase stack size slightly due to CPX library import nesting -#define CIRCUITPY_DEFAULT_STACK_SIZE (4248) //divisible by 8 +#define CIRCUITPY_DEFAULT_STACK_SIZE (4248) // divisible by 8 #define DEFAULT_I2C_BUS_SCL (&pin_PB03) #define DEFAULT_I2C_BUS_SDA (&pin_PB02) diff --git a/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c b/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c index 13fed598eb..4666482e9d 100644 --- a/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c +++ b/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c @@ -31,8 +31,7 @@ #include "hal/include/hal_gpio.h" #include "supervisor/shared/board.h" -void board_init(void) -{ +void board_init(void) { } // Check the status of the two buttons on CircuitPlayground Express. If both are diff --git a/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c b/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c index 13fed598eb..4666482e9d 100644 --- a/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c +++ b/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c @@ -31,8 +31,7 @@ #include "hal/include/hal_gpio.h" #include "supervisor/shared/board.h" -void board_init(void) -{ +void board_init(void) { } // Check the status of the two buttons on CircuitPlayground Express. If both are diff --git a/ports/atmel-samd/boards/cp32-m4/mpconfigboard.h b/ports/atmel-samd/boards/cp32-m4/mpconfigboard.h index 8664a6a0ec..bdc44c79b1 100644 --- a/ports/atmel-samd/boards/cp32-m4/mpconfigboard.h +++ b/ports/atmel-samd/boards/cp32-m4/mpconfigboard.h @@ -7,8 +7,8 @@ #define CIRCUITPY_MCU_FAMILY samd51 -#define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11| PORT_PA12| PORT_PA13) -#define MICROPY_PORT_B ( PORT_PB10 | PORT_PB11) +#define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11 | PORT_PA12 | PORT_PA13) +#define MICROPY_PORT_B (PORT_PB10 | PORT_PB11) #define MICROPY_PORT_C (0) #define MICROPY_PORT_D (0) diff --git a/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.h b/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.h index c67f022eb8..b04a31c46f 100644 --- a/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.h +++ b/ports/atmel-samd/boards/cp_sapling_m0/mpconfigboard.h @@ -7,15 +7,15 @@ #define MICROPY_PORT_B (0) #define MICROPY_PORT_C (0) -#define IGNORE_PIN_PA02 1 -#define IGNORE_PIN_PA03 1 -#define IGNORE_PIN_PA04 1 -#define IGNORE_PIN_PA05 1 -#define IGNORE_PIN_PA06 1 -#define IGNORE_PIN_PA07 1 +#define IGNORE_PIN_PA02 1 +#define IGNORE_PIN_PA03 1 +#define IGNORE_PIN_PA04 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA06 1 +#define IGNORE_PIN_PA07 1 #define IGNORE_PIN_PA12 1 #define IGNORE_PIN_PA13 1 -#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA14 1 #define IGNORE_PIN_PA20 1 #define IGNORE_PIN_PA21 1 // USB is always used internally so skip the pin objects for it. diff --git a/ports/atmel-samd/boards/cp_sapling_m0_spiflash/mpconfigboard.h b/ports/atmel-samd/boards/cp_sapling_m0_spiflash/mpconfigboard.h index 9c69c48026..528d989edd 100644 --- a/ports/atmel-samd/boards/cp_sapling_m0_spiflash/mpconfigboard.h +++ b/ports/atmel-samd/boards/cp_sapling_m0_spiflash/mpconfigboard.h @@ -12,15 +12,15 @@ #define SPI_FLASH_SCK_PIN &pin_PA19 #define SPI_FLASH_CS_PIN &pin_PA22 -#define IGNORE_PIN_PA02 1 -#define IGNORE_PIN_PA03 1 -#define IGNORE_PIN_PA04 1 -#define IGNORE_PIN_PA05 1 -#define IGNORE_PIN_PA06 1 -#define IGNORE_PIN_PA07 1 +#define IGNORE_PIN_PA02 1 +#define IGNORE_PIN_PA03 1 +#define IGNORE_PIN_PA04 1 +#define IGNORE_PIN_PA05 1 +#define IGNORE_PIN_PA06 1 +#define IGNORE_PIN_PA07 1 #define IGNORE_PIN_PA12 1 #define IGNORE_PIN_PA13 1 -#define IGNORE_PIN_PA14 1 +#define IGNORE_PIN_PA14 1 #define IGNORE_PIN_PA20 1 #define IGNORE_PIN_PA21 1 // USB is always used internally so skip the pin objects for it. diff --git a/ports/atmel-samd/boards/datum_distance/board.c b/ports/atmel-samd/boards/datum_distance/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/datum_distance/board.c +++ b/ports/atmel-samd/boards/datum_distance/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/datum_imu/board.c b/ports/atmel-samd/boards/datum_imu/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/datum_imu/board.c +++ b/ports/atmel-samd/boards/datum_imu/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/datum_light/board.c b/ports/atmel-samd/boards/datum_light/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/datum_light/board.c +++ b/ports/atmel-samd/boards/datum_light/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/datum_weather/board.c b/ports/atmel-samd/boards/datum_weather/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/datum_weather/board.c +++ b/ports/atmel-samd/boards/datum_weather/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/dynossat_edu_eps/board.c b/ports/atmel-samd/boards/dynossat_edu_eps/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/dynossat_edu_eps/board.c +++ b/ports/atmel-samd/boards/dynossat_edu_eps/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/dynossat_edu_eps/mpconfigboard.h b/ports/atmel-samd/boards/dynossat_edu_eps/mpconfigboard.h index ef4fa8f997..02707a69d4 100644 --- a/ports/atmel-samd/boards/dynossat_edu_eps/mpconfigboard.h +++ b/ports/atmel-samd/boards/dynossat_edu_eps/mpconfigboard.h @@ -9,9 +9,9 @@ #define SPI_FLASH_CS_PIN &pin_PA20 // These are pins not to reset. -#define MICROPY_PORT_A ( 0 ) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define BOARD_HAS_CRYSTAL 1 @@ -28,7 +28,7 @@ // USB is always used internally so skip the pin objects for it. #define IGNORE_PIN_PA24 1 #define IGNORE_PIN_PA25 1 -#define IGNORE_PIN_PA03 1 +#define IGNORE_PIN_PA03 1 #define IGNORE_PIN_PA13 1 #define IGNORE_PIN_PA14 1 #define IGNORE_PIN_PA15 1 diff --git a/ports/atmel-samd/boards/dynossat_edu_obc/board.c b/ports/atmel-samd/boards/dynossat_edu_obc/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/dynossat_edu_obc/board.c +++ b/ports/atmel-samd/boards/dynossat_edu_obc/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/dynossat_edu_obc/mpconfigboard.h b/ports/atmel-samd/boards/dynossat_edu_obc/mpconfigboard.h index d7df8db74d..102a8cfb64 100644 --- a/ports/atmel-samd/boards/dynossat_edu_obc/mpconfigboard.h +++ b/ports/atmel-samd/boards/dynossat_edu_obc/mpconfigboard.h @@ -9,10 +9,10 @@ #define SPI_FLASH_CS_PIN &pin_PA19 // These are pins not to reset. -#define MICROPY_PORT_A ( PORT_PA16 | PORT_PA17 | PORT_PA18 | PORT_PA19 ) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) -#define MICROPY_PORT_D ( 0 ) +#define MICROPY_PORT_A (PORT_PA16 | PORT_PA17 | PORT_PA18 | PORT_PA19) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) +#define MICROPY_PORT_D (0) #define BOARD_HAS_CRYSTAL 1 diff --git a/ports/atmel-samd/boards/escornabot_makech/board.c b/ports/atmel-samd/boards/escornabot_makech/board.c index 5afe2fb655..76849c53e4 100644 --- a/ports/atmel-samd/boards/escornabot_makech/board.c +++ b/ports/atmel-samd/boards/escornabot_makech/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/escornabot_makech/pins.c b/ports/atmel-samd/boards/escornabot_makech/pins.c index fefee19199..86a70cb041 100644 --- a/ports/atmel-samd/boards/escornabot_makech/pins.c +++ b/ports/atmel-samd/boards/escornabot_makech/pins.c @@ -1,7 +1,7 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_global_dict_table[] = { - //LEDs + // LEDs { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA02) }, { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA04) }, { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA05) }, @@ -31,7 +31,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA09) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA13) }, - //UART + // UART { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_PA01) }, { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PA00) }, diff --git a/ports/atmel-samd/boards/feather_m0_adalogger/board.c b/ports/atmel-samd/boards/feather_m0_adalogger/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/feather_m0_adalogger/board.c +++ b/ports/atmel-samd/boards/feather_m0_adalogger/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/feather_m0_basic/board.c b/ports/atmel-samd/boards/feather_m0_basic/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/feather_m0_basic/board.c +++ b/ports/atmel-samd/boards/feather_m0_basic/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/feather_m0_express/board.c b/ports/atmel-samd/boards/feather_m0_express/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/feather_m0_express/board.c +++ b/ports/atmel-samd/boards/feather_m0_express/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h b/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h index 5421dc8890..27ea6c72ba 100644 --- a/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h +++ b/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.h @@ -12,8 +12,8 @@ // These are pins not to reset. #define MICROPY_PORT_A (PORT_PA06) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define BOARD_HAS_CRYSTAL 1 diff --git a/ports/atmel-samd/boards/feather_m0_express_crickit/board.c b/ports/atmel-samd/boards/feather_m0_express_crickit/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/feather_m0_express_crickit/board.c +++ b/ports/atmel-samd/boards/feather_m0_express_crickit/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/feather_m0_express_crickit/mpconfigboard.h b/ports/atmel-samd/boards/feather_m0_express_crickit/mpconfigboard.h index ee61e1d87d..112dd80fa6 100644 --- a/ports/atmel-samd/boards/feather_m0_express_crickit/mpconfigboard.h +++ b/ports/atmel-samd/boards/feather_m0_express_crickit/mpconfigboard.h @@ -12,8 +12,8 @@ // These are pins not to reset. #define MICROPY_PORT_A (PORT_PA06) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define BOARD_HAS_CRYSTAL 1 diff --git a/ports/atmel-samd/boards/feather_m0_rfm69/board.c b/ports/atmel-samd/boards/feather_m0_rfm69/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/feather_m0_rfm69/board.c +++ b/ports/atmel-samd/boards/feather_m0_rfm69/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/feather_m0_rfm9x/board.c b/ports/atmel-samd/boards/feather_m0_rfm9x/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/feather_m0_rfm9x/board.c +++ b/ports/atmel-samd/boards/feather_m0_rfm9x/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/feather_m0_supersized/board.c b/ports/atmel-samd/boards/feather_m0_supersized/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/feather_m0_supersized/board.c +++ b/ports/atmel-samd/boards/feather_m0_supersized/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.h b/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.h index 2d9f88e2e1..9fa2ba9ce7 100644 --- a/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.h +++ b/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.h @@ -14,8 +14,8 @@ // These are pins not to reset. #define MICROPY_PORT_A (PORT_PA06) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define DEFAULT_I2C_BUS_SCL (&pin_PA23) #define DEFAULT_I2C_BUS_SDA (&pin_PA22) diff --git a/ports/atmel-samd/boards/feather_radiofruit_zigbee/board.c b/ports/atmel-samd/boards/feather_radiofruit_zigbee/board.c old mode 100755 new mode 100644 index 6baa43ffaa..84960e73cf --- a/ports/atmel-samd/boards/feather_radiofruit_zigbee/board.c +++ b/ports/atmel-samd/boards/feather_radiofruit_zigbee/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/feather_radiofruit_zigbee/mpconfigboard.h b/ports/atmel-samd/boards/feather_radiofruit_zigbee/mpconfigboard.h old mode 100755 new mode 100644 index 2afe358178..b1839f2c99 --- a/ports/atmel-samd/boards/feather_radiofruit_zigbee/mpconfigboard.h +++ b/ports/atmel-samd/boards/feather_radiofruit_zigbee/mpconfigboard.h @@ -11,8 +11,8 @@ // These are pins not to reset. #define MICROPY_PORT_A (PORT_PA22) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define BOARD_HAS_CRYSTAL 1 diff --git a/ports/atmel-samd/boards/fluff_m0/board.c b/ports/atmel-samd/boards/fluff_m0/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/fluff_m0/board.c +++ b/ports/atmel-samd/boards/fluff_m0/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/gemma_m0/board.c b/ports/atmel-samd/boards/gemma_m0/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/gemma_m0/board.c +++ b/ports/atmel-samd/boards/gemma_m0/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.h b/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.h index bab0550148..f2f3d7cc46 100644 --- a/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.h +++ b/ports/atmel-samd/boards/grandcentral_m4_express/mpconfigboard.h @@ -14,11 +14,11 @@ // These are pins not to reset. // QSPI Data pins -#define MICROPY_PORT_A ( PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11 ) +#define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11) // QSPI CS, and QSPI SCK -#define MICROPY_PORT_B ( PORT_PB10 | PORT_PB11 ) +#define MICROPY_PORT_B (PORT_PB10 | PORT_PB11) // NeoPixel pin, RX LED, TX LED -#define MICROPY_PORT_C ( PORT_PC24 | PORT_PC30 | PORT_PC31 ) +#define MICROPY_PORT_C (PORT_PC24 | PORT_PC30 | PORT_PC31) #define MICROPY_PORT_D (0) #define BOARD_HAS_CRYSTAL 1 diff --git a/ports/atmel-samd/boards/hallowing_m0_express/board.c b/ports/atmel-samd/boards/hallowing_m0_express/board.c index 8b922d6bef..a9c11f1bae 100644 --- a/ports/atmel-samd/boards/hallowing_m0_express/board.c +++ b/ports/atmel-samd/boards/hallowing_m0_express/board.c @@ -55,13 +55,13 @@ uint8_t display_init_sequence[] = { // fix on VTL 0x3a, 1, 0x05, // COLMOD - 16bit color 0xe0, 16, 0x02, 0x1c, 0x07, 0x12, // _GMCTRP1 Gamma - 0x37, 0x32, 0x29, 0x2d, - 0x29, 0x25, 0x2B, 0x39, - 0x00, 0x01, 0x03, 0x10, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, 0xe1, 16, 0x03, 0x1d, 0x07, 0x06, // _GMCTRN1 - 0x2E, 0x2C, 0x29, 0x2D, - 0x2E, 0x2E, 0x37, 0x3F, - 0x00, 0x00, 0x02, 0x10, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, 0x2a, 3, 0x02, 0x00, 0x81, // _CASET XSTART = 2, XEND = 129 0x2b, 3, 0x02, 0x00, 0x81, // _RASET XSTART = 2, XEND = 129 0x13, 0 | DELAY, 10, // _NORON @@ -69,7 +69,7 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; busio_spi_obj_t *spi = common_hal_board_create_spi(); common_hal_displayio_fourwire_construct(bus, @@ -81,7 +81,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/hallowing_m0_express/mpconfigboard.h b/ports/atmel-samd/boards/hallowing_m0_express/mpconfigboard.h index e5ac346daf..28ce108119 100644 --- a/ports/atmel-samd/boards/hallowing_m0_express/mpconfigboard.h +++ b/ports/atmel-samd/boards/hallowing_m0_express/mpconfigboard.h @@ -11,10 +11,10 @@ // These are pins not to reset. // NeoPixel and for the display: Reset, Command or data, and Chip select -#define MICROPY_PORT_A ( PORT_PA01 | PORT_PA12 | PORT_PA27 | PORT_PA28) +#define MICROPY_PORT_A (PORT_PA01 | PORT_PA12 | PORT_PA27 | PORT_PA28) // Data and Clock for the display -#define MICROPY_PORT_B ( PORT_PB22 | PORT_PB23 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (PORT_PB22 | PORT_PB23) +#define MICROPY_PORT_C (0) #define DEFAULT_I2C_BUS_SCL (&pin_PA17) #define DEFAULT_I2C_BUS_SDA (&pin_PA16) diff --git a/ports/atmel-samd/boards/hallowing_m4_express/board.c b/ports/atmel-samd/boards/hallowing_m4_express/board.c index f51d4282d3..f9cdbdbafb 100644 --- a/ports/atmel-samd/boards/hallowing_m4_express/board.c +++ b/ports/atmel-samd/boards/hallowing_m4_express/board.c @@ -47,11 +47,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PA01, &pin_PA00, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -62,7 +62,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.h b/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.h index 4d911ad64c..0ac595edf7 100644 --- a/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.h +++ b/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.h @@ -8,7 +8,7 @@ #define MICROPY_PORT_A (PORT_PA24 | PORT_PA25) #define MICROPY_PORT_B (0) #define MICROPY_PORT_C (0) -#define MICROPY_PORT_D (0) +#define MICROPY_PORT_D (0) #define CIRCUITPY_INTERNAL_NVM_SIZE 0 diff --git a/ports/atmel-samd/boards/kicksat-sprite/pins.c b/ports/atmel-samd/boards/kicksat-sprite/pins.c index 27ee903231..711406189d 100644 --- a/ports/atmel-samd/boards/kicksat-sprite/pins.c +++ b/ports/atmel-samd/boards/kicksat-sprite/pins.c @@ -8,20 +8,20 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_radioCS), MP_ROM_PTR(&pin_PA00) }, { MP_ROM_QSTR(MP_QSTR_WAKE), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_SHDWN), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_SHDWN), MP_ROM_PTR(&pin_PB10) }, { MP_ROM_QSTR(MP_QSTR_PWDWN), MP_ROM_PTR(&pin_PB11) }, { MP_ROM_QSTR(MP_QSTR_TST), MP_ROM_PTR(&pin_PA11) }, { MP_ROM_QSTR(MP_QSTR_FSYNC), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_VCLK), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_VCLK), MP_ROM_PTR(&pin_PA14) }, { MP_ROM_QSTR(MP_QSTR_FSYNC), MP_ROM_PTR(&pin_PA15) }, - { MP_ROM_QSTR(MP_QSTR_MD), MP_ROM_PTR(&pin_PA18) }, - { MP_ROM_QSTR(MP_QSTR_MC), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_MD), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_MC), MP_ROM_PTR(&pin_PA19) }, - { MP_ROM_QSTR(MP_QSTR_PA08), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, - { MP_ROM_QSTR(MP_QSTR_PA09), MP_ROM_PTR(&pin_PA09) }, - { MP_ROM_QSTR(MP_QSTR_PA06), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_DAC0), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_PA08), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_PA09), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_PA06), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_DAC0), MP_ROM_PTR(&pin_PA02) }, { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PB09) }, { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_PB08) }, diff --git a/ports/atmel-samd/boards/meowmeow/board.c b/ports/atmel-samd/boards/meowmeow/board.c index 5afe2fb655..76849c53e4 100644 --- a/ports/atmel-samd/boards/meowmeow/board.c +++ b/ports/atmel-samd/boards/meowmeow/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/metro_m0_express/board.c b/ports/atmel-samd/boards/metro_m0_express/board.c index bb1c5335c1..bb6ad8bc0d 100644 --- a/ports/atmel-samd/boards/metro_m0_express/board.c +++ b/ports/atmel-samd/boards/metro_m0_express/board.c @@ -27,8 +27,7 @@ #include "supervisor/board.h" #include "mpconfigboard.h" -void board_init(void) -{ +void board_init(void) { // struct port_config pin_conf; // port_get_config_defaults(&pin_conf); // diff --git a/ports/atmel-samd/boards/monster_m4sk/board.c b/ports/atmel-samd/boards/monster_m4sk/board.c index 2b757d0914..8ef0c6ff95 100644 --- a/ports/atmel-samd/boards/monster_m4sk/board.c +++ b/ports/atmel-samd/boards/monster_m4sk/board.c @@ -48,11 +48,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PA13, &pin_PA12, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -63,7 +63,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/nfc_copy_cat/board.c b/ports/atmel-samd/boards/nfc_copy_cat/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/nfc_copy_cat/board.c +++ b/ports/atmel-samd/boards/nfc_copy_cat/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/openbook_m4/board.c b/ports/atmel-samd/boards/openbook_m4/board.c index a110779a6a..d8184da73e 100644 --- a/ports/atmel-samd/boards/openbook_m4/board.c +++ b/ports/atmel-samd/boards/openbook_m4/board.c @@ -53,11 +53,11 @@ uint8_t stop_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PB13, &pin_PB15, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -68,7 +68,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_epaperdisplay_obj_t* display = &displays[0].epaper_display; + displayio_epaperdisplay_obj_t *display = &displays[0].epaper_display; display->base.type = &displayio_epaperdisplay_type; common_hal_displayio_epaperdisplay_construct(display, bus, diff --git a/ports/atmel-samd/boards/pewpew_m4/board.c b/ports/atmel-samd/boards/pewpew_m4/board.c index 26bd53cad1..88c5bd9698 100644 --- a/ports/atmel-samd/boards/pewpew_m4/board.c +++ b/ports/atmel-samd/boards/pewpew_m4/board.c @@ -57,8 +57,9 @@ uint32_t lookupCfg(uint32_t key, uint32_t defl) { } else { ptr += 4; while (*ptr) { - if (*ptr == key) + if (*ptr == key) { return ptr[1]; + } ptr += 2; } } @@ -84,23 +85,23 @@ uint8_t display_init_sequence[] = { // fix on VTL 0x3a, 1, 0x05, // COLMOD - 16bit color 0xe0, 16, 0x02, 0x1c, 0x07, 0x12, // _GMCTRP1 Gamma - 0x37, 0x32, 0x29, 0x2d, - 0x29, 0x25, 0x2B, 0x39, - 0x00, 0x01, 0x03, 0x10, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, 0xe1, 16, 0x03, 0x1d, 0x07, 0x06, // _GMCTRN1 - 0x2E, 0x2C, 0x29, 0x2D, - 0x2E, 0x2E, 0x37, 0x3F, - 0x00, 0x00, 0x02, 0x10, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, 0x13, 0 | DELAY, 10, // _NORON 0x29, 0 | DELAY, 100, // _DISPON }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PA13, &pin_PA15, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -114,7 +115,7 @@ void board_init(void) { uint32_t cfg0 = lookupCfg(CFG_DISPLAY_CFG0, 0x000000); uint32_t offX = (cfg0 >> 8) & 0xff; uint32_t offY = (cfg0 >> 16) & 0xff; - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/picoplanet/mpconfigboard.h b/ports/atmel-samd/boards/picoplanet/mpconfigboard.h index 61430e06c2..30a9169e04 100644 --- a/ports/atmel-samd/boards/picoplanet/mpconfigboard.h +++ b/ports/atmel-samd/boards/picoplanet/mpconfigboard.h @@ -33,10 +33,10 @@ #define DEFAULT_SPI_BUS_SCK (&pin_PA17) #define DEFAULT_SPI_BUS_MOSI (&pin_PA16) -//#define CP_RGB_STATUS_R (&pin_PA06) -//#define CP_RGB_STATUS_G (&pin_PA05) -//#define CP_RGB_STATUS_B (&pin_PA07) -//#define CP_RGB_STATUS_INVERTED_PWM -//#define CP_RGB_STATUS_LED +// #define CP_RGB_STATUS_R (&pin_PA06) +// #define CP_RGB_STATUS_G (&pin_PA05) +// #define CP_RGB_STATUS_B (&pin_PA07) +// #define CP_RGB_STATUS_INVERTED_PWM +// #define CP_RGB_STATUS_LED #define MICROPY_HW_LED_STATUS (&pin_PA06) diff --git a/ports/atmel-samd/boards/pirkey_m0/board.c b/ports/atmel-samd/boards/pirkey_m0/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/pirkey_m0/board.c +++ b/ports/atmel-samd/boards/pirkey_m0/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/pybadge/board.c b/ports/atmel-samd/boards/pybadge/board.c index 188bf7bf6c..4adf10710e 100644 --- a/ports/atmel-samd/boards/pybadge/board.c +++ b/ports/atmel-samd/boards/pybadge/board.c @@ -56,13 +56,13 @@ uint8_t display_init_sequence[] = { // fix on VTL 0x3a, 1, 0x05, // COLMOD - 16bit color 0xe0, 16, 0x02, 0x1c, 0x07, 0x12, // _GMCTRP1 Gamma - 0x37, 0x32, 0x29, 0x2d, - 0x29, 0x25, 0x2B, 0x39, - 0x00, 0x01, 0x03, 0x10, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, 0xe1, 16, 0x03, 0x1d, 0x07, 0x06, // _GMCTRN1 - 0x2E, 0x2C, 0x29, 0x2D, - 0x2E, 0x2E, 0x37, 0x3F, - 0x00, 0x00, 0x02, 0x10, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, 0x2a, 3, 0x02, 0x00, 0x81, // _CASET XSTART = 2, XEND = 129 0x2b, 3, 0x02, 0x00, 0x81, // _RASET XSTART = 2, XEND = 129 0x13, 0 | DELAY, 10, // _NORON @@ -70,11 +70,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PB13, &pin_PB15, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -85,7 +85,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/pybadge_airlift/board.c b/ports/atmel-samd/boards/pybadge_airlift/board.c index de7eeda096..fe3549a64a 100644 --- a/ports/atmel-samd/boards/pybadge_airlift/board.c +++ b/ports/atmel-samd/boards/pybadge_airlift/board.c @@ -48,11 +48,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PB13, &pin_PB15, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -63,7 +63,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/pybadge_airlift/pins.c b/ports/atmel-samd/boards/pybadge_airlift/pins.c index cdf8071da8..cce9b04420 100644 --- a/ports/atmel-samd/boards/pybadge_airlift/pins.c +++ b/ports/atmel-samd/boards/pybadge_airlift/pins.c @@ -68,5 +68,6 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { {MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj)}, {MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj)}, - {MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display)}}; + {MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display)} +}; MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/pycubed/board.c b/ports/atmel-samd/boards/pycubed/board.c index f092a8d20e..2777b9031c 100644 --- a/ports/atmel-samd/boards/pycubed/board.c +++ b/ports/atmel-samd/boards/pycubed/board.c @@ -37,10 +37,10 @@ nvm_bytearray_obj_t bootcnt = { .base = { .type = &nvm_bytearray_type - }, - .len = ( uint32_t) 8192, - .start_address = (uint8_t*) (0x00080000 - 8192) - }; + }, + .len = (uint32_t)8192, + .start_address = (uint8_t *)(0x00080000 - 8192) +}; void board_init(void) { diff --git a/ports/atmel-samd/boards/pycubed/mpconfigboard.h b/ports/atmel-samd/boards/pycubed/mpconfigboard.h index fc16e22b59..244f41da38 100644 --- a/ports/atmel-samd/boards/pycubed/mpconfigboard.h +++ b/ports/atmel-samd/boards/pycubed/mpconfigboard.h @@ -7,9 +7,9 @@ #define MICROPY_HW_NEOPIXEL (&pin_PA21) #define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11) -#define MICROPY_PORT_B ( PORT_PB10 | PORT_PB11) +#define MICROPY_PORT_B (PORT_PB10 | PORT_PB11) #define MICROPY_PORT_C (0) -#define MICROPY_PORT_D (0) +#define MICROPY_PORT_D (0) #define AUTORESET_DELAY_MS 500 diff --git a/ports/atmel-samd/boards/pycubed_mram/board.c b/ports/atmel-samd/boards/pycubed_mram/board.c index f092a8d20e..2777b9031c 100644 --- a/ports/atmel-samd/boards/pycubed_mram/board.c +++ b/ports/atmel-samd/boards/pycubed_mram/board.c @@ -37,10 +37,10 @@ nvm_bytearray_obj_t bootcnt = { .base = { .type = &nvm_bytearray_type - }, - .len = ( uint32_t) 8192, - .start_address = (uint8_t*) (0x00080000 - 8192) - }; + }, + .len = (uint32_t)8192, + .start_address = (uint8_t *)(0x00080000 - 8192) +}; void board_init(void) { diff --git a/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.h b/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.h index e2a733025d..0d49e1b00f 100644 --- a/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.h +++ b/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.h @@ -8,7 +8,7 @@ #define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11) #define MICROPY_PORT_B (PORT_PA21 | PORT_PB10 | PORT_PB11) #define MICROPY_PORT_C (0) -#define MICROPY_PORT_D (0) +#define MICROPY_PORT_D (0) #define SPI_FLASH_WP_PIN &pin_PA10 #define SPI_FLASH_HOLD_PIN &pin_PA11 diff --git a/ports/atmel-samd/boards/pygamer/board.c b/ports/atmel-samd/boards/pygamer/board.c index 4614e347cd..11e18f1271 100644 --- a/ports/atmel-samd/boards/pygamer/board.c +++ b/ports/atmel-samd/boards/pygamer/board.c @@ -56,13 +56,13 @@ uint8_t display_init_sequence[] = { // fix on VTL 0x3a, 1, 0x05, // COLMOD - 16bit color 0xe0, 16, 0x02, 0x1c, 0x07, 0x12, // _GMCTRP1 Gamma - 0x37, 0x32, 0x29, 0x2d, - 0x29, 0x25, 0x2B, 0x39, - 0x00, 0x01, 0x03, 0x10, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, 0xe1, 16, 0x03, 0x1d, 0x07, 0x06, // _GMCTRN1 - 0x2E, 0x2C, 0x29, 0x2D, - 0x2E, 0x2E, 0x37, 0x3F, - 0x00, 0x00, 0x02, 0x10, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, 0x2a, 3, 0x02, 0x00, 0x81, // _CASET XSTART = 2, XEND = 129 0x2b, 3, 0x02, 0x00, 0x81, // _RASET XSTART = 2, XEND = 129 0x13, 0 | DELAY, 10, // _NORON @@ -70,11 +70,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PB13, &pin_PB15, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -85,7 +85,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/pygamer_advance/board.c b/ports/atmel-samd/boards/pygamer_advance/board.c index 39bf65602e..0711c4298a 100644 --- a/ports/atmel-samd/boards/pygamer_advance/board.c +++ b/ports/atmel-samd/boards/pygamer_advance/board.c @@ -48,11 +48,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PB13, &pin_PB12, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -63,7 +63,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/pyportal/board.c b/ports/atmel-samd/boards/pyportal/board.c index db474a8209..6fd1696897 100644 --- a/ports/atmel-samd/boards/pyportal/board.c +++ b/ports/atmel-samd/boards/pyportal/board.c @@ -53,15 +53,15 @@ uint8_t display_init_sequence[] = { 0xF2, 1, 0x00, // 3Gamma Function Disable 0x26, 1, 0x01, // Gamma curve selected 0xe0, 15, 0x0F, 0x31, 0x2B, 0x0C, 0x0E, 0x08, // Set Gamma - 0x4E, 0xF1, 0x37, 0x07, 0x10, 0x03, 0x0E, 0x09, 0x00, + 0x4E, 0xF1, 0x37, 0x07, 0x10, 0x03, 0x0E, 0x09, 0x00, 0xe1, 15, 0x00, 0x0E, 0x14, 0x03, 0x11, 0x07, // Set Gamma - 0x31, 0xC1, 0x48, 0x08, 0x0F, 0x0C, 0x31, 0x36, 0x0F, + 0x31, 0xC1, 0x48, 0x08, 0x0F, 0x0C, 0x31, 0x36, 0x0F, 0x11, DELAY, 120, // Exit Sleep 0x29, DELAY, 120, // Display on }; void board_init(void) { - displayio_parallelbus_obj_t* bus = &displays[0].parallel_bus; + displayio_parallelbus_obj_t *bus = &displays[0].parallel_bus; bus->base.type = &displayio_parallelbus_type; common_hal_displayio_parallelbus_construct(bus, &pin_PA16, // Data0 @@ -71,7 +71,7 @@ void board_init(void) { &pin_PB04, // Read &pin_PA00); // Reset - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/pyportal/mpconfigboard.h b/ports/atmel-samd/boards/pyportal/mpconfigboard.h index 00c376ad90..351647b122 100644 --- a/ports/atmel-samd/boards/pyportal/mpconfigboard.h +++ b/ports/atmel-samd/boards/pyportal/mpconfigboard.h @@ -11,10 +11,10 @@ // These are pins not to reset. // QSPI Data pins -#define MICROPY_PORT_A ( PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11 ) +#define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11) // QSPI CS, and QSPI SCK -#define MICROPY_PORT_B ( PORT_PB10 | PORT_PB11 | PORT_PB22 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (PORT_PB10 | PORT_PB11 | PORT_PB22) +#define MICROPY_PORT_C (0) #define MICROPY_PORT_D (0) #define DEFAULT_I2C_BUS_SCL (&pin_PB03) diff --git a/ports/atmel-samd/boards/pyportal_titano/board.c b/ports/atmel-samd/boards/pyportal_titano/board.c index 59a25c4acf..d219ba7948 100644 --- a/ports/atmel-samd/boards/pyportal_titano/board.c +++ b/ports/atmel-samd/boards/pyportal_titano/board.c @@ -37,48 +37,48 @@ #define DELAY 0x80 uint8_t display_init_sequence[] = { - 0x01, DELAY, 100/5, // Soft reset, then delay 10 ms + 0x01, DELAY, 100 / 5, // Soft reset, then delay 10 ms 0xB9, 3, 0xFF, 0x83, 0x57, // Extension command set - 0xFF, DELAY, 500/5, + 0xFF, DELAY, 500 / 5, 0xB3, 4, 0x80, 0x00, 0x06, 0x06, // 0x80 enables SDO pin (0x00 disables) 0xB6, 2, 0x01, 0x25, // -1.52V 0xB0, 1, 0x68, // Normal mode 70Hz, Idle mode 55 Hz 0xCC, 1, 0x05, 0xB1, 6, - 0x00, // Not deep standby - 0x15, // BT - 0x1C, // VSPR - 0x1C, // VSNR - 0x83, // AP - 0xAA, // FS + 0x00, // Not deep standby + 0x15, // BT + 0x1C, // VSPR + 0x1C, // VSNR + 0x83, // AP + 0xAA, // FS 0xC0, 6, - 0x50, // OPON normal - 0x50, // OPON idle - 0x01, // STBA - 0x3C, // STBA - 0x1E, // STBA - 0x08, // GEN + 0x50, // OPON normal + 0x50, // OPON idle + 0x01, // STBA + 0x3C, // STBA + 0x1E, // STBA + 0x08, // GEN 0xB4, 7, - 0x02, // NW 0x02 - 0x40, // RTN - 0x00, // DIV - 0x2A, // DUM - 0x2A, // DUM - 0x0D, // GDON - 0x78, // GDOFF + 0x02, // NW 0x02 + 0x40, // RTN + 0x00, // DIV + 0x2A, // DUM + 0x2A, // DUM + 0x0D, // GDON + 0x78, // GDOFF 0xE0, 34, - 0x02, 0x0A, 0x11, 0x1d, 0x23, 0x35, 0x41, 0x4b, 0x4b, - 0x42, 0x3A, 0x27, 0x1B, 0x08, 0x09, 0x03, 0x02, 0x0A, - 0x11, 0x1d, 0x23, 0x35, 0x41, 0x4b, 0x4b, 0x42, 0x3A, - 0x27, 0x1B, 0x08, 0x09, 0x03, 0x00, 0x01, + 0x02, 0x0A, 0x11, 0x1d, 0x23, 0x35, 0x41, 0x4b, 0x4b, + 0x42, 0x3A, 0x27, 0x1B, 0x08, 0x09, 0x03, 0x02, 0x0A, + 0x11, 0x1d, 0x23, 0x35, 0x41, 0x4b, 0x4b, 0x42, 0x3A, + 0x27, 0x1B, 0x08, 0x09, 0x03, 0x00, 0x01, 0x3a, 1, 0x55, 0x36, 1, 0x60, - 0x11, DELAY, 150/5, // Exit Sleep, then delay 150 ms - 0x29, DELAY, 50/5 + 0x11, DELAY, 150 / 5, // Exit Sleep, then delay 150 ms + 0x29, DELAY, 50 / 5 }; void board_init(void) { - displayio_parallelbus_obj_t* bus = &displays[0].parallel_bus; + displayio_parallelbus_obj_t *bus = &displays[0].parallel_bus; bus->base.type = &displayio_parallelbus_type; common_hal_displayio_parallelbus_construct(bus, &pin_PA16, // Data0 @@ -88,7 +88,7 @@ void board_init(void) { &pin_PB04, // Read &pin_PA00); // Reset - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/pyportal_titano/mpconfigboard.h b/ports/atmel-samd/boards/pyportal_titano/mpconfigboard.h index a76f1db5c8..61c6117d96 100644 --- a/ports/atmel-samd/boards/pyportal_titano/mpconfigboard.h +++ b/ports/atmel-samd/boards/pyportal_titano/mpconfigboard.h @@ -9,10 +9,10 @@ // These are pins not to reset. // QSPI Data pins -#define MICROPY_PORT_A ( PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11 ) +#define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11) // QSPI CS, and QSPI SCK -#define MICROPY_PORT_B ( PORT_PB10 | PORT_PB11 | PORT_PB22 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (PORT_PB10 | PORT_PB11 | PORT_PB22) +#define MICROPY_PORT_C (0) #define MICROPY_PORT_D (0) #define DEFAULT_I2C_BUS_SCL (&pin_PB03) diff --git a/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.h b/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.h index c66873aeb2..4e482cff5a 100644 --- a/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.h +++ b/ports/atmel-samd/boards/robohatmm1_m4/mpconfigboard.h @@ -28,8 +28,8 @@ #define DEFAULT_SPI_BUS_MOSI (&pin_PB08) #define DEFAULT_SPI_BUS_MISO (&pin_PB11) -//#define DEFAULT_UART_BUS_RX (&pin_PB03) -//#define DEFAULT_UART_BUS_TX (&pin_PB02) +// #define DEFAULT_UART_BUS_RX (&pin_PB03) +// #define DEFAULT_UART_BUS_TX (&pin_PB02) // USB is always used internally so skip the pin objects for it. #define IGNORE_PIN_PA24 1 diff --git a/ports/atmel-samd/boards/robohatmm1_m4/pins.c b/ports/atmel-samd/boards/robohatmm1_m4/pins.c index 74dcfd651f..32959ef3f2 100644 --- a/ports/atmel-samd/boards/robohatmm1_m4/pins.c +++ b/ports/atmel-samd/boards/robohatmm1_m4/pins.c @@ -1,91 +1,91 @@ #include "shared-bindings/board/__init__.h" // Version 2.4 STATIC const mp_rom_map_elem_t board_global_dict_table[] = { - // SERVO Pins - { MP_ROM_QSTR(MP_QSTR_SERVO1), MP_ROM_PTR(&pin_PA18) }, - { MP_ROM_QSTR(MP_QSTR_SERVO2), MP_ROM_PTR(&pin_PA19) }, - { MP_ROM_QSTR(MP_QSTR_SERVO3), MP_ROM_PTR(&pin_PA20) }, - { MP_ROM_QSTR(MP_QSTR_SERVO4), MP_ROM_PTR(&pin_PA21) }, - { MP_ROM_QSTR(MP_QSTR_SERVO5), MP_ROM_PTR(&pin_PA11) }, - { MP_ROM_QSTR(MP_QSTR_SERVO6), MP_ROM_PTR(&pin_PA10) }, - { MP_ROM_QSTR(MP_QSTR_SERVO7), MP_ROM_PTR(&pin_PA09) }, - { MP_ROM_QSTR(MP_QSTR_SERVO8), MP_ROM_PTR(&pin_PA08) }, + // SERVO Pins + { MP_ROM_QSTR(MP_QSTR_SERVO1), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_SERVO2), MP_ROM_PTR(&pin_PA19) }, + { MP_ROM_QSTR(MP_QSTR_SERVO3), MP_ROM_PTR(&pin_PA20) }, + { MP_ROM_QSTR(MP_QSTR_SERVO4), MP_ROM_PTR(&pin_PA21) }, + { MP_ROM_QSTR(MP_QSTR_SERVO5), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_SERVO6), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_SERVO7), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_SERVO8), MP_ROM_PTR(&pin_PA08) }, - // RCC Pins - { MP_ROM_QSTR(MP_QSTR_RCC1), MP_ROM_PTR(&pin_PA07) }, - { MP_ROM_QSTR(MP_QSTR_RCC2), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_RCC3), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_RCC4), MP_ROM_PTR(&pin_PA04) }, + // RCC Pins + { MP_ROM_QSTR(MP_QSTR_RCC1), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_RCC2), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_RCC3), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_RCC4), MP_ROM_PTR(&pin_PA04) }, - // Special Function - { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_PA02) }, - { MP_ROM_QSTR(MP_QSTR_BATTERY), MP_ROM_PTR(&pin_PA02) }, - { MP_ROM_QSTR(MP_QSTR_POWER_OFF), MP_ROM_PTR(&pin_PA03) }, - { MP_ROM_QSTR(MP_QSTR_POWER_DISABLE), MP_ROM_PTR(&pin_PA03) }, - { MP_ROM_QSTR(MP_QSTR_POWER_ON), MP_ROM_PTR(&pin_PA27) }, - { MP_ROM_QSTR(MP_QSTR_POWER_ENABLE), MP_ROM_PTR(&pin_PA27) }, - { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_PA27) }, + // Special Function + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_BATTERY), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_POWER_OFF), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_POWER_DISABLE), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_POWER_ON), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_POWER_ENABLE), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_PA27) }, - { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PB23) }, - { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PB22) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PB22) }, - // GROVE on SERCOM0 - { MP_ROM_QSTR(MP_QSTR_GROVE_SCL), MP_ROM_PTR(&pin_PA09) }, - { MP_ROM_QSTR(MP_QSTR_GROVE_SDA), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_GROVE_RX), MP_ROM_PTR(&pin_PA09) }, - { MP_ROM_QSTR(MP_QSTR_GROVE_TX), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_GROVE_D1), MP_ROM_PTR(&pin_PA09) }, - { MP_ROM_QSTR(MP_QSTR_GROVE_D0), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_GROVE_A1), MP_ROM_PTR(&pin_PA09) }, - { MP_ROM_QSTR(MP_QSTR_GROVE_A0), MP_ROM_PTR(&pin_PA08) }, + // GROVE on SERCOM0 + { MP_ROM_QSTR(MP_QSTR_GROVE_SCL), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_GROVE_SDA), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_GROVE_RX), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_GROVE_TX), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_GROVE_D1), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_GROVE_D0), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_GROVE_A1), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_GROVE_A0), MP_ROM_PTR(&pin_PA08) }, - // UART on SERCOM0 - { MP_ROM_QSTR(MP_QSTR_UART_TX), MP_ROM_PTR(&pin_PA04) }, - { MP_ROM_QSTR(MP_QSTR_UART_RX), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_UART_CTS), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_UART_RTS), MP_ROM_PTR(&pin_PA07) }, + // UART on SERCOM0 + { MP_ROM_QSTR(MP_QSTR_UART_TX), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_UART_RX), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_UART_CTS), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_UART_RTS), MP_ROM_PTR(&pin_PA07) }, - // UART on SERCOM1 (Raspberry Pi) - { MP_ROM_QSTR(MP_QSTR_TX1), MP_ROM_PTR(&pin_PA16) }, - { MP_ROM_QSTR(MP_QSTR_RX1), MP_ROM_PTR(&pin_PA17) }, - { MP_ROM_QSTR(MP_QSTR_PI_TX), MP_ROM_PTR(&pin_PA16) }, - { MP_ROM_QSTR(MP_QSTR_PI_RX), MP_ROM_PTR(&pin_PA17) }, + // UART on SERCOM1 (Raspberry Pi) + { MP_ROM_QSTR(MP_QSTR_TX1), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_RX1), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_PI_TX), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_PI_RX), MP_ROM_PTR(&pin_PA17) }, - // I2C on SERCOM1 (External Connector) - { MP_ROM_QSTR(MP_QSTR_SDA1), MP_ROM_PTR(&pin_PA00) }, - { MP_ROM_QSTR(MP_QSTR_SCL1), MP_ROM_PTR(&pin_PA01) }, + // I2C on SERCOM1 (External Connector) + { MP_ROM_QSTR(MP_QSTR_SDA1), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_SCL1), MP_ROM_PTR(&pin_PA01) }, - // SPI Flash on SERCOM2 - { MP_ROM_QSTR(MP_QSTR_FLASH_SCK), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_FLASH_MISO), MP_ROM_PTR(&pin_PA14) }, - { MP_ROM_QSTR(MP_QSTR_FLASH_MOSI), MP_ROM_PTR(&pin_PA12) }, - { MP_ROM_QSTR(MP_QSTR_FLASH_CS), MP_ROM_PTR(&pin_PA15) }, + // SPI Flash on SERCOM2 + { MP_ROM_QSTR(MP_QSTR_FLASH_SCK), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_FLASH_MISO), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_FLASH_MOSI), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_FLASH_CS), MP_ROM_PTR(&pin_PA15) }, - // I2C on SERCOM3 (RPi & Internal) - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA22) }, - { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA23) }, - { MP_ROM_QSTR(MP_QSTR_PI_SDA), MP_ROM_PTR(&pin_PA22) }, - { MP_ROM_QSTR(MP_QSTR_PI_SCL), MP_ROM_PTR(&pin_PA23) }, + // I2C on SERCOM3 (RPi & Internal) + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PA23) }, + { MP_ROM_QSTR(MP_QSTR_PI_SDA), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_PI_SCL), MP_ROM_PTR(&pin_PA23) }, - // SPI on SERCOM4 - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PB08) }, - { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PB09) }, - { MP_ROM_QSTR(MP_QSTR_SS), MP_ROM_PTR(&pin_PB10) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PB11) }, + // SPI on SERCOM4 + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_SS), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PB11) }, - // GPS on SERCOM5 - { MP_ROM_QSTR(MP_QSTR_GPS_TX), MP_ROM_PTR(&pin_PB02) }, - { MP_ROM_QSTR(MP_QSTR_GPS_RX), MP_ROM_PTR(&pin_PB03) }, + // GPS on SERCOM5 + { MP_ROM_QSTR(MP_QSTR_GPS_TX), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_GPS_RX), MP_ROM_PTR(&pin_PB03) }, - // Raspberry Pi - { MP_ROM_QSTR(MP_QSTR_PI_GP25), MP_ROM_PTR(&pin_PA30) }, - { MP_ROM_QSTR(MP_QSTR_SWCLK), MP_ROM_PTR(&pin_PA30) }, - { MP_ROM_QSTR(MP_QSTR_PI_GP24), MP_ROM_PTR(&pin_PA31) }, - { MP_ROM_QSTR(MP_QSTR_SWDIO), MP_ROM_PTR(&pin_PA31) }, + // Raspberry Pi + { MP_ROM_QSTR(MP_QSTR_PI_GP25), MP_ROM_PTR(&pin_PA30) }, + { MP_ROM_QSTR(MP_QSTR_SWCLK), MP_ROM_PTR(&pin_PA30) }, + { MP_ROM_QSTR(MP_QSTR_PI_GP24), MP_ROM_PTR(&pin_PA31) }, + { MP_ROM_QSTR(MP_QSTR_SWDIO), MP_ROM_PTR(&pin_PA31) }, - { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, - { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + // { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/atmel-samd/boards/sam32/mpconfigboard.h b/ports/atmel-samd/boards/sam32/mpconfigboard.h index 364d380d1d..19f326782a 100644 --- a/ports/atmel-samd/boards/sam32/mpconfigboard.h +++ b/ports/atmel-samd/boards/sam32/mpconfigboard.h @@ -11,7 +11,7 @@ #define MICROPY_PORT_D (0) #define CIRCUITPY_INTERNAL_NVM_SIZE 0 -#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (128*1024) +#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (128 * 1024) #define BOARD_HAS_CRYSTAL 1 diff --git a/ports/atmel-samd/boards/same54_xplained/mpconfigboard.h b/ports/atmel-samd/boards/same54_xplained/mpconfigboard.h index 934559a2a4..dbdd1aaa6a 100644 --- a/ports/atmel-samd/boards/same54_xplained/mpconfigboard.h +++ b/ports/atmel-samd/boards/same54_xplained/mpconfigboard.h @@ -9,9 +9,9 @@ // These are pins not to reset. // QSPI Data pins -#define MICROPY_PORT_A ( PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11 ) +#define MICROPY_PORT_A (PORT_PA08 | PORT_PA09 | PORT_PA10 | PORT_PA11) // QSPI CS, and QSPI SCK -#define MICROPY_PORT_B ( PORT_PB10 | PORT_PB11 ) +#define MICROPY_PORT_B (PORT_PB10 | PORT_PB11) #define MICROPY_PORT_C (0) #define MICROPY_PORT_D (0) diff --git a/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c b/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c index 53c43cd441..fe2393a572 100644 --- a/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c +++ b/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c @@ -65,11 +65,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_PB20, &pin_PB19, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -80,7 +80,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, @@ -112,23 +112,23 @@ void board_init(void) { true, // backlight_on_high false); // SH1107_addressing - // Enabling the Power of the 40-pin at the back - CTR_5V.base.type = &digitalio_digitalinout_type; - CTR_3V3.base.type = &digitalio_digitalinout_type; - USB_HOST_ENABLE.base.type = &digitalio_digitalinout_type; + // Enabling the Power of the 40-pin at the back + CTR_5V.base.type = &digitalio_digitalinout_type; + CTR_3V3.base.type = &digitalio_digitalinout_type; + USB_HOST_ENABLE.base.type = &digitalio_digitalinout_type; - common_hal_digitalio_digitalinout_construct(&CTR_5V, PIN_CTR_5V); - common_hal_digitalio_digitalinout_construct(&CTR_3V3, PIN_CTR_3V3); - common_hal_digitalio_digitalinout_construct(&USB_HOST_ENABLE, PIN_USB_HOST_ENABLE); + common_hal_digitalio_digitalinout_construct(&CTR_5V, PIN_CTR_5V); + common_hal_digitalio_digitalinout_construct(&CTR_3V3, PIN_CTR_3V3); + common_hal_digitalio_digitalinout_construct(&USB_HOST_ENABLE, PIN_USB_HOST_ENABLE); - common_hal_digitalio_digitalinout_set_value(&CTR_5V, true); - common_hal_digitalio_digitalinout_set_value(&CTR_3V3, false); - common_hal_digitalio_digitalinout_set_value(&USB_HOST_ENABLE, false); + common_hal_digitalio_digitalinout_set_value(&CTR_5V, true); + common_hal_digitalio_digitalinout_set_value(&CTR_3V3, false); + common_hal_digitalio_digitalinout_set_value(&USB_HOST_ENABLE, false); - // Never reset - common_hal_digitalio_digitalinout_never_reset(&CTR_5V); - common_hal_digitalio_digitalinout_never_reset(&CTR_3V3); - common_hal_digitalio_digitalinout_never_reset(&USB_HOST_ENABLE); + // Never reset + common_hal_digitalio_digitalinout_never_reset(&CTR_5V); + common_hal_digitalio_digitalinout_never_reset(&CTR_3V3); + common_hal_digitalio_digitalinout_never_reset(&USB_HOST_ENABLE); } diff --git a/ports/atmel-samd/boards/seeeduino_wio_terminal/pins.c b/ports/atmel-samd/boards/seeeduino_wio_terminal/pins.c index 0558191e63..45ff7c3361 100644 --- a/ports/atmel-samd/boards/seeeduino_wio_terminal/pins.c +++ b/ports/atmel-samd/boards/seeeduino_wio_terminal/pins.c @@ -26,7 +26,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PA06) }, { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PA17) }, // MP_QSTR_SDA - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PA16) }, //MP_QSTR_SCL + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PA16) }, // MP_QSTR_SCL { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA15) }, // MP_QSTR_LED // UART pins diff --git a/ports/atmel-samd/boards/snekboard/board.c b/ports/atmel-samd/boards/snekboard/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/snekboard/board.c +++ b/ports/atmel-samd/boards/snekboard/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/snekboard/mpconfigboard.h b/ports/atmel-samd/boards/snekboard/mpconfigboard.h index 1c0804fe72..bea90a0fae 100644 --- a/ports/atmel-samd/boards/snekboard/mpconfigboard.h +++ b/ports/atmel-samd/boards/snekboard/mpconfigboard.h @@ -12,16 +12,16 @@ // These are pins not to reset. #define MICROPY_PORT_A (PORT_PB11) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define BOARD_HAS_CRYSTAL 0 -#define DEFAULT_I2C_BUS_SCL (&pin_PA08) /* ANALOG 5 */ -#define DEFAULT_I2C_BUS_SDA (&pin_PA09) /* ANALOG 6 */ +#define DEFAULT_I2C_BUS_SCL (&pin_PA08) /* ANALOG 5 */ +#define DEFAULT_I2C_BUS_SDA (&pin_PA09) /* ANALOG 6 */ -#define DEFAULT_UART_BUS_RX (&pin_PB08) /* ANALOG 1 */ -#define DEFAULT_UART_BUS_TX (&pin_PB09) /* ANALOG 2 */ +#define DEFAULT_UART_BUS_RX (&pin_PB08) /* ANALOG 1 */ +#define DEFAULT_UART_BUS_TX (&pin_PB09) /* ANALOG 2 */ // USB is always used internally so skip the pin objects for it. #define IGNORE_PIN_PA24 1 diff --git a/ports/atmel-samd/boards/sparkfun_lumidrive/board.c b/ports/atmel-samd/boards/sparkfun_lumidrive/board.c old mode 100755 new mode 100644 index 6baa43ffaa..84960e73cf --- a/ports/atmel-samd/boards/sparkfun_lumidrive/board.c +++ b/ports/atmel-samd/boards/sparkfun_lumidrive/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/sparkfun_lumidrive/mpconfigboard.h b/ports/atmel-samd/boards/sparkfun_lumidrive/mpconfigboard.h old mode 100755 new mode 100644 index 80f37429fa..836261bf8d --- a/ports/atmel-samd/boards/sparkfun_lumidrive/mpconfigboard.h +++ b/ports/atmel-samd/boards/sparkfun_lumidrive/mpconfigboard.h @@ -9,17 +9,17 @@ #define SPI_FLASH_SCK_PIN &pin_PA09 #define SPI_FLASH_CS_PIN &pin_PA13 -#define MICROPY_PORT_A ( 0 ) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define BOARD_HAS_CRYSTAL 1 -//I2C +// I2C #define DEFAULT_I2C_BUS_SCL (&pin_PA23) #define DEFAULT_I2C_BUS_SDA (&pin_PA22) -//SPI +// SPI #define DEFAULT_SPI_BUS_SCK (&pin_PA19) #define DEFAULT_SPI_BUS_MOSI (&pin_PA18) #define DEFAULT_SPI_BUS_MISO (&pin_PA21) diff --git a/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/board.c b/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/board.c +++ b/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/mpconfigboard.h b/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/mpconfigboard.h index dcce97b8da..c2527301ff 100644 --- a/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/mpconfigboard.h +++ b/ports/atmel-samd/boards/sparkfun_qwiic_micro_no_flash/mpconfigboard.h @@ -1,23 +1,23 @@ #define MICROPY_HW_BOARD_NAME "SparkFun Qwiic Micro" #define MICROPY_HW_MCU_NAME "samd21e18" -#define MICROPY_PORT_A ( 0 ) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define CALIBRATE_CRYSTALLESS 1 #define BOARD_HAS_CRYSTAL 0 -//I2C and Qwiic Connector +// I2C and Qwiic Connector #define DEFAULT_I2C_BUS_SCL (&pin_PA09) #define DEFAULT_I2C_BUS_SDA (&pin_PA08) -//SPI +// SPI #define DEFAULT_SPI_BUS_SCK (&pin_PA07) #define DEFAULT_SPI_BUS_MOSI (&pin_PA06) #define DEFAULT_SPI_BUS_MISO (&pin_PA05) -//UART +// UART #define DEFAULT_UART_BUS_RX (&pin_PA23) #define DEFAULT_UART_BUS_TX (&pin_PA22) diff --git a/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/board.c b/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/board.c +++ b/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/mpconfigboard.h b/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/mpconfigboard.h index c9b195eef4..4fb43629b4 100644 --- a/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/mpconfigboard.h +++ b/ports/atmel-samd/boards/sparkfun_qwiic_micro_with_flash/mpconfigboard.h @@ -9,23 +9,23 @@ #define SPI_FLASH_SCK_PIN &pin_PA17 #define SPI_FLASH_CS_PIN &pin_PA19 -#define MICROPY_PORT_A ( 0 ) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define CALIBRATE_CRYSTALLESS 1 #define BOARD_HAS_CRYSTAL 0 -//I2C and Qwiic Connector +// I2C and Qwiic Connector #define DEFAULT_I2C_BUS_SCL (&pin_PA09) #define DEFAULT_I2C_BUS_SDA (&pin_PA08) -//SPI +// SPI #define DEFAULT_SPI_BUS_SCK (&pin_PA07) #define DEFAULT_SPI_BUS_MOSI (&pin_PA06) #define DEFAULT_SPI_BUS_MISO (&pin_PA05) -//UART +// UART #define DEFAULT_UART_BUS_RX (&pin_PA23) #define DEFAULT_UART_BUS_TX (&pin_PA22) diff --git a/ports/atmel-samd/boards/sparkfun_redboard_turbo/board.c b/ports/atmel-samd/boards/sparkfun_redboard_turbo/board.c old mode 100755 new mode 100644 index 6baa43ffaa..84960e73cf --- a/ports/atmel-samd/boards/sparkfun_redboard_turbo/board.c +++ b/ports/atmel-samd/boards/sparkfun_redboard_turbo/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.h b/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.h old mode 100755 new mode 100644 index ae272d502b..b4076523f4 --- a/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.h +++ b/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.h @@ -15,9 +15,9 @@ #define SPI_FLASH_SCK_PIN &pin_PB23 #define SPI_FLASH_CS_PIN &pin_PA13 -#define MICROPY_PORT_A ( 0 ) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_A (0) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define BOARD_HAS_CRYSTAL 1 diff --git a/ports/atmel-samd/boards/stackrduino_m0_pro/pins.c b/ports/atmel-samd/boards/stackrduino_m0_pro/pins.c index 95d2eb5a3d..e0278aca0d 100644 --- a/ports/atmel-samd/boards/stackrduino_m0_pro/pins.c +++ b/ports/atmel-samd/boards/stackrduino_m0_pro/pins.c @@ -23,16 +23,16 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PA20) }, { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PA21) }, { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PA06) }, { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PA07) }, { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PA18) }, { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA16) }, { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA19) }, { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA17) }, - { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PA28) }, - { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_PA28) }, - { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_CHRG_EN), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PA28) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_PA28) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_CHRG_EN), MP_ROM_PTR(&pin_PA13) }, { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, diff --git a/ports/atmel-samd/boards/uchip/mpconfigboard.h b/ports/atmel-samd/boards/uchip/mpconfigboard.h index 5d6af4b782..6b8435877a 100644 --- a/ports/atmel-samd/boards/uchip/mpconfigboard.h +++ b/ports/atmel-samd/boards/uchip/mpconfigboard.h @@ -3,7 +3,7 @@ #define MICROPY_HW_LED_STATUS (&pin_PA07) -#define MICROPY_PORT_A (PORT_PA00 | PORT_PA01 | PORT_PA14 | PORT_PA15 | PORT_PA28 | PORT_PA27 | PORT_PA24 | PORT_PA25) +#define MICROPY_PORT_A (PORT_PA00 | PORT_PA01 | PORT_PA14 | PORT_PA15 | PORT_PA28 | PORT_PA27 | PORT_PA24 | PORT_PA25) #define MICROPY_PORT_B (0) #define MICROPY_PORT_C (0) diff --git a/ports/atmel-samd/boards/ugame10/board.c b/ports/atmel-samd/boards/ugame10/board.c index 918fe2d59d..f17b60ff60 100644 --- a/ports/atmel-samd/boards/ugame10/board.c +++ b/ports/atmel-samd/boards/ugame10/board.c @@ -56,13 +56,13 @@ uint8_t display_init_sequence[] = { // fix on VTL 0x3a, 1, 0x05, // COLMOD - 16bit color 0xe0, 16, 0x02, 0x1c, 0x07, 0x12, // _GMCTRP1 Gamma - 0x37, 0x32, 0x29, 0x2d, - 0x29, 0x25, 0x2B, 0x39, - 0x00, 0x01, 0x03, 0x10, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, 0xe1, 16, 0x03, 0x1d, 0x07, 0x06, // _GMCTRN1 - 0x2E, 0x2C, 0x29, 0x2D, - 0x2E, 0x2E, 0x37, 0x3F, - 0x00, 0x00, 0x02, 0x10, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, 0x2a, 3, 0x02, 0x00, 0x81, // _CASET XSTART = 2, XEND = 129 0x2b, 3, 0x02, 0x00, 0x81, // _RASET XSTART = 2, XEND = 129 0x13, 0 | DELAY, 10, // _NORON @@ -70,7 +70,7 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; busio_spi_obj_t *spi = common_hal_board_create_spi(); common_hal_displayio_fourwire_construct(bus, @@ -82,7 +82,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/atmel-samd/boards/winterbloom_big_honking_button/board.c b/ports/atmel-samd/boards/winterbloom_big_honking_button/board.c index 6baa43ffaa..84960e73cf 100644 --- a/ports/atmel-samd/boards/winterbloom_big_honking_button/board.c +++ b/ports/atmel-samd/boards/winterbloom_big_honking_button/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.h b/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.h index 8d520f675b..67882f6335 100644 --- a/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.h +++ b/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.h @@ -10,8 +10,8 @@ // These are pins not to reset. #define MICROPY_PORT_A (PORT_PA00 | PORT_PA01) -#define MICROPY_PORT_B ( 0 ) -#define MICROPY_PORT_C ( 0 ) +#define MICROPY_PORT_B (0) +#define MICROPY_PORT_C (0) #define BOARD_HAS_CRYSTAL 0 diff --git a/ports/atmel-samd/boards/winterbloom_big_honking_button/usermods/_bhb/bhb.c b/ports/atmel-samd/boards/winterbloom_big_honking_button/usermods/_bhb/bhb.c index 54ce173d81..1a340ae226 100644 --- a/ports/atmel-samd/boards/winterbloom_big_honking_button/usermods/_bhb/bhb.c +++ b/ports/atmel-samd/boards/winterbloom_big_honking_button/usermods/_bhb/bhb.c @@ -15,18 +15,22 @@ STATIC mp_obj_t _bhb_init_adc(void) { /* Enable GCLK0 for the ADC */ GCLK->CLKCTRL.reg = GCLK_CLKCTRL_CLKEN | - GCLK_CLKCTRL_GEN_GCLK0 | - GCLK_CLKCTRL_ID_ADC; + GCLK_CLKCTRL_GEN_GCLK0 | + GCLK_CLKCTRL_ID_ADC; /* Wait for bus synchronization. */ - while (GCLK->STATUS.bit.SYNCBUSY) {}; + while (GCLK->STATUS.bit.SYNCBUSY) { + } + ; - uint32_t bias = (*((uint32_t *) ADC_FUSES_BIASCAL_ADDR) & ADC_FUSES_BIASCAL_Msk) >> ADC_FUSES_BIASCAL_Pos; - uint32_t linearity = (*((uint32_t *) ADC_FUSES_LINEARITY_0_ADDR) & ADC_FUSES_LINEARITY_0_Msk) >> ADC_FUSES_LINEARITY_0_Pos; - linearity |= ((*((uint32_t *) ADC_FUSES_LINEARITY_1_ADDR) & ADC_FUSES_LINEARITY_1_Msk) >> ADC_FUSES_LINEARITY_1_Pos) << 5; + uint32_t bias = (*((uint32_t *)ADC_FUSES_BIASCAL_ADDR) & ADC_FUSES_BIASCAL_Msk) >> ADC_FUSES_BIASCAL_Pos; + uint32_t linearity = (*((uint32_t *)ADC_FUSES_LINEARITY_0_ADDR) & ADC_FUSES_LINEARITY_0_Msk) >> ADC_FUSES_LINEARITY_0_Pos; + linearity |= ((*((uint32_t *)ADC_FUSES_LINEARITY_1_ADDR) & ADC_FUSES_LINEARITY_1_Msk) >> ADC_FUSES_LINEARITY_1_Pos) << 5; /* Wait for bus synchronization. */ - while (ADC->STATUS.bit.SYNCBUSY) {}; + while (ADC->STATUS.bit.SYNCBUSY) { + } + ; /* Write the calibration data. */ ADC->CALIB.reg = ADC_CALIB_BIAS_CAL(bias) | ADC_CALIB_LINEARITY_CAL(linearity); @@ -43,7 +47,7 @@ STATIC mp_obj_t _bhb_init_adc(void) { Set the resolution to 16 for averaging */ ADC->CTRLB.reg = ADC_CTRLB_PRESCALER_DIV32 | - ADC_CTRLB_RESSEL_16BIT; + ADC_CTRLB_RESSEL_16BIT; /* Configure the input parameters. @@ -56,8 +60,8 @@ STATIC mp_obj_t _bhb_init_adc(void) { - MUXPOS_PIN3 means that the ADC should read from AIN2, or PB08. */ ADC->INPUTCTRL.reg = ADC_INPUTCTRL_GAIN_DIV2 | - ADC_INPUTCTRL_MUXNEG_GND | - ADC_INPUTCTRL_MUXPOS_PIN2; + ADC_INPUTCTRL_MUXNEG_GND | + ADC_INPUTCTRL_MUXPOS_PIN2; /* Set PB08 as an input pin. */ @@ -70,7 +74,9 @@ STATIC mp_obj_t _bhb_init_adc(void) { PORT->Group[1].PMUX[4].reg |= PORT_PMUX_PMUXE_B; /* Wait for bus synchronization. */ - while (ADC->STATUS.bit.SYNCBUSY) {}; + while (ADC->STATUS.bit.SYNCBUSY) { + } + ; /* Enable the ADC. */ ADC->CTRLA.bit.ENABLE = true; @@ -83,13 +89,17 @@ STATIC mp_obj_t _bhb_init_adc(void) { STATIC mp_obj_t _bhb_read_adc(void) { /* Wait for bus synchronization. */ - while (ADC->STATUS.bit.SYNCBUSY) {}; + while (ADC->STATUS.bit.SYNCBUSY) { + } + ; /* Start the ADC using a software trigger. */ ADC->SWTRIG.bit.START = true; /* Wait for the result ready flag to be set. */ - while (ADC->INTFLAG.bit.RESRDY == 0); + while (ADC->INTFLAG.bit.RESRDY == 0) { + ; + } /* Clear the flag. */ ADC->INTFLAG.reg = ADC_INTFLAG_RESRDY; @@ -114,7 +124,7 @@ STATIC MP_DEFINE_CONST_DICT(_bhb_module_globals, _bhb_module_globals_table); const mp_obj_module_t _bhb_user_cmodule = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&_bhb_module_globals, + .globals = (mp_obj_dict_t *)&_bhb_module_globals, }; MP_REGISTER_MODULE(MP_QSTR__bhb, _bhb_user_cmodule, MODULE_BHB_ENABLED); diff --git a/ports/atmel-samd/boards/xinabox_cc03/board.c b/ports/atmel-samd/boards/xinabox_cc03/board.c index 112b173ecc..7af05ba45a 100644 --- a/ports/atmel-samd/boards/xinabox_cc03/board.c +++ b/ports/atmel-samd/boards/xinabox_cc03/board.c @@ -28,8 +28,7 @@ #include "mpconfigboard.h" #include "hal/include/hal_gpio.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/boards/xinabox_cs11/board.c b/ports/atmel-samd/boards/xinabox_cs11/board.c index 112b173ecc..7af05ba45a 100644 --- a/ports/atmel-samd/boards/xinabox_cs11/board.c +++ b/ports/atmel-samd/boards/xinabox_cs11/board.c @@ -28,8 +28,7 @@ #include "mpconfigboard.h" #include "hal/include/hal_gpio.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/atmel-samd/common-hal/_pew/PewPew.c b/ports/atmel-samd/common-hal/_pew/PewPew.c index 1e7561ac8e..40cd52134a 100644 --- a/ports/atmel-samd/common-hal/_pew/PewPew.c +++ b/ports/atmel-samd/common-hal/_pew/PewPew.c @@ -47,7 +47,7 @@ void pewpew_interrupt_handler(uint8_t index) { if (index != pewpew_tc_index) { return; } - Tc* tc = tc_insts[index]; + Tc *tc = tc_insts[index]; if (!tc->COUNT16.INTFLAG.bit.MC0) { return; } @@ -60,7 +60,7 @@ void pewpew_interrupt_handler(uint8_t index) { } void pew_init() { - pew_obj_t* pew = MP_STATE_VM(pew_singleton); + pew_obj_t *pew = MP_STATE_VM(pew_singleton); common_hal_digitalio_digitalinout_switch_to_input(pew->buttons, PULL_UP); @@ -97,8 +97,8 @@ void pew_init() { #ifdef SAMD21 tc->COUNT16.CTRLA.reg = TC_CTRLA_MODE_COUNT16 | - TC_CTRLA_PRESCALER_DIV64 | - TC_CTRLA_WAVEGEN_MFRQ; + TC_CTRLA_PRESCALER_DIV64 | + TC_CTRLA_WAVEGEN_MFRQ; #endif #ifdef SAM_D5X_E5X tc_reset(tc); diff --git a/ports/atmel-samd/common-hal/_pew/PewPew.h b/ports/atmel-samd/common-hal/_pew/PewPew.h index a9c3b6626c..523be01671 100644 --- a/ports/atmel-samd/common-hal/_pew/PewPew.h +++ b/ports/atmel-samd/common-hal/_pew/PewPew.h @@ -32,9 +32,9 @@ typedef struct { mp_obj_base_t base; - uint8_t* buffer; - mp_obj_t* rows; - mp_obj_t* cols; + uint8_t *buffer; + mp_obj_t *rows; + mp_obj_t *cols; digitalio_digitalinout_obj_t *buttons; uint8_t rows_size; uint8_t cols_size; diff --git a/ports/atmel-samd/common-hal/_pew/__init__.c b/ports/atmel-samd/common-hal/_pew/__init__.c index f3b23c606c..b89b464dd3 100644 --- a/ports/atmel-samd/common-hal/_pew/__init__.c +++ b/ports/atmel-samd/common-hal/_pew/__init__.c @@ -40,8 +40,10 @@ void pew_tick(void) { static uint8_t last_pressed = 0; digitalio_digitalinout_obj_t *pin; - pew_obj_t* pew = MP_STATE_VM(pew_singleton); - if (!pew) { return; } + pew_obj_t *pew = MP_STATE_VM(pew_singleton); + if (!pew) { + return; + } pin = MP_OBJ_TO_PTR(pew->cols[col]); ++col; @@ -69,7 +71,7 @@ void pew_tick(void) { break; case 2: if (turn == 2 || turn == 5 || turn == 8 || turn == 11) { - value = true; + value = true; } break; case 1: diff --git a/ports/atmel-samd/common-hal/analogio/AnalogIn.c b/ports/atmel-samd/common-hal/analogio/AnalogIn.c index 2bd218cdda..262e44350c 100644 --- a/ports/atmel-samd/common-hal/analogio/AnalogIn.c +++ b/ports/atmel-samd/common-hal/analogio/AnalogIn.c @@ -46,8 +46,8 @@ #include "hpl/pm/hpl_pm_base.h" #endif -void common_hal_analogio_analogin_construct(analogio_analogin_obj_t* self, - const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, + const mcu_pin_obj_t *pin) { uint8_t adc_index; uint8_t adc_channel = 0xff; for (adc_index = 0; adc_index < NUM_ADC_PER_PIN; adc_index++) { @@ -66,7 +66,7 @@ void common_hal_analogio_analogin_construct(analogio_analogin_obj_t* self, gpio_set_pin_function(pin->number, GPIO_PIN_FUNCTION_B); - static Adc* adc_insts[] = ADC_INSTS; + static Adc *adc_insts[] = ADC_INSTS; self->instance = adc_insts[adc_index]; self->channel = adc_channel; self->pin = pin; @@ -118,8 +118,8 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { // Empirical observation shows the first reading is quite different than subsequent ones. uint16_t value; - adc_sync_read_channel(&adc, self->channel, ((uint8_t*) &value), 2); - adc_sync_read_channel(&adc, self->channel, ((uint8_t*) &value), 2); + adc_sync_read_channel(&adc, self->channel, ((uint8_t *)&value), 2); + adc_sync_read_channel(&adc, self->channel, ((uint8_t *)&value), 2); adc_sync_deinit(&adc); // Shift the value to be 16 bit. diff --git a/ports/atmel-samd/common-hal/analogio/AnalogIn.h b/ports/atmel-samd/common-hal/analogio/AnalogIn.h index 0b13ba7e14..3a467f64db 100644 --- a/ports/atmel-samd/common-hal/analogio/AnalogIn.h +++ b/ports/atmel-samd/common-hal/analogio/AnalogIn.h @@ -33,8 +33,8 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t * pin; - Adc* instance; + const mcu_pin_obj_t *pin; + Adc *instance; uint8_t channel; } analogio_analogin_obj_t; diff --git a/ports/atmel-samd/common-hal/analogio/AnalogOut.c b/ports/atmel-samd/common-hal/analogio/AnalogOut.c index 3ddd9cac66..f3b3310ebe 100644 --- a/ports/atmel-samd/common-hal/analogio/AnalogOut.c +++ b/ports/atmel-samd/common-hal/analogio/AnalogOut.c @@ -47,10 +47,10 @@ #define HAVE_ANALOGOUT ( \ (defined(PIN_PA02) && !defined(IGNORE_PA02)) || \ (defined(SAM_D5X_E5X) && defined(PIN_PA05) && !defined(IGNORE_PA05)) \ -) + ) -void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, - const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, + const mcu_pin_obj_t *pin) { #if !HAVE_ANALOGOUT mp_raise_NotImplementedError(translate("No DAC on chip")); #else @@ -63,15 +63,15 @@ void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, break; #endif - #if defined(SAM_D5X_E5X) && defined(PIN_PA05) && !defined(IGNORE_PIN_PA05) + #if defined(SAM_D5X_E5X) && defined(PIN_PA05) && !defined(IGNORE_PIN_PA05) case PIN_PA05: channel = 1; break; - #endif + #endif default: mp_raise_ValueError(translate("AnalogOut not supported on given pin")); - return; + return; } self->channel = channel; @@ -94,14 +94,14 @@ void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, #ifdef SAM_D5X_E5X if (!common_hal_mcu_pin_is_free(&pin_PA02) || !common_hal_mcu_pin_is_free(&pin_PA05)) { #endif - // Fake the descriptor if the DAC is already initialized. - self->descriptor.device.hw = DAC; + // Fake the descriptor if the DAC is already initialized. + self->descriptor.device.hw = DAC; #ifdef SAM_D5X_E5X - } else { +} else { #endif - result = dac_sync_init(&self->descriptor, DAC); + result = dac_sync_init(&self->descriptor, DAC); #ifdef SAM_D5X_E5X - } +} #endif if (result != ERR_NONE) { mp_raise_OSError(MP_EIO); @@ -134,9 +134,9 @@ void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { #ifdef SAM_D5X_E5X if (common_hal_mcu_pin_is_free(&pin_PA02) && common_hal_mcu_pin_is_free(&pin_PA05)) { #endif - dac_sync_deinit(&self->descriptor); + dac_sync_deinit(&self->descriptor); #ifdef SAM_D5X_E5X - } +} #endif self->deinited = true; // TODO(tannewt): Turn off the DAC clocks to save power. @@ -144,7 +144,7 @@ void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { } void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, - uint16_t value) { + uint16_t value) { #if HAVE_ANALOGOUT // Input is 16 bit so make sure and set LEFTADJ to 1 so it takes the top // bits. This is currently done in asf4_conf/*/hpl_dac_config.h. @@ -155,15 +155,17 @@ void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, void analogout_reset(void) { // audioout_reset also resets the DAC, and does a smooth ramp down to avoid clicks // if it was enabled, so do that instead if AudioOut is enabled. -#if CIRCUITPY_AUDIOIO + #if CIRCUITPY_AUDIOIO audioout_reset(); -#elif HAVE_ANALOGOUT + #elif HAVE_ANALOGOUT #ifdef SAMD21 - while (DAC->STATUS.reg & DAC_STATUS_SYNCBUSY) {} + while (DAC->STATUS.reg & DAC_STATUS_SYNCBUSY) { + } #endif #ifdef SAM_D5X_E5X - while (DAC->SYNCBUSY.reg & DAC_SYNCBUSY_SWRST) {} + while (DAC->SYNCBUSY.reg & DAC_SYNCBUSY_SWRST) { + } #endif DAC->CTRLA.reg |= DAC_CTRLA_SWRST; -#endif + #endif } diff --git a/ports/atmel-samd/common-hal/audiobusio/I2SOut.c b/ports/atmel-samd/common-hal/audiobusio/I2SOut.c index 0aa48c8047..2488b7b922 100644 --- a/ports/atmel-samd/common-hal/audiobusio/I2SOut.c +++ b/ports/atmel-samd/common-hal/audiobusio/I2SOut.c @@ -61,11 +61,11 @@ #include "audio_dma.h" #ifdef SAMD21 -#define SERCTRL(name) I2S_SERCTRL_ ## name +#define SERCTRL(name) I2S_SERCTRL_##name #endif #ifdef SAM_D5X_E5X -#define SERCTRL(name) I2S_TXCTRL_ ## name +#define SERCTRL(name) I2S_TXCTRL_##name #endif void i2sout_reset(void) { @@ -77,7 +77,8 @@ void i2sout_reset(void) { #endif if (I2S->CTRLA.bit.ENABLE == 1) { I2S->CTRLA.bit.ENABLE = 0; - while (I2S->SYNCBUSY.bit.ENABLE == 1) {} + while (I2S->SYNCBUSY.bit.ENABLE == 1) { + } } // Make sure the I2S peripheral is running so we can see if the resources we need are free. @@ -95,9 +96,9 @@ void i2sout_reset(void) { } // Caller validates that pins are free. -void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, - const mcu_pin_obj_t* bit_clock, const mcu_pin_obj_t* word_select, - const mcu_pin_obj_t* data, bool left_justified) { +void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, + const mcu_pin_obj_t *bit_clock, const mcu_pin_obj_t *word_select, + const mcu_pin_obj_t *data, bool left_justified) { uint8_t serializer = 0xff; uint8_t bc_clock_unit = 0xff; uint8_t ws_clock_unit = 0xff; @@ -130,10 +131,10 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, if (data == &pin_PA07 || data == &pin_PA19) { // I2S SD[0] serializer = 0; } else if (data == &pin_PA08 - #ifdef PIN_PB16 - || data == &pin_PB16 - #endif - ) { // I2S SD[1] + #ifdef PIN_PB16 + || data == &pin_PB16 + #endif + ) { // I2S SD[1] serializer = 1; } #endif @@ -168,7 +169,8 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, if (I2S->CTRLA.bit.ENABLE == 0) { I2S->CTRLA.bit.SWRST = 1; - while (I2S->CTRLA.bit.SWRST == 1) {} + while (I2S->CTRLA.bit.SWRST == 1) { + } } else { #ifdef SAMD21 if ((I2S->CTRLA.vec.SEREN & (1 << serializer)) != 0) { @@ -206,11 +208,11 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, audio_dma_init(&self->dma); } -bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t *self) { return self->bit_clock == NULL; } -void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self) { if (common_hal_audiobusio_i2sout_deinited(self)) { return; } @@ -223,8 +225,8 @@ void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { self->data = NULL; } -void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, - mp_obj_t sample, bool loop) { +void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, + mp_obj_t sample, bool loop) { if (common_hal_audiobusio_i2sout_get_playing(self)) { common_hal_audiobusio_i2sout_stop(self); } @@ -245,8 +247,8 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, self->gclk = gclk; uint32_t clkctrl = I2S_CLKCTRL_MCKSEL_GCLK | - I2S_CLKCTRL_NBSLOTS(1) | - I2S_CLKCTRL_FSWIDTH_HALF; + I2S_CLKCTRL_NBSLOTS(1) | + I2S_CLKCTRL_FSWIDTH_HALF; if (self->left_justified) { clkctrl |= I2S_CLKCTRL_BITDELAY_LJ; } else { @@ -293,11 +295,11 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, i2s_set_enable(true); #ifdef SAMD21 - uint32_t tx_register = (uint32_t) &I2S->DATA[self->serializer].reg; + uint32_t tx_register = (uint32_t)&I2S->DATA[self->serializer].reg; uint8_t dmac_id = I2S_DMAC_ID_TX_0 + self->serializer; #endif #ifdef SAM_D5X_E5X - uint32_t tx_register = (uint32_t) &I2S->TXDATA.reg; + uint32_t tx_register = (uint32_t)&I2S->TXDATA.reg; uint8_t dmac_id = I2S_DMAC_ID_TX_0; #endif audio_dma_result result = audio_dma_setup_playback(&self->dma, sample, loop, false, 0, @@ -314,26 +316,29 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, I2S->INTFLAG.reg = I2S_INTFLAG_TXUR0 | I2S_INTFLAG_TXUR1; I2S->CTRLA.vec.CKEN = 1 << self->clock_unit; - while ((I2S->SYNCBUSY.vec.CKEN & (1 << self->clock_unit)) != 0) {} + while ((I2S->SYNCBUSY.vec.CKEN & (1 << self->clock_unit)) != 0) { + } // Init the serializer after the clock. Otherwise, it will never enable because its unclocked. #ifdef SAMD21 I2S->CTRLA.vec.SEREN = 1 << self->serializer; - while ((I2S->SYNCBUSY.vec.SEREN & (1 << self->serializer)) != 0) {} + while ((I2S->SYNCBUSY.vec.SEREN & (1 << self->serializer)) != 0) { + } #endif #ifdef SAM_D5X_E5X I2S->CTRLA.bit.TXEN = 1; - while (I2S->SYNCBUSY.bit.TXEN == 1) {} + while (I2S->SYNCBUSY.bit.TXEN == 1) { + } #endif self->playing = true; } -void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t *self) { audio_dma_pause(&self->dma); } -void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t *self) { // Clear any overrun/underrun errors #ifdef SAMD21 I2S->INTFLAG.reg = I2S_INTFLAG_TXUR0 << self->serializer; @@ -345,29 +350,33 @@ void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t* self) { audio_dma_resume(&self->dma); } -bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t *self) { return audio_dma_get_paused(&self->dma); } -void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t *self) { audio_dma_stop(&self->dma); #ifdef SAMD21 I2S->CTRLA.vec.SEREN &= ~(1 << self->serializer); - while ((I2S->SYNCBUSY.vec.SEREN & (1 << self->serializer)) != 0) {} + while ((I2S->SYNCBUSY.vec.SEREN & (1 << self->serializer)) != 0) { + } #endif #ifdef SAM_D5X_E5X I2S->CTRLA.bit.TXEN = 0; - while (I2S->SYNCBUSY.bit.TXEN == 1) {} + while (I2S->SYNCBUSY.bit.TXEN == 1) { + } #endif #ifdef SAMD21 if (self->clock_unit == 0) { I2S->CTRLA.bit.CKEN0 = 0; - while (I2S->SYNCBUSY.bit.CKEN0 == 1) {} + while (I2S->SYNCBUSY.bit.CKEN0 == 1) { + } } else { I2S->CTRLA.bit.CKEN1 = 0; - while (I2S->SYNCBUSY.bit.CKEN1 == 1) {} + while (I2S->SYNCBUSY.bit.CKEN1 == 1) { + } } #endif disconnect_gclk_from_peripheral(self->gclk, I2S_GCLK_ID_0 + self->clock_unit); @@ -380,7 +389,7 @@ void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t* self) { self->playing = false; } -bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t *self) { bool still_playing = audio_dma_get_playing(&self->dma); if (self->playing && !still_playing) { common_hal_audiobusio_i2sout_stop(self); diff --git a/ports/atmel-samd/common-hal/audiobusio/PDMIn.c.uncrustify b/ports/atmel-samd/common-hal/audiobusio/PDMIn.c.uncrustify new file mode 100644 index 0000000000..e69de29bb2 diff --git a/ports/atmel-samd/modules/frozentest.py b/ports/atmel-samd/modules/frozentest.py index 0f99b74297..78cdd60bf0 100644 --- a/ports/atmel-samd/modules/frozentest.py +++ b/ports/atmel-samd/modules/frozentest.py @@ -1,7 +1,7 @@ -print('uPy') -print('a long string that is not interned') -print('a string that has unicode αβγ chars') -print(b'bytes 1234\x01') +print("uPy") +print("a long string that is not interned") +print("a string that has unicode αβγ chars") +print(b"bytes 1234\x01") print(123456789) for i in range(4): print(i) diff --git a/ports/atmel-samd/tools/gen_pin_name_table.py b/ports/atmel-samd/tools/gen_pin_name_table.py index 4e25c39fd9..a78144d400 100644 --- a/ports/atmel-samd/tools/gen_pin_name_table.py +++ b/ports/atmel-samd/tools/gen_pin_name_table.py @@ -27,11 +27,47 @@ import os import os.path -pins = ["PA00", "PA01", "PA02", "PA03", "PB08", "PB09", "PA04", "PA05", "PA06", - "PA07", "PA08", "PA09", "PA10", "PA11", "PB10", "PB11", "PA12", "PA13", - "PA14", "PA15", "PA16", "PA17", "PA18", "PA19", "PA20", "PA21", "PA22", - "PA23", "PA24", "PA25", "PB22", "PB23", "PA27", "PA28", "PA29", "PA30", - "PA31", "PB02", "PB03"] +pins = [ + "PA00", + "PA01", + "PA02", + "PA03", + "PB08", + "PB09", + "PA04", + "PA05", + "PA06", + "PA07", + "PA08", + "PA09", + "PA10", + "PA11", + "PB10", + "PB11", + "PA12", + "PA13", + "PA14", + "PA15", + "PA16", + "PA17", + "PA18", + "PA19", + "PA20", + "PA21", + "PA22", + "PA23", + "PA24", + "PA25", + "PB22", + "PB23", + "PA27", + "PA28", + "PA29", + "PA30", + "PA31", + "PB02", + "PB03", +] # Dictionary keys: [board][pin] = list of pin names mapping = {} @@ -46,7 +82,7 @@ for board in os.listdir("boards"): for line in f: if line.startswith(QSTR): board_name, _, pin = line.split(")") - board_name = board_name[len(QSTR):] + board_name = board_name[len(QSTR) :] pin = pin[-8:-4] if pin not in mapping[board]: mapping[board][pin] = [] @@ -108,61 +144,196 @@ ALL_BUT_USB.remove("PA25") # dictionary is [module][class] = [pins] capabilities = { - "analogio" : { - "AnalogIn" : ["PA02", "PA03", "PB08", "PB09", "PA04", "PA05", "PA06", - "PA07", "PA08", "PA09", "PA10", "PA11", "PB02", "PB03"], - "AnalogOut": ["PA02"] - }, - "audioio" : { - "AudioOut": ["PA02"] - }, - "bitbangio": { - "I2C": ALL_BUT_USB, - "OneWire": ALL_BUT_USB, - "SPI": ALL_BUT_USB + "analogio": { + "AnalogIn": [ + "PA02", + "PA03", + "PB08", + "PB09", + "PA04", + "PA05", + "PA06", + "PA07", + "PA08", + "PA09", + "PA10", + "PA11", + "PB02", + "PB03", + ], + "AnalogOut": ["PA02"], }, + "audioio": {"AudioOut": ["PA02"]}, + "bitbangio": {"I2C": ALL_BUT_USB, "OneWire": ALL_BUT_USB, "SPI": ALL_BUT_USB}, "busio": { - "I2C - SDA": ["PA00", "PB08", "PA08", "PA12", "PA16", "PA22", "PB02"], # SERCOM pad 0 - "I2C - SCL": ["PA01", "PB09", "PA09", "PA13", "PA17", "PA23", "PB03"], # SERCOM pad 1 + "I2C - SDA": ["PA00", "PB08", "PA08", "PA12", "PA16", "PA22", "PB02"], # SERCOM pad 0 + "I2C - SCL": ["PA01", "PB09", "PA09", "PA13", "PA17", "PA23", "PB03"], # SERCOM pad 1 "OneWire": ALL_BUT_USB, - "SPI - MISO": ["PA00", "PA01", "PB08", "PB09", "PA04", "PA05", "PA06", - "PA07", "PA08", "PA09", "PA10", "PA11", "PB10", "PB11", - "PA12", "PA13", "PA14", "PA15", "PA16", "PA17", "PA18", - "PA19", "PA20", "PA21", "PA22", "PA23", "PB22", "PB23", - "PA30", "PA31", "PB02", "PB03"], # any SERCOM pad - "SPI - MOSI": ["PA00", "PB08", "PA04", "PA06", "PA08", "PA10", "PA11", - "PB10", "PB11", "PA14", "PA15", "PA16", "PA18", "PA19", - "PA20", "PA21", "PA22", "PB22", "PB23", "PA30", "PA31", - "PB02"], # any pad but 1 - "SPI - SCK": ["PA01", "PB09", "PA05", "PA07", "PA09", "PA11", "PB11", - "PA13", "PA15", "PA17", "PA19", "PA21", "PA23", "PB23", - "PA31", "PB03"], # 1 or 3 - "UART - RX": ["PA00", "PA01", "PB08", "PB09", "PA04", "PA05", "PA06", - "PA07", "PA08", "PA09", "PA10", "PA11", "PB10", "PB11", - "PA12", "PA13", "PA14", "PA15", "PA16", "PA17", "PA18", - "PA19", "PA20", "PA21", "PA22", "PA23", "PB22", "PB23", - "PA30", "PA31", "PB02", "PB03"], # any pad - "UART - TX": ["PA00", "PB08", "PA04", "PA06", "PA08", "PA10", "PB10", - "PA12", "PA14", "PA16", "PA18", "PA20", "PA22", "PB22", - "PA30", "PB02"] # pad 0 or 2 - }, - "digitalio": { - "DigitalInOut": ALL_BUT_USB + "SPI - MISO": [ + "PA00", + "PA01", + "PB08", + "PB09", + "PA04", + "PA05", + "PA06", + "PA07", + "PA08", + "PA09", + "PA10", + "PA11", + "PB10", + "PB11", + "PA12", + "PA13", + "PA14", + "PA15", + "PA16", + "PA17", + "PA18", + "PA19", + "PA20", + "PA21", + "PA22", + "PA23", + "PB22", + "PB23", + "PA30", + "PA31", + "PB02", + "PB03", + ], # any SERCOM pad + "SPI - MOSI": [ + "PA00", + "PB08", + "PA04", + "PA06", + "PA08", + "PA10", + "PA11", + "PB10", + "PB11", + "PA14", + "PA15", + "PA16", + "PA18", + "PA19", + "PA20", + "PA21", + "PA22", + "PB22", + "PB23", + "PA30", + "PA31", + "PB02", + ], # any pad but 1 + "SPI - SCK": [ + "PA01", + "PB09", + "PA05", + "PA07", + "PA09", + "PA11", + "PB11", + "PA13", + "PA15", + "PA17", + "PA19", + "PA21", + "PA23", + "PB23", + "PA31", + "PB03", + ], # 1 or 3 + "UART - RX": [ + "PA00", + "PA01", + "PB08", + "PB09", + "PA04", + "PA05", + "PA06", + "PA07", + "PA08", + "PA09", + "PA10", + "PA11", + "PB10", + "PB11", + "PA12", + "PA13", + "PA14", + "PA15", + "PA16", + "PA17", + "PA18", + "PA19", + "PA20", + "PA21", + "PA22", + "PA23", + "PB22", + "PB23", + "PA30", + "PA31", + "PB02", + "PB03", + ], # any pad + "UART - TX": [ + "PA00", + "PB08", + "PA04", + "PA06", + "PA08", + "PA10", + "PB10", + "PA12", + "PA14", + "PA16", + "PA18", + "PA20", + "PA22", + "PB22", + "PA30", + "PB02", + ], # pad 0 or 2 }, + "digitalio": {"DigitalInOut": ALL_BUT_USB}, "pulseio": { "PulseIn": ALL_BUT_USB, - "PWMOut": ["PA01", "PB09", "PA04", "PA05", "PA06", "PA07", "PA08", - "PA09", "PA10", "PA11", "PB10", "PB11", "PA12", "PA13", - "PA14", "PA15", "PA16", "PA17", "PA18", "PA19", "PA20", - "PA21", "PA22", "PA23", "PA30", "PA31"] - }, - "ps2io": { - "Ps2": ALL_BUT_USB, + "PWMOut": [ + "PA01", + "PB09", + "PA04", + "PA05", + "PA06", + "PA07", + "PA08", + "PA09", + "PA10", + "PA11", + "PB10", + "PB11", + "PA12", + "PA13", + "PA14", + "PA15", + "PA16", + "PA17", + "PA18", + "PA19", + "PA20", + "PA21", + "PA22", + "PA23", + "PA30", + "PA31", + ], }, + "ps2io": {"Ps2": ALL_BUT_USB}, "touchio": { - "TouchIn": ["PA02", "PA03", "PB08", "PB09", "PA04", "PA05", "PA06", - "PA07", "PB02", "PB03"] - } + "TouchIn": ["PA02", "PA03", "PB08", "PB09", "PA04", "PA05", "PA06", "PA07", "PB02", "PB03"] + }, } column_width = {} @@ -178,7 +349,7 @@ for module in capabilities: module_width[module] -= 2 if module_width[module] < (len(module) + 2): - column_width[module + c] += (len(module) + 2 - module_width[module]) + column_width[module + c] += len(module) + 2 - module_width[module] module_width[module] = len(module) + 2 first_column_width = len("`microcontroller.pin`") diff --git a/ports/atmel-samd/tools/mkcandata.py b/ports/atmel-samd/tools/mkcandata.py index 9668d2208a..d505c81bdc 100755 --- a/ports/atmel-samd/tools/mkcandata.py +++ b/ports/atmel-samd/tools/mkcandata.py @@ -1,22 +1,27 @@ #!/usr/bin/python3 + def defines(name, suffix): - print(f'mcu_pin_function_t {name} [] = {{') + print(f"mcu_pin_function_t {name} [] = {{") for instance in (0, 1): - for function in 'HI': - for port in 'ABCD': + for function in "HI": + for port in "ABCD": for idx in range(32): - pin = f'P{port}{idx:02d}' - pinmux = f'PINMUX_{pin}{function}_CAN{instance}_{suffix}' - print(f'''\ + pin = f"P{port}{idx:02d}" + pinmux = f"PINMUX_{pin}{function}_CAN{instance}_{suffix}" + print( + f"""\ #if defined({pinmux}) && ! defined(IGNORE_PIN_{pin}) {{&pin_{pin}, {instance}, PIN_{pin}, {pinmux} & 0xffff}}, -#endif''') - print(f'{{NULL, 0, 0}}') - print(f'}};') +#endif""" + ) + print(f"{{NULL, 0, 0}}") + print(f"}};") print() -print('''\ + +print( + """\ #include #include "py/obj.h" #include "sam.h" @@ -25,7 +30,8 @@ print('''\ #include "atmel_start_pins.h" #include "hal/include/hal_gpio.h" #include "common-hal/microcontroller/Pin.h" -''') +""" +) -defines('can_rx', 'RX') -defines('can_tx', 'TX') +defines("can_rx", "RX") +defines("can_tx", "TX") diff --git a/ports/atmel-samd/tools/mksdiodata.py b/ports/atmel-samd/tools/mksdiodata.py index 48c4a085f5..bfdcd696c2 100755 --- a/ports/atmel-samd/tools/mksdiodata.py +++ b/ports/atmel-samd/tools/mksdiodata.py @@ -1,21 +1,26 @@ #!/usr/bin/python3 + def defines(name, function): - print(f'mcu_pin_function_t {name} [] = {{') + print(f"mcu_pin_function_t {name} [] = {{") for instance in (0, 1): - for port in 'ABCD': + for port in "ABCD": for idx in range(32): - pin = f'P{port}{idx:02d}' - pinmux = f'PINMUX_{pin}I_SDHC{instance}_{function}' - print(f'''\ + pin = f"P{port}{idx:02d}" + pinmux = f"PINMUX_{pin}I_SDHC{instance}_{function}" + print( + f"""\ #if defined({pinmux}) && ! defined(IGNORE_PIN_{pin}) {{&pin_{pin}, {instance}, PIN_{pin}, {pinmux} & 0xffff}}, -#endif''') - print(f'{{NULL, 0, 0}}') - print(f'}};') +#endif""" + ) + print(f"{{NULL, 0, 0}}") + print(f"}};") print() -print('''\ + +print( + """\ #include #include "py/obj.h" #include "sam.h" @@ -25,11 +30,12 @@ print('''\ #include "hal/include/hal_gpio.h" #include "common-hal/microcontroller/Pin.h" -''') +""" +) -defines('sdio_ck', 'SDCK') -defines('sdio_cmd', 'SDCMD') -defines('sdio_dat0', 'SDDAT0') -defines('sdio_dat1', 'SDDAT1') -defines('sdio_dat2', 'SDDAT2') -defines('sdio_dat3', 'SDDAT3') +defines("sdio_ck", "SDCK") +defines("sdio_cmd", "SDCMD") +defines("sdio_dat0", "SDDAT0") +defines("sdio_dat1", "SDDAT1") +defines("sdio_dat2", "SDDAT2") +defines("sdio_dat3", "SDDAT3") diff --git a/ports/atmel-samd/tools/update_asf.py b/ports/atmel-samd/tools/update_asf.py index 7b7bac10fe..a747d6b061 100644 --- a/ports/atmel-samd/tools/update_asf.py +++ b/ports/atmel-samd/tools/update_asf.py @@ -11,7 +11,11 @@ for chip in ["samd21", "samd51"]: if not os.path.isfile(filename): with open("tools/" + chip + ".json", "r") as project_json: headers = {"content-type": "text/plain"} - r = requests.post("http://start.atmel.com/api/v1/generate/?format=atzip&compilers=[make]&file_name_base=My%20Project", headers=headers, data=project_json) + r = requests.post( + "http://start.atmel.com/api/v1/generate/?format=atzip&compilers=[make]&file_name_base=My%20Project", + headers=headers, + data=project_json, + ) if not r.ok: # Double check that the JSON is minified. If its not, you'll get a 404. print(r.text) @@ -40,7 +44,9 @@ for chip in ["samd21", "samd51"]: for patch in os.listdir("asf4/patches/" + chip): patch = "patches/" + chip + "/" + patch print(patch) - result = subprocess.run(["patch", "-l", "-F", "10", "-u", "-p", "1", "-d", tmp_dir, "-i", "../" + patch]) + result = subprocess.run( + ["patch", "-l", "-F", "10", "-u", "-p", "1", "-d", tmp_dir, "-i", "../" + patch] + ) ok = ok and result.returncode == 0 print() diff --git a/ports/cxd56/boards/spresense/board.c b/ports/cxd56/boards/spresense/board.c index fd27d3493a..7d6297b648 100644 --- a/ports/cxd56/boards/spresense/board.c +++ b/ports/cxd56/boards/spresense/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/cxd56/common-hal/analogio/AnalogIn.c b/ports/cxd56/common-hal/analogio/AnalogIn.c index 5c47991eb2..d1bd68cfbe 100644 --- a/ports/cxd56/common-hal/analogio/AnalogIn.c +++ b/ports/cxd56/common-hal/analogio/AnalogIn.c @@ -36,7 +36,7 @@ #include "shared-bindings/analogio/AnalogIn.h" typedef struct { - const char* devpath; + const char *devpath; const mcu_pin_obj_t *pin; int fd; } analogin_dev_t; @@ -109,7 +109,7 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { read(analogin_dev[self->number].fd, &value, sizeof(value)); - return (uint16_t) 32768 + (uint16_t) value; + return (uint16_t)32768 + (uint16_t)value; } // Reference voltage is a fixed value which is depending on the board. diff --git a/ports/cxd56/common-hal/busio/I2C.c b/ports/cxd56/common-hal/busio/I2C.c index 5579bedeb1..0e6dbedc00 100644 --- a/ports/cxd56/common-hal/busio/I2C.c +++ b/ports/cxd56/common-hal/busio/I2C.c @@ -101,7 +101,7 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t address, cons msg.frequency = self->frequency; msg.addr = address; msg.flags = (stop ? 0 : I2C_M_NOSTOP); - msg.buffer = (uint8_t *) data; + msg.buffer = (uint8_t *)data; msg.length = len; return -I2C_TRANSFER(self->i2c_dev, &msg, 1); } diff --git a/ports/cxd56/common-hal/busio/I2C.h b/ports/cxd56/common-hal/busio/I2C.h index cdef270bfa..4d1d3ce9b8 100644 --- a/ports/cxd56/common-hal/busio/I2C.h +++ b/ports/cxd56/common-hal/busio/I2C.h @@ -33,7 +33,7 @@ typedef struct { mp_obj_base_t base; - struct i2c_master_s* i2c_dev; + struct i2c_master_s *i2c_dev; uint32_t frequency; bool has_lock; const mcu_pin_obj_t *scl_pin; diff --git a/ports/cxd56/common-hal/busio/SPI.c b/ports/cxd56/common-hal/busio/SPI.c index 56ab0758d4..e77c0224dd 100644 --- a/ports/cxd56/common-hal/busio/SPI.c +++ b/ports/cxd56/common-hal/busio/SPI.c @@ -144,7 +144,7 @@ uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { return self->frequency; } -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { return self->phase; } diff --git a/ports/cxd56/common-hal/busio/SPI.h b/ports/cxd56/common-hal/busio/SPI.h index 8985a60d9f..ee04de08c4 100644 --- a/ports/cxd56/common-hal/busio/SPI.h +++ b/ports/cxd56/common-hal/busio/SPI.h @@ -35,7 +35,7 @@ typedef struct { mp_obj_base_t base; - struct spi_dev_s* spi_dev; + struct spi_dev_s *spi_dev; uint32_t frequency; uint8_t phase; uint8_t polarity; diff --git a/ports/cxd56/common-hal/busio/UART.c b/ports/cxd56/common-hal/busio/UART.c index 52d2afc0c2..f7588c7101 100644 --- a/ports/cxd56/common-hal/busio/UART.c +++ b/ports/cxd56/common-hal/busio/UART.c @@ -42,7 +42,7 @@ #include "shared-bindings/busio/UART.h" typedef struct { - const char* devpath; + const char *devpath; const mcu_pin_obj_t *tx; const mcu_pin_obj_t *rx; int fd; @@ -53,11 +53,11 @@ STATIC busio_uart_dev_t busio_uart_dev[] = { }; void common_hal_busio_uart_construct(busio_uart_obj_t *self, - const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, - const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, - const mcu_pin_obj_t * rs485_dir, bool rs485_invert, + const mcu_pin_obj_t *tx, const mcu_pin_obj_t *rx, + const mcu_pin_obj_t *rts, const mcu_pin_obj_t *cts, + const mcu_pin_obj_t *rs485_dir, bool rs485_invert, uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, - mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, + mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { struct termios tio; @@ -180,7 +180,7 @@ void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrat } mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { - return (mp_float_t) (self->timeout_us / 1000000.0f); + return (mp_float_t)(self->timeout_us / 1000000.0f); } void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { diff --git a/ports/cxd56/common-hal/camera/Camera.c b/ports/cxd56/common-hal/camera/Camera.c index 35e2ab8822..5e159d61dc 100644 --- a/ports/cxd56/common-hal/camera/Camera.c +++ b/ports/cxd56/common-hal/camera/Camera.c @@ -36,7 +36,7 @@ #include "shared-bindings/camera/Camera.h" typedef struct { - const char* devpath; + const char *devpath; int fd; } camera_dev_t; diff --git a/ports/cxd56/common-hal/gnss/GNSS.c b/ports/cxd56/common-hal/gnss/GNSS.c index c0aaa3cfbd..f345f5261d 100644 --- a/ports/cxd56/common-hal/gnss/GNSS.c +++ b/ports/cxd56/common-hal/gnss/GNSS.c @@ -34,7 +34,7 @@ #include "shared-bindings/gnss/GNSS.h" typedef struct { - const char* devpath; + const char *devpath; int fd; } gnss_dev_t; @@ -110,15 +110,15 @@ void common_hal_gnss_update(gnss_obj_t *self) { } mp_float_t common_hal_gnss_get_latitude(gnss_obj_t *self) { - return (mp_float_t) self->latitude; + return (mp_float_t)self->latitude; } mp_float_t common_hal_gnss_get_longitude(gnss_obj_t *self) { - return (mp_float_t) self->longitude; + return (mp_float_t)self->longitude; } mp_float_t common_hal_gnss_get_altitude(gnss_obj_t *self) { - return (mp_float_t) self->altitude; + return (mp_float_t)self->altitude; } void common_hal_gnss_get_timestamp(gnss_obj_t *self, timeutils_struct_time_t *tm) { diff --git a/ports/cxd56/common-hal/microcontroller/Pin.h b/ports/cxd56/common-hal/microcontroller/Pin.h index 6759a2dcab..259fc57162 100644 --- a/ports/cxd56/common-hal/microcontroller/Pin.h +++ b/ports/cxd56/common-hal/microcontroller/Pin.h @@ -32,11 +32,11 @@ extern const mp_obj_type_t mcu_pin_type; #define PIN(pin, a) \ -{ \ - { &mcu_pin_type }, \ - .number = (pin), \ - .analog = (a) \ -} + { \ + { &mcu_pin_type }, \ + .number = (pin), \ + .analog = (a) \ + } typedef struct { mp_obj_base_t base; @@ -93,6 +93,6 @@ extern const mcu_pin_obj_t pin_HPADC1; void never_reset_pin_number(uint8_t pin_number); void reset_pin_number(uint8_t pin_number); void reset_all_pins(void); -void claim_pin(const mcu_pin_obj_t* pin); +void claim_pin(const mcu_pin_obj_t *pin); #endif // MICROPY_INCLUDED_CXD56_COMMON_HAL_MICROCONTROLLER_PIN_H diff --git a/ports/cxd56/common-hal/microcontroller/Processor.c b/ports/cxd56/common-hal/microcontroller/Processor.c index 3cb187de61..b5efe37ce6 100644 --- a/ports/cxd56/common-hal/microcontroller/Processor.c +++ b/ports/cxd56/common-hal/microcontroller/Processor.c @@ -46,7 +46,7 @@ float common_hal_mcu_processor_get_voltage(void) { } void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { - boardctl(BOARDIOC_UNIQUEID, (uintptr_t) raw_id); + boardctl(BOARDIOC_UNIQUEID, (uintptr_t)raw_id); } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { diff --git a/ports/cxd56/common-hal/microcontroller/__init__.c b/ports/cxd56/common-hal/microcontroller/__init__.c index 7aa3b839d7..499e0e5f04 100644 --- a/ports/cxd56/common-hal/microcontroller/__init__.c +++ b/ports/cxd56/common-hal/microcontroller/__init__.c @@ -49,14 +49,16 @@ const mcu_processor_obj_t common_hal_mcu_processor_obj = { void common_hal_mcu_delay_us(uint32_t delay) { if (delay) { unsigned long long ticks = cxd56_get_cpu_baseclk() / 1000000L * delay; - if (ticks < DELAY_CORRECTION) return; // delay time already used in calculation + if (ticks < DELAY_CORRECTION) { + return; // delay time already used in calculation + } ticks -= DELAY_CORRECTION; ticks /= 6; // following loop takes 6 cycles do { - __asm__ __volatile__("nop"); - } while(--ticks); + __asm__ __volatile__ ("nop"); + } while (--ticks); } } @@ -69,9 +71,9 @@ void common_hal_mcu_enable_interrupts(void) { } void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { - if(runmode == RUNMODE_BOOTLOADER) { + if (runmode == RUNMODE_BOOTLOADER) { mp_raise_ValueError(translate("Cannot reset into bootloader because no bootloader is present.")); - } else if(runmode == RUNMODE_SAFE_MODE) { + } else if (runmode == RUNMODE_SAFE_MODE) { safe_mode_on_next_reset(PROGRAMMATIC_SAFE_MODE); } } diff --git a/ports/cxd56/common-hal/os/__init__.c b/ports/cxd56/common-hal/os/__init__.c index d4b0e23bec..e44d293f00 100644 --- a/ports/cxd56/common-hal/os/__init__.c +++ b/ports/cxd56/common-hal/os/__init__.c @@ -50,13 +50,13 @@ STATIC MP_DEFINE_ATTRTUPLE( (mp_obj_t)&os_uname_info_release_obj, (mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj -); + ); mp_obj_t common_hal_os_uname(void) { return (mp_obj_t)&os_uname_info_obj; } -bool common_hal_os_urandom(uint8_t* buffer, mp_uint_t length) { +bool common_hal_os_urandom(uint8_t *buffer, mp_uint_t length) { uint32_t i = 0; while (i < length) { diff --git a/ports/cxd56/common-hal/pulseio/PulseIn.c b/ports/cxd56/common-hal/pulseio/PulseIn.c index 7c3e4a9d05..0d2fbbfd96 100644 --- a/ports/cxd56/common-hal/pulseio/PulseIn.c +++ b/ports/cxd56/common-hal/pulseio/PulseIn.c @@ -54,7 +54,7 @@ static int pulsein_interrupt_handler(int irq, FAR void *context, FAR void *arg) // Grab the current time first. struct timeval tv; gettimeofday(&tv, NULL); - uint64_t current_us = ((uint64_t) tv.tv_sec) * 1000000 + tv.tv_usec; + uint64_t current_us = ((uint64_t)tv.tv_sec) * 1000000 + tv.tv_usec; pulseio_pulsein_obj_t *self = pulsein_objects[irq - CXD56_IRQ_EXDEVICE_0]; @@ -85,7 +85,7 @@ static int pulsein_interrupt_handler(int irq, FAR void *context, FAR void *arg) void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state) { - self->buffer = (uint16_t *) m_malloc(maxlen * sizeof(uint16_t), false); + self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t), false); if (self->buffer == NULL) { mp_raise_msg_varg(&mp_type_MemoryError, translate("Failed to allocate RX buffer of %d bytes"), maxlen * sizeof(uint16_t)); } diff --git a/ports/cxd56/common-hal/pulseio/PulseOut.c b/ports/cxd56/common-hal/pulseio/PulseOut.c index f08e7cd7a0..be0d51f575 100644 --- a/ports/cxd56/common-hal/pulseio/PulseOut.c +++ b/ports/cxd56/common-hal/pulseio/PulseOut.c @@ -38,8 +38,7 @@ static uint16_t pulse_index = 0; static uint16_t pulse_length; static int pulse_fd = -1; -static bool pulseout_timer_handler(unsigned int *next_interval_us, void *arg) -{ +static bool pulseout_timer_handler(unsigned int *next_interval_us, void *arg) { uint8_t pwm_num = (uint8_t)(int)arg; pulse_index++; @@ -58,11 +57,11 @@ static bool pulseout_timer_handler(unsigned int *next_interval_us, void *arg) return true; } -void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, - const pwmio_pwmout_obj_t* carrier, - const mcu_pin_obj_t* pin, - uint32_t frequency, - uint16_t duty_cycle) { +void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, + const pwmio_pwmout_obj_t *carrier, + const mcu_pin_obj_t *pin, + uint32_t frequency, + uint16_t duty_cycle) { if (!carrier || pin || frequency) { mp_raise_NotImplementedError(translate("Port does not accept pins or frequency. Construct and pass a PWMOut Carrier instead")); } @@ -110,12 +109,12 @@ void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pu ioctl(pulse_fd, TCIOC_SETTIMEOUT, timeout); sethandler.handler = pulseout_timer_handler; - sethandler.arg = (void *)(int)self->pwm_num; + sethandler.arg = (void *)(int)self->pwm_num; ioctl(pulse_fd, TCIOC_SETHANDLER, (unsigned long)&sethandler); ioctl(pulse_fd, TCIOC_START, 0); - while(pulse_index < len) { + while (pulse_index < len) { // Do other things while we wait. The interrupts will handle sending the // signal. RUN_BACKGROUND_TASKS; diff --git a/ports/cxd56/common-hal/pwmio/PWMOut.c b/ports/cxd56/common-hal/pwmio/PWMOut.c index e0eb7abde8..61806540b1 100644 --- a/ports/cxd56/common-hal/pwmio/PWMOut.c +++ b/ports/cxd56/common-hal/pwmio/PWMOut.c @@ -33,7 +33,7 @@ #include "shared-bindings/pwmio/PWMOut.h" typedef struct { - const char* devpath; + const char *devpath; const mcu_pin_obj_t *pin; int fd; bool reset; @@ -141,11 +141,11 @@ void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { void pwmout_reset(void) { for (int i = 0; i < MP_ARRAY_SIZE(pwmout_dev); i++) { if (pwmout_dev[i].fd >= 0 && pwmout_dev[i].reset) { - ioctl(pwmout_dev[i].fd, PWMIOC_STOP, 0); - close(pwmout_dev[i].fd); - pwmout_dev[i].fd = -1; + ioctl(pwmout_dev[i].fd, PWMIOC_STOP, 0); + close(pwmout_dev[i].fd); + pwmout_dev[i].fd = -1; - reset_pin_number(pwmout_dev[i].pin->number); + reset_pin_number(pwmout_dev[i].pin->number); } } } diff --git a/ports/cxd56/common-hal/sdioio/SDCard.c b/ports/cxd56/common-hal/sdioio/SDCard.c index cf7de422c1..cf8986a4f8 100644 --- a/ports/cxd56/common-hal/sdioio/SDCard.c +++ b/ports/cxd56/common-hal/sdioio/SDCard.c @@ -96,15 +96,15 @@ bool common_hal_sdioio_sdcard_configure(sdioio_sdcard_obj_t *self, uint32_t baud return true; } -uint32_t common_hal_sdioio_sdcard_get_frequency(sdioio_sdcard_obj_t* self) { +uint32_t common_hal_sdioio_sdcard_get_frequency(sdioio_sdcard_obj_t *self) { return self->frequency; } -uint8_t common_hal_sdioio_sdcard_get_width(sdioio_sdcard_obj_t* self) { +uint8_t common_hal_sdioio_sdcard_get_width(sdioio_sdcard_obj_t *self) { return self->width; } -uint32_t common_hal_sdioio_sdcard_get_count(sdioio_sdcard_obj_t* self) { +uint32_t common_hal_sdioio_sdcard_get_count(sdioio_sdcard_obj_t *self) { return self->count; } @@ -114,7 +114,7 @@ STATIC void check_whole_block(mp_buffer_info_t *bufinfo) { } } -int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t* self, uint32_t start_block, mp_buffer_info_t *bufinfo) { +int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { if (common_hal_sdioio_sdcard_deinited(self)) { raise_deinited_error(); } @@ -123,13 +123,14 @@ int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t* self, uint32_t star return self->inode->u.i_bops->read(self->inode, bufinfo->buf, start_block, bufinfo->len / 512); } -int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t* self, uint32_t start_block, mp_buffer_info_t *bufinfo) { +int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { if (common_hal_sdioio_sdcard_deinited(self)) { raise_deinited_error(); } check_whole_block(bufinfo); - return self->inode->u.i_bops->write(self->inode, bufinfo->buf, start_block, bufinfo->len / 512);; + return self->inode->u.i_bops->write(self->inode, bufinfo->buf, start_block, bufinfo->len / 512); + ; } void common_hal_sdioio_sdcard_never_reset(sdioio_sdcard_obj_t *self) { diff --git a/ports/cxd56/common-hal/sdioio/SDCard.h b/ports/cxd56/common-hal/sdioio/SDCard.h index cbdcd47069..04f6ccdba2 100644 --- a/ports/cxd56/common-hal/sdioio/SDCard.h +++ b/ports/cxd56/common-hal/sdioio/SDCard.h @@ -35,7 +35,7 @@ typedef struct { mp_obj_base_t base; - struct inode* inode; + struct inode *inode; uint32_t frequency; uint32_t count; uint8_t width; diff --git a/ports/cxd56/common-hal/supervisor/Runtime.c b/ports/cxd56/common-hal/supervisor/Runtime.c old mode 100755 new mode 100644 index eeeb1430f4..6ecdc2581e --- a/ports/cxd56/common-hal/supervisor/Runtime.c +++ b/ports/cxd56/common-hal/supervisor/Runtime.c @@ -28,9 +28,9 @@ #include "supervisor/serial.h" bool common_hal_supervisor_runtime_get_serial_connected(void) { - return (bool) serial_connected(); + return (bool)serial_connected(); } bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); + return (bool)serial_bytes_available(); } diff --git a/ports/cxd56/fatfs_port.c b/ports/cxd56/fatfs_port.c index e986b4c6eb..a58465b983 100644 --- a/ports/cxd56/fatfs_port.c +++ b/ports/cxd56/fatfs_port.c @@ -35,12 +35,12 @@ #endif DWORD get_fattime(void) { -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC timeutils_struct_time_t tm; common_hal_rtc_get_time(&tm); return ((tm.tm_year - 1980) << 25) | (tm.tm_mon << 21) | (tm.tm_mday << 16) | - (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1); -#else + (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1); + #else return ((2016 - 1980) << 25) | ((9) << 21) | ((1) << 16) | ((16) << 11) | ((43) << 5) | (35 / 2); -#endif + #endif } diff --git a/ports/cxd56/mkspk/clefia.c b/ports/cxd56/mkspk/clefia.c index 02a175505d..e946ee5348 100644 --- a/ports/cxd56/mkspk/clefia.c +++ b/ports/cxd56/mkspk/clefia.c @@ -60,458 +60,424 @@ static const unsigned char clefia_s0[256] = { - 0x57u, 0x49u, 0xd1u, 0xc6u, 0x2fu, 0x33u, 0x74u, 0xfbu, - 0x95u, 0x6du, 0x82u, 0xeau, 0x0eu, 0xb0u, 0xa8u, 0x1cu, - 0x28u, 0xd0u, 0x4bu, 0x92u, 0x5cu, 0xeeu, 0x85u, 0xb1u, - 0xc4u, 0x0au, 0x76u, 0x3du, 0x63u, 0xf9u, 0x17u, 0xafu, - 0xbfu, 0xa1u, 0x19u, 0x65u, 0xf7u, 0x7au, 0x32u, 0x20u, - 0x06u, 0xceu, 0xe4u, 0x83u, 0x9du, 0x5bu, 0x4cu, 0xd8u, - 0x42u, 0x5du, 0x2eu, 0xe8u, 0xd4u, 0x9bu, 0x0fu, 0x13u, - 0x3cu, 0x89u, 0x67u, 0xc0u, 0x71u, 0xaau, 0xb6u, 0xf5u, - 0xa4u, 0xbeu, 0xfdu, 0x8cu, 0x12u, 0x00u, 0x97u, 0xdau, - 0x78u, 0xe1u, 0xcfu, 0x6bu, 0x39u, 0x43u, 0x55u, 0x26u, - 0x30u, 0x98u, 0xccu, 0xddu, 0xebu, 0x54u, 0xb3u, 0x8fu, - 0x4eu, 0x16u, 0xfau, 0x22u, 0xa5u, 0x77u, 0x09u, 0x61u, - 0xd6u, 0x2au, 0x53u, 0x37u, 0x45u, 0xc1u, 0x6cu, 0xaeu, - 0xefu, 0x70u, 0x08u, 0x99u, 0x8bu, 0x1du, 0xf2u, 0xb4u, - 0xe9u, 0xc7u, 0x9fu, 0x4au, 0x31u, 0x25u, 0xfeu, 0x7cu, - 0xd3u, 0xa2u, 0xbdu, 0x56u, 0x14u, 0x88u, 0x60u, 0x0bu, - 0xcdu, 0xe2u, 0x34u, 0x50u, 0x9eu, 0xdcu, 0x11u, 0x05u, - 0x2bu, 0xb7u, 0xa9u, 0x48u, 0xffu, 0x66u, 0x8au, 0x73u, - 0x03u, 0x75u, 0x86u, 0xf1u, 0x6au, 0xa7u, 0x40u, 0xc2u, - 0xb9u, 0x2cu, 0xdbu, 0x1fu, 0x58u, 0x94u, 0x3eu, 0xedu, - 0xfcu, 0x1bu, 0xa0u, 0x04u, 0xb8u, 0x8du, 0xe6u, 0x59u, - 0x62u, 0x93u, 0x35u, 0x7eu, 0xcau, 0x21u, 0xdfu, 0x47u, - 0x15u, 0xf3u, 0xbau, 0x7fu, 0xa6u, 0x69u, 0xc8u, 0x4du, - 0x87u, 0x3bu, 0x9cu, 0x01u, 0xe0u, 0xdeu, 0x24u, 0x52u, - 0x7bu, 0x0cu, 0x68u, 0x1eu, 0x80u, 0xb2u, 0x5au, 0xe7u, - 0xadu, 0xd5u, 0x23u, 0xf4u, 0x46u, 0x3fu, 0x91u, 0xc9u, - 0x6eu, 0x84u, 0x72u, 0xbbu, 0x0du, 0x18u, 0xd9u, 0x96u, - 0xf0u, 0x5fu, 0x41u, 0xacu, 0x27u, 0xc5u, 0xe3u, 0x3au, - 0x81u, 0x6fu, 0x07u, 0xa3u, 0x79u, 0xf6u, 0x2du, 0x38u, - 0x1au, 0x44u, 0x5eu, 0xb5u, 0xd2u, 0xecu, 0xcbu, 0x90u, - 0x9au, 0x36u, 0xe5u, 0x29u, 0xc3u, 0x4fu, 0xabu, 0x64u, - 0x51u, 0xf8u, 0x10u, 0xd7u, 0xbcu, 0x02u, 0x7du, 0x8eu + 0x57u, 0x49u, 0xd1u, 0xc6u, 0x2fu, 0x33u, 0x74u, 0xfbu, + 0x95u, 0x6du, 0x82u, 0xeau, 0x0eu, 0xb0u, 0xa8u, 0x1cu, + 0x28u, 0xd0u, 0x4bu, 0x92u, 0x5cu, 0xeeu, 0x85u, 0xb1u, + 0xc4u, 0x0au, 0x76u, 0x3du, 0x63u, 0xf9u, 0x17u, 0xafu, + 0xbfu, 0xa1u, 0x19u, 0x65u, 0xf7u, 0x7au, 0x32u, 0x20u, + 0x06u, 0xceu, 0xe4u, 0x83u, 0x9du, 0x5bu, 0x4cu, 0xd8u, + 0x42u, 0x5du, 0x2eu, 0xe8u, 0xd4u, 0x9bu, 0x0fu, 0x13u, + 0x3cu, 0x89u, 0x67u, 0xc0u, 0x71u, 0xaau, 0xb6u, 0xf5u, + 0xa4u, 0xbeu, 0xfdu, 0x8cu, 0x12u, 0x00u, 0x97u, 0xdau, + 0x78u, 0xe1u, 0xcfu, 0x6bu, 0x39u, 0x43u, 0x55u, 0x26u, + 0x30u, 0x98u, 0xccu, 0xddu, 0xebu, 0x54u, 0xb3u, 0x8fu, + 0x4eu, 0x16u, 0xfau, 0x22u, 0xa5u, 0x77u, 0x09u, 0x61u, + 0xd6u, 0x2au, 0x53u, 0x37u, 0x45u, 0xc1u, 0x6cu, 0xaeu, + 0xefu, 0x70u, 0x08u, 0x99u, 0x8bu, 0x1du, 0xf2u, 0xb4u, + 0xe9u, 0xc7u, 0x9fu, 0x4au, 0x31u, 0x25u, 0xfeu, 0x7cu, + 0xd3u, 0xa2u, 0xbdu, 0x56u, 0x14u, 0x88u, 0x60u, 0x0bu, + 0xcdu, 0xe2u, 0x34u, 0x50u, 0x9eu, 0xdcu, 0x11u, 0x05u, + 0x2bu, 0xb7u, 0xa9u, 0x48u, 0xffu, 0x66u, 0x8au, 0x73u, + 0x03u, 0x75u, 0x86u, 0xf1u, 0x6au, 0xa7u, 0x40u, 0xc2u, + 0xb9u, 0x2cu, 0xdbu, 0x1fu, 0x58u, 0x94u, 0x3eu, 0xedu, + 0xfcu, 0x1bu, 0xa0u, 0x04u, 0xb8u, 0x8du, 0xe6u, 0x59u, + 0x62u, 0x93u, 0x35u, 0x7eu, 0xcau, 0x21u, 0xdfu, 0x47u, + 0x15u, 0xf3u, 0xbau, 0x7fu, 0xa6u, 0x69u, 0xc8u, 0x4du, + 0x87u, 0x3bu, 0x9cu, 0x01u, 0xe0u, 0xdeu, 0x24u, 0x52u, + 0x7bu, 0x0cu, 0x68u, 0x1eu, 0x80u, 0xb2u, 0x5au, 0xe7u, + 0xadu, 0xd5u, 0x23u, 0xf4u, 0x46u, 0x3fu, 0x91u, 0xc9u, + 0x6eu, 0x84u, 0x72u, 0xbbu, 0x0du, 0x18u, 0xd9u, 0x96u, + 0xf0u, 0x5fu, 0x41u, 0xacu, 0x27u, 0xc5u, 0xe3u, 0x3au, + 0x81u, 0x6fu, 0x07u, 0xa3u, 0x79u, 0xf6u, 0x2du, 0x38u, + 0x1au, 0x44u, 0x5eu, 0xb5u, 0xd2u, 0xecu, 0xcbu, 0x90u, + 0x9au, 0x36u, 0xe5u, 0x29u, 0xc3u, 0x4fu, 0xabu, 0x64u, + 0x51u, 0xf8u, 0x10u, 0xd7u, 0xbcu, 0x02u, 0x7du, 0x8eu }; /* S1 (8-bit S-box based on inverse function) */ static const unsigned char clefia_s1[256] = { - 0x6cu, 0xdau, 0xc3u, 0xe9u, 0x4eu, 0x9du, 0x0au, 0x3du, - 0xb8u, 0x36u, 0xb4u, 0x38u, 0x13u, 0x34u, 0x0cu, 0xd9u, - 0xbfu, 0x74u, 0x94u, 0x8fu, 0xb7u, 0x9cu, 0xe5u, 0xdcu, - 0x9eu, 0x07u, 0x49u, 0x4fu, 0x98u, 0x2cu, 0xb0u, 0x93u, - 0x12u, 0xebu, 0xcdu, 0xb3u, 0x92u, 0xe7u, 0x41u, 0x60u, - 0xe3u, 0x21u, 0x27u, 0x3bu, 0xe6u, 0x19u, 0xd2u, 0x0eu, - 0x91u, 0x11u, 0xc7u, 0x3fu, 0x2au, 0x8eu, 0xa1u, 0xbcu, - 0x2bu, 0xc8u, 0xc5u, 0x0fu, 0x5bu, 0xf3u, 0x87u, 0x8bu, - 0xfbu, 0xf5u, 0xdeu, 0x20u, 0xc6u, 0xa7u, 0x84u, 0xceu, - 0xd8u, 0x65u, 0x51u, 0xc9u, 0xa4u, 0xefu, 0x43u, 0x53u, - 0x25u, 0x5du, 0x9bu, 0x31u, 0xe8u, 0x3eu, 0x0du, 0xd7u, - 0x80u, 0xffu, 0x69u, 0x8au, 0xbau, 0x0bu, 0x73u, 0x5cu, - 0x6eu, 0x54u, 0x15u, 0x62u, 0xf6u, 0x35u, 0x30u, 0x52u, - 0xa3u, 0x16u, 0xd3u, 0x28u, 0x32u, 0xfau, 0xaau, 0x5eu, - 0xcfu, 0xeau, 0xedu, 0x78u, 0x33u, 0x58u, 0x09u, 0x7bu, - 0x63u, 0xc0u, 0xc1u, 0x46u, 0x1eu, 0xdfu, 0xa9u, 0x99u, - 0x55u, 0x04u, 0xc4u, 0x86u, 0x39u, 0x77u, 0x82u, 0xecu, - 0x40u, 0x18u, 0x90u, 0x97u, 0x59u, 0xddu, 0x83u, 0x1fu, - 0x9au, 0x37u, 0x06u, 0x24u, 0x64u, 0x7cu, 0xa5u, 0x56u, - 0x48u, 0x08u, 0x85u, 0xd0u, 0x61u, 0x26u, 0xcau, 0x6fu, - 0x7eu, 0x6au, 0xb6u, 0x71u, 0xa0u, 0x70u, 0x05u, 0xd1u, - 0x45u, 0x8cu, 0x23u, 0x1cu, 0xf0u, 0xeeu, 0x89u, 0xadu, - 0x7au, 0x4bu, 0xc2u, 0x2fu, 0xdbu, 0x5au, 0x4du, 0x76u, - 0x67u, 0x17u, 0x2du, 0xf4u, 0xcbu, 0xb1u, 0x4au, 0xa8u, - 0xb5u, 0x22u, 0x47u, 0x3au, 0xd5u, 0x10u, 0x4cu, 0x72u, - 0xccu, 0x00u, 0xf9u, 0xe0u, 0xfdu, 0xe2u, 0xfeu, 0xaeu, - 0xf8u, 0x5fu, 0xabu, 0xf1u, 0x1bu, 0x42u, 0x81u, 0xd6u, - 0xbeu, 0x44u, 0x29u, 0xa6u, 0x57u, 0xb9u, 0xafu, 0xf2u, - 0xd4u, 0x75u, 0x66u, 0xbbu, 0x68u, 0x9fu, 0x50u, 0x02u, - 0x01u, 0x3cu, 0x7fu, 0x8du, 0x1au, 0x88u, 0xbdu, 0xacu, - 0xf7u, 0xe4u, 0x79u, 0x96u, 0xa2u, 0xfcu, 0x6du, 0xb2u, - 0x6bu, 0x03u, 0xe1u, 0x2eu, 0x7du, 0x14u, 0x95u, 0x1du + 0x6cu, 0xdau, 0xc3u, 0xe9u, 0x4eu, 0x9du, 0x0au, 0x3du, + 0xb8u, 0x36u, 0xb4u, 0x38u, 0x13u, 0x34u, 0x0cu, 0xd9u, + 0xbfu, 0x74u, 0x94u, 0x8fu, 0xb7u, 0x9cu, 0xe5u, 0xdcu, + 0x9eu, 0x07u, 0x49u, 0x4fu, 0x98u, 0x2cu, 0xb0u, 0x93u, + 0x12u, 0xebu, 0xcdu, 0xb3u, 0x92u, 0xe7u, 0x41u, 0x60u, + 0xe3u, 0x21u, 0x27u, 0x3bu, 0xe6u, 0x19u, 0xd2u, 0x0eu, + 0x91u, 0x11u, 0xc7u, 0x3fu, 0x2au, 0x8eu, 0xa1u, 0xbcu, + 0x2bu, 0xc8u, 0xc5u, 0x0fu, 0x5bu, 0xf3u, 0x87u, 0x8bu, + 0xfbu, 0xf5u, 0xdeu, 0x20u, 0xc6u, 0xa7u, 0x84u, 0xceu, + 0xd8u, 0x65u, 0x51u, 0xc9u, 0xa4u, 0xefu, 0x43u, 0x53u, + 0x25u, 0x5du, 0x9bu, 0x31u, 0xe8u, 0x3eu, 0x0du, 0xd7u, + 0x80u, 0xffu, 0x69u, 0x8au, 0xbau, 0x0bu, 0x73u, 0x5cu, + 0x6eu, 0x54u, 0x15u, 0x62u, 0xf6u, 0x35u, 0x30u, 0x52u, + 0xa3u, 0x16u, 0xd3u, 0x28u, 0x32u, 0xfau, 0xaau, 0x5eu, + 0xcfu, 0xeau, 0xedu, 0x78u, 0x33u, 0x58u, 0x09u, 0x7bu, + 0x63u, 0xc0u, 0xc1u, 0x46u, 0x1eu, 0xdfu, 0xa9u, 0x99u, + 0x55u, 0x04u, 0xc4u, 0x86u, 0x39u, 0x77u, 0x82u, 0xecu, + 0x40u, 0x18u, 0x90u, 0x97u, 0x59u, 0xddu, 0x83u, 0x1fu, + 0x9au, 0x37u, 0x06u, 0x24u, 0x64u, 0x7cu, 0xa5u, 0x56u, + 0x48u, 0x08u, 0x85u, 0xd0u, 0x61u, 0x26u, 0xcau, 0x6fu, + 0x7eu, 0x6au, 0xb6u, 0x71u, 0xa0u, 0x70u, 0x05u, 0xd1u, + 0x45u, 0x8cu, 0x23u, 0x1cu, 0xf0u, 0xeeu, 0x89u, 0xadu, + 0x7au, 0x4bu, 0xc2u, 0x2fu, 0xdbu, 0x5au, 0x4du, 0x76u, + 0x67u, 0x17u, 0x2du, 0xf4u, 0xcbu, 0xb1u, 0x4au, 0xa8u, + 0xb5u, 0x22u, 0x47u, 0x3au, 0xd5u, 0x10u, 0x4cu, 0x72u, + 0xccu, 0x00u, 0xf9u, 0xe0u, 0xfdu, 0xe2u, 0xfeu, 0xaeu, + 0xf8u, 0x5fu, 0xabu, 0xf1u, 0x1bu, 0x42u, 0x81u, 0xd6u, + 0xbeu, 0x44u, 0x29u, 0xa6u, 0x57u, 0xb9u, 0xafu, 0xf2u, + 0xd4u, 0x75u, 0x66u, 0xbbu, 0x68u, 0x9fu, 0x50u, 0x02u, + 0x01u, 0x3cu, 0x7fu, 0x8du, 0x1au, 0x88u, 0xbdu, 0xacu, + 0xf7u, 0xe4u, 0x79u, 0x96u, 0xa2u, 0xfcu, 0x6du, 0xb2u, + 0x6bu, 0x03u, 0xe1u, 0x2eu, 0x7du, 0x14u, 0x95u, 0x1du }; /**************************************************************************** * Private Functions ****************************************************************************/ -static void bytecpy(unsigned char *dst, const unsigned char *src, int bytelen) -{ - while (bytelen-- > 0) - { - *dst++ = *src++; +static void bytecpy(unsigned char *dst, const unsigned char *src, int bytelen) { + while (bytelen-- > 0) { + *dst++ = *src++; } } -static unsigned char clefiamul2(unsigned char x) -{ - /* multiplication over GF(2^8) (p(x) = '11d') */ +static unsigned char clefiamul2(unsigned char x) { + /* multiplication over GF(2^8) (p(x) = '11d') */ - if (x & 0x80u) - { - x ^= 0x0eu; + if (x & 0x80u) { + x ^= 0x0eu; } - return ((x << 1) | (x >> 7)); + return (x << 1) | (x >> 7); } static void clefiaf0xor(unsigned char *dst, const unsigned char *src, - const unsigned char *rk) -{ - unsigned char x[4]; - unsigned char y[4]; - unsigned char z[4]; + const unsigned char *rk) { + unsigned char x[4]; + unsigned char y[4]; + unsigned char z[4]; - /* F0 */ + /* F0 */ - /* Key addition */ + /* Key addition */ - bytexor(x, src, rk, 4); + bytexor(x, src, rk, 4); - /* Substitution layer */ + /* Substitution layer */ - z[0] = clefia_s0[x[0]]; - z[1] = clefia_s1[x[1]]; - z[2] = clefia_s0[x[2]]; - z[3] = clefia_s1[x[3]]; + z[0] = clefia_s0[x[0]]; + z[1] = clefia_s1[x[1]]; + z[2] = clefia_s0[x[2]]; + z[3] = clefia_s1[x[3]]; - /* Diffusion layer (M0) */ + /* Diffusion layer (M0) */ - y[0] = z[0] ^ clefiamul2(z[1]) ^ clefiamul4(z[2]) ^ clefiamul6(z[3]); - y[1] = clefiamul2(z[0]) ^ z[1] ^ clefiamul6(z[2]) ^ clefiamul4(z[3]); - y[2] = clefiamul4(z[0]) ^ clefiamul6(z[1]) ^ z[2] ^ clefiamul2(z[3]); - y[3] = clefiamul6(z[0]) ^ clefiamul4(z[1]) ^ clefiamul2(z[2]) ^ z[3]; + y[0] = z[0] ^ clefiamul2(z[1]) ^ clefiamul4(z[2]) ^ clefiamul6(z[3]); + y[1] = clefiamul2(z[0]) ^ z[1] ^ clefiamul6(z[2]) ^ clefiamul4(z[3]); + y[2] = clefiamul4(z[0]) ^ clefiamul6(z[1]) ^ z[2] ^ clefiamul2(z[3]); + y[3] = clefiamul6(z[0]) ^ clefiamul4(z[1]) ^ clefiamul2(z[2]) ^ z[3]; - /* Xoring after F0 */ + /* Xoring after F0 */ - bytecpy(dst + 0, src + 0, 4); - bytexor(dst + 4, src + 4, y, 4); + bytecpy(dst + 0, src + 0, 4); + bytexor(dst + 4, src + 4, y, 4); } static void clefiaf1xor(unsigned char *dst, const unsigned char *src, - const unsigned char *rk) -{ - unsigned char x[4]; - unsigned char y[4]; - unsigned char z[4]; + const unsigned char *rk) { + unsigned char x[4]; + unsigned char y[4]; + unsigned char z[4]; - /* F1 */ + /* F1 */ - /* Key addition */ + /* Key addition */ - bytexor(x, src, rk, 4); + bytexor(x, src, rk, 4); - /* Substitution layer */ + /* Substitution layer */ - z[0] = clefia_s1[x[0]]; - z[1] = clefia_s0[x[1]]; - z[2] = clefia_s1[x[2]]; - z[3] = clefia_s0[x[3]]; + z[0] = clefia_s1[x[0]]; + z[1] = clefia_s0[x[1]]; + z[2] = clefia_s1[x[2]]; + z[3] = clefia_s0[x[3]]; - /* Diffusion layer (M1) */ + /* Diffusion layer (M1) */ - y[0] = z[0] ^ clefiamul8(z[1]) ^ clefiamul2(z[2]) ^ clefiamula(z[3]); - y[1] = clefiamul8(z[0]) ^ z[1] ^ clefiamula(z[2]) ^ clefiamul2(z[3]); - y[2] = clefiamul2(z[0]) ^ clefiamula(z[1]) ^ z[2] ^ clefiamul8(z[3]); - y[3] = clefiamula(z[0]) ^ clefiamul2(z[1]) ^ clefiamul8(z[2]) ^ z[3]; + y[0] = z[0] ^ clefiamul8(z[1]) ^ clefiamul2(z[2]) ^ clefiamula(z[3]); + y[1] = clefiamul8(z[0]) ^ z[1] ^ clefiamula(z[2]) ^ clefiamul2(z[3]); + y[2] = clefiamul2(z[0]) ^ clefiamula(z[1]) ^ z[2] ^ clefiamul8(z[3]); + y[3] = clefiamula(z[0]) ^ clefiamul2(z[1]) ^ clefiamul8(z[2]) ^ z[3]; - /* Xoring after F1 */ + /* Xoring after F1 */ - bytecpy(dst + 0, src + 0, 4); - bytexor(dst + 4, src + 4, y, 4); + bytecpy(dst + 0, src + 0, 4); + bytexor(dst + 4, src + 4, y, 4); } static void clefiagfn4(unsigned char *y, const unsigned char *x, - const unsigned char *rk, int r) -{ - unsigned char fin[16]; - unsigned char fout[16]; + const unsigned char *rk, int r) { + unsigned char fin[16]; + unsigned char fout[16]; - bytecpy(fin, x, 16); - while (r-- > 0) - { - clefiaf0xor(fout + 0, fin + 0, rk + 0); - clefiaf1xor(fout + 8, fin + 8, rk + 4); - rk += 8; - if (r) - { - /* swapping for encryption */ + bytecpy(fin, x, 16); + while (r-- > 0) { + clefiaf0xor(fout + 0, fin + 0, rk + 0); + clefiaf1xor(fout + 8, fin + 8, rk + 4); + rk += 8; + if (r) { + /* swapping for encryption */ - bytecpy(fin + 0, fout + 4, 12); - bytecpy(fin + 12, fout + 0, 4); + bytecpy(fin + 0, fout + 4, 12); + bytecpy(fin + 12, fout + 0, 4); } } - bytecpy(y, fout, 16); + bytecpy(y, fout, 16); } #if 0 /* Not used */ static void clefiagfn8(unsigned char *y, const unsigned char *x, - const unsigned char *rk, int r) -{ - unsigned char fin[32]; - unsigned char fout[32]; + const unsigned char *rk, int r) { + unsigned char fin[32]; + unsigned char fout[32]; - bytecpy(fin, x, 32); - while (r-- > 0) - { - clefiaf0xor(fout + 0, fin + 0, rk + 0); - clefiaf1xor(fout + 8, fin + 8, rk + 4); - clefiaf0xor(fout + 16, fin + 16, rk + 8); - clefiaf1xor(fout + 24, fin + 24, rk + 12); - rk += 16; - if (r) - { - /* swapping for encryption */ + bytecpy(fin, x, 32); + while (r-- > 0) { + clefiaf0xor(fout + 0, fin + 0, rk + 0); + clefiaf1xor(fout + 8, fin + 8, rk + 4); + clefiaf0xor(fout + 16, fin + 16, rk + 8); + clefiaf1xor(fout + 24, fin + 24, rk + 12); + rk += 16; + if (r) { + /* swapping for encryption */ - bytecpy(fin + 0, fout + 4, 28); - bytecpy(fin + 28, fout + 0, 4); + bytecpy(fin + 0, fout + 4, 28); + bytecpy(fin + 28, fout + 0, 4); } } - bytecpy(y, fout, 32); + bytecpy(y, fout, 32); } #endif #if 0 /* Not used */ static void clefiagfn4inv(unsigned char *y, const unsigned char *x, - const unsigned char *rk, int r) -{ - unsigned char fin[16]; - unsigned char fout[16]; + const unsigned char *rk, int r) { + unsigned char fin[16]; + unsigned char fout[16]; - rk += (r - 1) * 8; - bytecpy(fin, x, 16); - while (r-- > 0) - { - clefiaf0xor(fout + 0, fin + 0, rk + 0); - clefiaf1xor(fout + 8, fin + 8, rk + 4); - rk -= 8; - if (r) - { - /* swapping for decryption */ + rk += (r - 1) * 8; + bytecpy(fin, x, 16); + while (r-- > 0) { + clefiaf0xor(fout + 0, fin + 0, rk + 0); + clefiaf1xor(fout + 8, fin + 8, rk + 4); + rk -= 8; + if (r) { + /* swapping for decryption */ - bytecpy(fin + 0, fout + 12, 4); - bytecpy(fin + 4, fout + 0, 12); + bytecpy(fin + 0, fout + 12, 4); + bytecpy(fin + 4, fout + 0, 12); } } - bytecpy(y, fout, 16); + bytecpy(y, fout, 16); } #endif -static void clefiadoubleswap(unsigned char *lk) -{ - unsigned char t[16]; +static void clefiadoubleswap(unsigned char *lk) { + unsigned char t[16]; - t[0] = (lk[0] << 7) | (lk[1] >> 1); - t[1] = (lk[1] << 7) | (lk[2] >> 1); - t[2] = (lk[2] << 7) | (lk[3] >> 1); - t[3] = (lk[3] << 7) | (lk[4] >> 1); - t[4] = (lk[4] << 7) | (lk[5] >> 1); - t[5] = (lk[5] << 7) | (lk[6] >> 1); - t[6] = (lk[6] << 7) | (lk[7] >> 1); - t[7] = (lk[7] << 7) | (lk[15] & 0x7fu); + t[0] = (lk[0] << 7) | (lk[1] >> 1); + t[1] = (lk[1] << 7) | (lk[2] >> 1); + t[2] = (lk[2] << 7) | (lk[3] >> 1); + t[3] = (lk[3] << 7) | (lk[4] >> 1); + t[4] = (lk[4] << 7) | (lk[5] >> 1); + t[5] = (lk[5] << 7) | (lk[6] >> 1); + t[6] = (lk[6] << 7) | (lk[7] >> 1); + t[7] = (lk[7] << 7) | (lk[15] & 0x7fu); - t[8] = (lk[8] >> 7) | (lk[0] & 0xfeu); - t[9] = (lk[9] >> 7) | (lk[8] << 1); - t[10] = (lk[10] >> 7) | (lk[9] << 1); - t[11] = (lk[11] >> 7) | (lk[10] << 1); - t[12] = (lk[12] >> 7) | (lk[11] << 1); - t[13] = (lk[13] >> 7) | (lk[12] << 1); - t[14] = (lk[14] >> 7) | (lk[13] << 1); - t[15] = (lk[15] >> 7) | (lk[14] << 1); + t[8] = (lk[8] >> 7) | (lk[0] & 0xfeu); + t[9] = (lk[9] >> 7) | (lk[8] << 1); + t[10] = (lk[10] >> 7) | (lk[9] << 1); + t[11] = (lk[11] >> 7) | (lk[10] << 1); + t[12] = (lk[12] >> 7) | (lk[11] << 1); + t[13] = (lk[13] >> 7) | (lk[12] << 1); + t[14] = (lk[14] >> 7) | (lk[13] << 1); + t[15] = (lk[15] >> 7) | (lk[14] << 1); - bytecpy(lk, t, 16); + bytecpy(lk, t, 16); } -static void clefiaconset(unsigned char *con, const unsigned char *iv, int lk) -{ - unsigned char t[2]; - unsigned char tmp; +static void clefiaconset(unsigned char *con, const unsigned char *iv, int lk) { + unsigned char t[2]; + unsigned char tmp; - bytecpy(t, iv, 2); - while (lk-- > 0) - { - con[0] = t[0] ^ 0xb7u; /* P_16 = 0xb7e1 (natural logarithm) */ - con[1] = t[1] ^ 0xe1u; - con[2] = ~((t[0] << 1) | (t[1] >> 7)); - con[3] = ~((t[1] << 1) | (t[0] >> 7)); - con[4] = ~t[0] ^ 0x24u; /* Q_16 = 0x243f (circle ratio) */ - con[5] = ~t[1] ^ 0x3fu; - con[6] = t[1]; - con[7] = t[0]; - con += 8; + bytecpy(t, iv, 2); + while (lk-- > 0) { + con[0] = t[0] ^ 0xb7u; /* P_16 = 0xb7e1 (natural logarithm) */ + con[1] = t[1] ^ 0xe1u; + con[2] = ~((t[0] << 1) | (t[1] >> 7)); + con[3] = ~((t[1] << 1) | (t[0] >> 7)); + con[4] = ~t[0] ^ 0x24u; /* Q_16 = 0x243f (circle ratio) */ + con[5] = ~t[1] ^ 0x3fu; + con[6] = t[1]; + con[7] = t[0]; + con += 8; - /* updating T */ + /* updating T */ - if (t[1] & 0x01u) - { - t[0] ^= 0xa8u; - t[1] ^= 0x30u; + if (t[1] & 0x01u) { + t[0] ^= 0xa8u; + t[1] ^= 0x30u; } - tmp = t[0] << 7; - t[0] = (t[0] >> 1) | (t[1] << 7); - t[1] = (t[1] >> 1) | tmp; + tmp = t[0] << 7; + t[0] = (t[0] >> 1) | (t[1] << 7); + t[1] = (t[1] >> 1) | tmp; } } -static void left_shift_one(uint8_t * in, uint8_t * out) -{ - int i; - int overflow; +static void left_shift_one(uint8_t *in, uint8_t *out) { + int i; + int overflow; - overflow = 0; - for (i = 15; i >= 0; i--) + overflow = 0; + for (i = 15; i >= 0; i--) { - out[i] = in[i] << 1; - out[i] |= overflow; - overflow = (in[i] >> 7) & 1; + out[i] = in[i] << 1; + out[i] |= overflow; + overflow = (in[i] >> 7) & 1; } } -static void gen_subkey(struct cipher *c) -{ - uint8_t L[16]; +static void gen_subkey(struct cipher *c) { + uint8_t L[16]; - memset(L, 0, 16); - clefiaencrypt(L, L, c->rk, c->round); + memset(L, 0, 16); + clefiaencrypt(L, L, c->rk, c->round); - left_shift_one(L, c->k1); - if (L[0] & 0x80) - { - c->k1[15] = c->k1[15] ^ 0x87; + left_shift_one(L, c->k1); + if (L[0] & 0x80) { + c->k1[15] = c->k1[15] ^ 0x87; } - left_shift_one(c->k1, c->k2); - if (c->k1[0] & 0x80) - { - c->k2[15] = c->k2[15] ^ 0x87; + left_shift_one(c->k1, c->k2); + if (c->k1[0] & 0x80) { + c->k2[15] = c->k2[15] ^ 0x87; } - memset(L, 0, 16); + memset(L, 0, 16); } /**************************************************************************** * Public Functions ****************************************************************************/ -struct cipher *cipher_init(uint8_t * key, uint8_t * iv) -{ - struct cipher *c; +struct cipher *cipher_init(uint8_t *key, uint8_t *iv) { + struct cipher *c; - c = (struct cipher *)malloc(sizeof(*c)); - if (!c) - { - return NULL; + c = (struct cipher *)malloc(sizeof(*c)); + if (!c) { + return NULL; } - c->round = clefiakeyset(c->rk, key); + c->round = clefiakeyset(c->rk, key); - gen_subkey(c); - memset(c->vector, 0, 16); + gen_subkey(c); + memset(c->vector, 0, 16); - return c; + return c; } -void cipher_deinit(struct cipher *c) -{ - memset(c, 0, sizeof(*c)); - free(c); +void cipher_deinit(struct cipher *c) { + memset(c, 0, sizeof(*c)); + free(c); } -int cipher_calc_cmac(struct cipher *c, void *data, int size, void *cmac) -{ - uint8_t m[16]; - uint8_t *p; +int cipher_calc_cmac(struct cipher *c, void *data, int size, void *cmac) { + uint8_t m[16]; + uint8_t *p; - if (size & 0xf) - { - return -1; + if (size & 0xf) { + return -1; } - p = (uint8_t *) data; - while (size) - { - bytexor(m, c->vector, p, 16); - clefiaencrypt(c->vector, m, c->rk, c->round); - size -= 16; - p += 16; + p = (uint8_t *)data; + while (size) { + bytexor(m, c->vector, p, 16); + clefiaencrypt(c->vector, m, c->rk, c->round); + size -= 16; + p += 16; } - bytexor(cmac, m, c->k1, 16); - clefiaencrypt(cmac, cmac, c->rk, c->round); - memset(m, 0, 16); + bytexor(cmac, m, c->k1, 16); + clefiaencrypt(cmac, cmac, c->rk, c->round); + memset(m, 0, 16); - return 0; + return 0; } void bytexor(unsigned char *dst, const unsigned char *a, - const unsigned char *b, int bytelen) -{ - while (bytelen-- > 0) - { - *dst++ = *a++ ^ *b++; + const unsigned char *b, int bytelen) { + while (bytelen-- > 0) { + *dst++ = *a++ ^ *b++; } } -int clefiakeyset(unsigned char *rk, const unsigned char *skey) -{ - const unsigned char iv[2] = - { - 0x42u, 0x8au /* cubic root of 2 */ - }; - - unsigned char lk[16]; - unsigned char con128[4 * 60]; - int i; - - /* generating CONi^(128) (0 <= i < 60, lk = 30) */ - - clefiaconset(con128, iv, 30); - - /* GFN_{4,12} (generating L from K) */ - - clefiagfn4(lk, skey, con128, 12); - - bytecpy(rk, skey, 8); /* initial whitening key (WK0, WK1) */ - rk += 8; - for (i = 0; i < 9; i++) +int clefiakeyset(unsigned char *rk, const unsigned char *skey) { + const unsigned char iv[2] = { - /* round key (RKi (0 <= i < 36)) */ + 0x42u, 0x8au /* cubic root of 2 */ + }; - bytexor(rk, lk, con128 + i * 16 + (4 * 24), 16); - if (i % 2) - { - bytexor(rk, rk, skey, 16); /* Xoring K */ + unsigned char lk[16]; + unsigned char con128[4 * 60]; + int i; + + /* generating CONi^(128) (0 <= i < 60, lk = 30) */ + + clefiaconset(con128, iv, 30); + + /* GFN_{4,12} (generating L from K) */ + + clefiagfn4(lk, skey, con128, 12); + + bytecpy(rk, skey, 8); /* initial whitening key (WK0, WK1) */ + rk += 8; + for (i = 0; i < 9; i++) + { + /* round key (RKi (0 <= i < 36)) */ + + bytexor(rk, lk, con128 + i * 16 + (4 * 24), 16); + if (i % 2) { + bytexor(rk, rk, skey, 16); /* Xoring K */ } - clefiadoubleswap(lk); /* Updating L (DoubleSwap function) */ - rk += 16; + clefiadoubleswap(lk); /* Updating L (DoubleSwap function) */ + rk += 16; } - bytecpy(rk, skey + 8, 8); /* final whitening key (WK2, WK3) */ + bytecpy(rk, skey + 8, 8); /* final whitening key (WK2, WK3) */ - return 18; + return 18; } void clefiaencrypt(unsigned char *ct, const unsigned char *pt, - const unsigned char *rk, const int r) -{ - unsigned char rin[16]; - unsigned char rout[16]; + const unsigned char *rk, const int r) { + unsigned char rin[16]; + unsigned char rout[16]; - bytecpy(rin, pt, 16); + bytecpy(rin, pt, 16); - bytexor(rin + 4, rin + 4, rk + 0, 4); /* initial key whitening */ - bytexor(rin + 12, rin + 12, rk + 4, 4); - rk += 8; + bytexor(rin + 4, rin + 4, rk + 0, 4); /* initial key whitening */ + bytexor(rin + 12, rin + 12, rk + 4, 4); + rk += 8; - clefiagfn4(rout, rin, rk, r); /* GFN_{4,r} */ + clefiagfn4(rout, rin, rk, r); /* GFN_{4,r} */ - bytecpy(ct, rout, 16); - bytexor(ct + 4, ct + 4, rk + r * 8 + 0, 4); /* final key whitening */ - bytexor(ct + 12, ct + 12, rk + r * 8 + 4, 4); + bytecpy(ct, rout, 16); + bytexor(ct + 4, ct + 4, rk + r * 8 + 0, 4); /* final key whitening */ + bytexor(ct + 12, ct + 12, rk + r * 8 + 4, 4); } diff --git a/ports/cxd56/mkspk/clefia.h b/ports/cxd56/mkspk/clefia.h index a0e02587da..0d67643710 100644 --- a/ports/cxd56/mkspk/clefia.h +++ b/ports/cxd56/mkspk/clefia.h @@ -39,7 +39,7 @@ ****************************************************************************/ struct cipher - { +{ int mode; int dir; uint8_t rk[8 * 26 + 16]; @@ -47,19 +47,19 @@ struct cipher int round; uint8_t k1[16]; uint8_t k2[16]; - }; +}; /**************************************************************************** * Public Function Prototypes ****************************************************************************/ -struct cipher *cipher_init(uint8_t * key, uint8_t * iv); +struct cipher *cipher_init(uint8_t *key, uint8_t *iv); void cipher_deinit(struct cipher *c); int cipher_calc_cmac(struct cipher *c, void *data, int size, void *cmac); void bytexor(unsigned char *dst, const unsigned char *a, - const unsigned char *b, int bytelen); + const unsigned char *b, int bytelen); int clefiakeyset(unsigned char *rk, const unsigned char *skey); void clefiaencrypt(unsigned char *ct, const unsigned char *pt, - const unsigned char *rk, const int r); + const unsigned char *rk, const int r); #endif diff --git a/ports/cxd56/mkspk/elf32.h b/ports/cxd56/mkspk/elf32.h index 94a9c81ba3..e19ce210a6 100644 --- a/ports/cxd56/mkspk/elf32.h +++ b/ports/cxd56/mkspk/elf32.h @@ -59,7 +59,7 @@ #define ELF32_R_SYM(i) ((i) >> 8) #define ELF32_R_TYPE(i) ((i) & 0xff) -#define ELF32_R_INFO(s,t) (((s)<< 8) | ((t) & 0xff)) +#define ELF32_R_INFO(s,t) (((s) << 8) | ((t) & 0xff)) #define ELF_R_SYM(i) ELF32_R_SYM(i) @@ -69,107 +69,107 @@ /* Figure 4.2: 32-Bit Data Types */ -typedef uint32_t Elf32_Addr; /* Unsigned program address */ -typedef uint16_t Elf32_Half; /* Unsigned medium integer */ -typedef uint32_t Elf32_Off; /* Unsigned file offset */ -typedef int32_t Elf32_Sword; /* Signed large integer */ -typedef uint32_t Elf32_Word; /* Unsigned large integer */ +typedef uint32_t Elf32_Addr; /* Unsigned program address */ +typedef uint16_t Elf32_Half; /* Unsigned medium integer */ +typedef uint32_t Elf32_Off; /* Unsigned file offset */ +typedef int32_t Elf32_Sword; /* Signed large integer */ +typedef uint32_t Elf32_Word; /* Unsigned large integer */ /* Figure 4-3: ELF Header */ typedef struct { - unsigned char e_ident[EI_NIDENT]; - Elf32_Half e_type; - Elf32_Half e_machine; - Elf32_Word e_version; - Elf32_Addr e_entry; - Elf32_Off e_phoff; - Elf32_Off e_shoff; - Elf32_Word e_flags; - Elf32_Half e_ehsize; - Elf32_Half e_phentsize; - Elf32_Half e_phnum; - Elf32_Half e_shentsize; - Elf32_Half e_shnum; - Elf32_Half e_shstrndx; + unsigned char e_ident[EI_NIDENT]; + Elf32_Half e_type; + Elf32_Half e_machine; + Elf32_Word e_version; + Elf32_Addr e_entry; + Elf32_Off e_phoff; + Elf32_Off e_shoff; + Elf32_Word e_flags; + Elf32_Half e_ehsize; + Elf32_Half e_phentsize; + Elf32_Half e_phnum; + Elf32_Half e_shentsize; + Elf32_Half e_shnum; + Elf32_Half e_shstrndx; } Elf32_Ehdr; /* Figure 4-8: Section Header */ typedef struct { - Elf32_Word sh_name; - Elf32_Word sh_type; - Elf32_Word sh_flags; - Elf32_Addr sh_addr; - Elf32_Off sh_offset; - Elf32_Word sh_size; - Elf32_Word sh_link; - Elf32_Word sh_info; - Elf32_Word sh_addralign; - Elf32_Word sh_entsize; + Elf32_Word sh_name; + Elf32_Word sh_type; + Elf32_Word sh_flags; + Elf32_Addr sh_addr; + Elf32_Off sh_offset; + Elf32_Word sh_size; + Elf32_Word sh_link; + Elf32_Word sh_info; + Elf32_Word sh_addralign; + Elf32_Word sh_entsize; } Elf32_Shdr; /* Figure 4-15: Symbol Table Entry */ typedef struct { - Elf32_Word st_name; - Elf32_Addr st_value; - Elf32_Word st_size; - unsigned char st_info; - unsigned char st_other; - Elf32_Half st_shndx; + Elf32_Word st_name; + Elf32_Addr st_value; + Elf32_Word st_size; + unsigned char st_info; + unsigned char st_other; + Elf32_Half st_shndx; } Elf32_Sym; /* Figure 4-19: Relocation Entries */ typedef struct { - Elf32_Addr r_offset; - Elf32_Word r_info; + Elf32_Addr r_offset; + Elf32_Word r_info; } Elf32_Rel; typedef struct { - Elf32_Addr r_offset; - Elf32_Word r_info; - Elf32_Sword r_addend; + Elf32_Addr r_offset; + Elf32_Word r_info; + Elf32_Sword r_addend; } Elf32_Rela; /* Figure 5-1: Program Header */ typedef struct { - Elf32_Word p_type; - Elf32_Off p_offset; - Elf32_Addr p_vaddr; - Elf32_Addr p_paddr; - Elf32_Word p_filesz; - Elf32_Word p_memsz; - Elf32_Word p_flags; - Elf32_Word p_align; + Elf32_Word p_type; + Elf32_Off p_offset; + Elf32_Addr p_vaddr; + Elf32_Addr p_paddr; + Elf32_Word p_filesz; + Elf32_Word p_memsz; + Elf32_Word p_flags; + Elf32_Word p_align; } Elf32_Phdr; /* Figure 5-9: Dynamic Structure */ typedef struct { - Elf32_Sword d_tag; - union - { - Elf32_Word d_val; - Elf32_Addr d_ptr; - } d_un; + Elf32_Sword d_tag; + union + { + Elf32_Word d_val; + Elf32_Addr d_ptr; + } d_un; } Elf32_Dyn; -typedef Elf32_Addr Elf_Addr; -typedef Elf32_Ehdr Elf_Ehdr; -typedef Elf32_Rel Elf_Rel; -typedef Elf32_Rela Elf_Rela; -typedef Elf32_Sym Elf_Sym; -typedef Elf32_Shdr Elf_Shdr; -typedef Elf32_Word Elf_Word; +typedef Elf32_Addr Elf_Addr; +typedef Elf32_Ehdr Elf_Ehdr; +typedef Elf32_Rel Elf_Rel; +typedef Elf32_Rela Elf_Rela; +typedef Elf32_Sym Elf_Sym; +typedef Elf32_Shdr Elf_Shdr; +typedef Elf32_Word Elf_Word; #endif /* __INCLUDE_ELF32_H */ diff --git a/ports/cxd56/mkspk/mkspk.c b/ports/cxd56/mkspk/mkspk.c index c447ad7dab..23bafb8347 100644 --- a/ports/cxd56/mkspk/mkspk.c +++ b/ports/cxd56/mkspk/mkspk.c @@ -53,10 +53,10 @@ struct args { - int core; - char *elffile; - char *savename; - char *outputfile; + int core; + char *elffile; + char *savename; + char *outputfile; }; /**************************************************************************** @@ -64,320 +64,295 @@ struct args ****************************************************************************/ static uint8_t vmk[16] = - "\x27\xc0\xaf\x1b\x5d\xcb\xc6\xc5\x58\x22\x1c\xdd\xaf\xf3\x20\x21"; + "\x27\xc0\xaf\x1b\x5d\xcb\xc6\xc5\x58\x22\x1c\xdd\xaf\xf3\x20\x21"; static struct args g_options = { - 0 + 0 }; /**************************************************************************** * Private Functions ****************************************************************************/ -static struct args *parse_args(int argc, char **argv) -{ - int opt; - int show_help; - struct args *args = &g_options; - char *endp; +static struct args *parse_args(int argc, char **argv) { + int opt; + int show_help; + struct args *args = &g_options; + char *endp; - show_help = 0; + show_help = 0; - if (argc < 2) - { - show_help = 1; + if (argc < 2) { + show_help = 1; } - memset(args, 0, sizeof(*args)); - args->core = -1; + memset(args, 0, sizeof(*args)); + args->core = -1; - while ((opt = getopt(argc, argv, "h:c:")) != -1) - { - switch (opt) + while ((opt = getopt(argc, argv, "h:c:")) != -1) { + switch (opt) { - case 'c': - args->core = strtol(optarg, &endp, 0); - if (*endp) - { - fprintf(stderr, "Invalid core number \"%s\"\n", optarg); - show_help = 1; - } - break; + case 'c': + args->core = strtol(optarg, &endp, 0); + if (*endp) { + fprintf(stderr, "Invalid core number \"%s\"\n", optarg); + show_help = 1; + } + break; - case 'h': - default: - show_help = 1; + case 'h': + default: + show_help = 1; } } - argc -= optind; - argv += optind; + argc -= optind; + argv += optind; - args->elffile = argv[0]; - args->savename = argv[1]; - argc -= 2; - argv += 2; + args->elffile = argv[0]; + args->savename = argv[1]; + argc -= 2; + argv += 2; - if (argc > 0) - { - args->outputfile = strdup(argv[0]); - } - else - { - show_help = 1; + if (argc > 0) { + args->outputfile = strdup(argv[0]); + } else { + show_help = 1; } - /* Sanity checks for options */ + /* Sanity checks for options */ - if (show_help == 1) - { - fprintf(stderr, - "mkspk [-c ] []\n"); - exit(EXIT_FAILURE); + if (show_help == 1) { + fprintf(stderr, + "mkspk [-c ] []\n"); + exit(EXIT_FAILURE); } - if (args->core < 0) - { - fprintf(stderr, "Core number is not set. Please use -c option.\n"); - exit(EXIT_FAILURE); + if (args->core < 0) { + fprintf(stderr, "Core number is not set. Please use -c option.\n"); + exit(EXIT_FAILURE); } - if (strlen(args->savename) > 63) - { - fprintf(stderr, "savename too long.\n"); - exit(EXIT_FAILURE); + if (strlen(args->savename) > 63) { + fprintf(stderr, "savename too long.\n"); + exit(EXIT_FAILURE); } - return args; + return args; } -static struct elf_file *load_elf(const char *filename) -{ - size_t fsize; - int pos; - char *buf; - FILE *fp; - struct elf_file *ef; - Elf32_Shdr *sh; - uint16_t i; - int ret; +static struct elf_file *load_elf(const char *filename) { + size_t fsize; + int pos; + char *buf; + FILE *fp; + struct elf_file *ef; + Elf32_Shdr *sh; + uint16_t i; + int ret; - fp = fopen(filename, "rb"); - if (!fp) - { - return NULL; + fp = fopen(filename, "rb"); + if (!fp) { + return NULL; } - ef = (struct elf_file *)malloc(sizeof(*ef)); - if (!ef) - { - return NULL; + ef = (struct elf_file *)malloc(sizeof(*ef)); + if (!ef) { + return NULL; } - pos = fseek(fp, 0, SEEK_END); - fsize = (size_t) ftell(fp); - fseek(fp, pos, SEEK_SET); + pos = fseek(fp, 0, SEEK_END); + fsize = (size_t)ftell(fp); + fseek(fp, pos, SEEK_SET); - buf = (char *)malloc(fsize); - if (!buf) - { - return NULL; + buf = (char *)malloc(fsize); + if (!buf) { + return NULL; } - ret = fread(buf, fsize, 1, fp); - fclose(fp); - if (ret != 1) - { - return NULL; + ret = fread(buf, fsize, 1, fp); + fclose(fp); + if (ret != 1) { + return NULL; } - ef->data = buf; + ef->data = buf; - ef->ehdr = (Elf32_Ehdr *) buf; + ef->ehdr = (Elf32_Ehdr *)buf; - Elf32_Ehdr *h = (Elf32_Ehdr *) buf; + Elf32_Ehdr *h = (Elf32_Ehdr *)buf; - if (!(h->e_ident[EI_MAG0] == 0x7f && - h->e_ident[EI_MAG1] == 'E' && - h->e_ident[EI_MAG2] == 'L' && h->e_ident[EI_MAG3] == 'F')) - { - free(ef); - free(buf); - return NULL; + if (!(h->e_ident[EI_MAG0] == 0x7f && + h->e_ident[EI_MAG1] == 'E' && + h->e_ident[EI_MAG2] == 'L' && h->e_ident[EI_MAG3] == 'F')) { + free(ef); + free(buf); + return NULL; } - ef->phdr = (Elf32_Phdr *) (buf + ef->ehdr->e_phoff); - ef->shdr = (Elf32_Shdr *) (buf + ef->ehdr->e_shoff); - ef->shstring = buf + ef->shdr[ef->ehdr->e_shstrndx].sh_offset; + ef->phdr = (Elf32_Phdr *)(buf + ef->ehdr->e_phoff); + ef->shdr = (Elf32_Shdr *)(buf + ef->ehdr->e_shoff); + ef->shstring = buf + ef->shdr[ef->ehdr->e_shstrndx].sh_offset; - for (i = 0, sh = ef->shdr; i < ef->ehdr->e_shnum; i++, sh++) + for (i = 0, sh = ef->shdr; i < ef->ehdr->e_shnum; i++, sh++) { - if (sh->sh_type == SHT_SYMTAB) - { - ef->symtab = (Elf32_Sym *) (buf + sh->sh_offset); - ef->nsyms = sh->sh_size / sh->sh_entsize; - continue; + if (sh->sh_type == SHT_SYMTAB) { + ef->symtab = (Elf32_Sym *)(buf + sh->sh_offset); + ef->nsyms = sh->sh_size / sh->sh_entsize; + continue; } - if (sh->sh_type == SHT_STRTAB) - { - if (!strcmp(".strtab", ef->shstring + sh->sh_name)) - { - ef->string = buf + sh->sh_offset; + if (sh->sh_type == SHT_STRTAB) { + if (!strcmp(".strtab", ef->shstring + sh->sh_name)) { + ef->string = buf + sh->sh_offset; } } } - return ef; + return ef; } static void *create_image(struct elf_file *elf, int core, char *savename, - int *image_size) -{ - char *img; - struct spk_header *header; - struct spk_prog_info *pi; - Elf32_Phdr *ph; - Elf32_Sym *sym; - char *name; - int snlen; - int nphs, psize, imgsize; - int i; - int j; - uint32_t offset; - uint32_t sp; + int *image_size) { + char *img; + struct spk_header *header; + struct spk_prog_info *pi; + Elf32_Phdr *ph; + Elf32_Sym *sym; + char *name; + int snlen; + int nphs, psize, imgsize; + int i; + int j; + uint32_t offset; + uint32_t sp; - snlen = alignup(strlen(savename) + 1, 16); + snlen = alignup(strlen(savename) + 1, 16); - nphs = 0; - psize = 0; - for (i = 0, ph = elf->phdr; i < elf->ehdr->e_phnum; i++, ph++) + nphs = 0; + psize = 0; + for (i = 0, ph = elf->phdr; i < elf->ehdr->e_phnum; i++, ph++) { - if (ph->p_type != PT_LOAD || ph->p_filesz == 0) - { - continue; + if (ph->p_type != PT_LOAD || ph->p_filesz == 0) { + continue; } - nphs++; - psize += alignup(ph->p_filesz, 16); + nphs++; + psize += alignup(ph->p_filesz, 16); } - imgsize = sizeof(*header) + snlen + (nphs * 16) + psize; + imgsize = sizeof(*header) + snlen + (nphs * 16) + psize; - img = (char *)malloc(imgsize + 32); - if (!img) - { - return NULL; + img = (char *)malloc(imgsize + 32); + if (!img) { + return NULL; } - *image_size = imgsize; - sym = elf->symtab; - name = elf->string; - sp = 0; + *image_size = imgsize; + sym = elf->symtab; + name = elf->string; + sp = 0; - for (j = 0; j < elf->nsyms; j++, sym++) + for (j = 0; j < elf->nsyms; j++, sym++) { - if (!strcmp("__stack", name + sym->st_name)) - { - sp = sym->st_value; + if (!strcmp("__stack", name + sym->st_name)) { + sp = sym->st_value; } } - memset(img, 0, imgsize); + memset(img, 0, imgsize); - header = (struct spk_header *)img; - header->magic[0] = 0xef; - header->magic[1] = 'M'; - header->magic[2] = 'O'; - header->magic[3] = 'D'; - header->cpu = core; + header = (struct spk_header *)img; + header->magic[0] = 0xef; + header->magic[1] = 'M'; + header->magic[2] = 'O'; + header->magic[3] = 'D'; + header->cpu = core; - header->entry = elf->ehdr->e_entry; - header->stack = sp; - header->core = core; + header->entry = elf->ehdr->e_entry; + header->stack = sp; + header->core = core; - header->binaries = nphs; - header->phoffs = sizeof(*header) + snlen; - header->mode = 0777; + header->binaries = nphs; + header->phoffs = sizeof(*header) + snlen; + header->mode = 0777; - strncpy(img + sizeof(*header), savename, 63); + strncpy(img + sizeof(*header), savename, 63); - ph = elf->phdr; - pi = (struct spk_prog_info *)(img + header->phoffs); - offset = ((char *)pi - img) + (nphs * sizeof(*pi)); - for (i = 0; i < elf->ehdr->e_phnum; i++, ph++) + ph = elf->phdr; + pi = (struct spk_prog_info *)(img + header->phoffs); + offset = ((char *)pi - img) + (nphs * sizeof(*pi)); + for (i = 0; i < elf->ehdr->e_phnum; i++, ph++) { - if (ph->p_type != PT_LOAD || ph->p_filesz == 0) - continue; - pi->load_address = ph->p_paddr; - pi->offset = offset; - pi->size = alignup(ph->p_filesz, 16); /* need 16 bytes align for + if (ph->p_type != PT_LOAD || ph->p_filesz == 0) { + continue; + } + pi->load_address = ph->p_paddr; + pi->offset = offset; + pi->size = alignup(ph->p_filesz, 16); /* need 16 bytes align for * decryption */ - pi->memsize = ph->p_memsz; + pi->memsize = ph->p_memsz; - memcpy(img + pi->offset, elf->data + ph->p_offset, ph->p_filesz); + memcpy(img + pi->offset, elf->data + ph->p_offset, ph->p_filesz); - offset += alignup(ph->p_filesz, 16); - pi++; + offset += alignup(ph->p_filesz, 16); + pi++; } - return img; + return img; } /**************************************************************************** * Public Functions ****************************************************************************/ -int main(int argc, char **argv) -{ - struct args *args; - struct elf_file *elf; - struct cipher *c; - uint8_t *spkimage; - int size = 0; - FILE *fp; - char footer[16]; +int main(int argc, char **argv) { + struct args *args; + struct elf_file *elf; + struct cipher *c; + uint8_t *spkimage; + int size = 0; + FILE *fp; + char footer[16]; - args = parse_args(argc, argv); + args = parse_args(argc, argv); - elf = load_elf(args->elffile); - if (!elf) - { - fprintf(stderr, "Loading ELF %s failure.\n", args->elffile); - exit(EXIT_FAILURE); + elf = load_elf(args->elffile); + if (!elf) { + fprintf(stderr, "Loading ELF %s failure.\n", args->elffile); + exit(EXIT_FAILURE); } - spkimage = create_image(elf, args->core, args->savename, &size); - free(elf); + spkimage = create_image(elf, args->core, args->savename, &size); + free(elf); - c = cipher_init(vmk, NULL); - cipher_calc_cmac(c, spkimage, size, (uint8_t *) spkimage + size); - cipher_deinit(c); + c = cipher_init(vmk, NULL); + cipher_calc_cmac(c, spkimage, size, (uint8_t *)spkimage + size); + cipher_deinit(c); - size += 16; /* Extend CMAC size */ + size += 16; /* Extend CMAC size */ - snprintf(footer, 16, "MKSPK_BN_HOOTER"); - footer[15] = '\0'; + snprintf(footer, 16, "MKSPK_BN_HOOTER"); + footer[15] = '\0'; - fp = fopen(args->outputfile, "wb"); - if (!fp) - { - fprintf(stderr, "Output file open error.\n"); - free(spkimage); - exit(EXIT_FAILURE); + fp = fopen(args->outputfile, "wb"); + if (!fp) { + fprintf(stderr, "Output file open error.\n"); + free(spkimage); + exit(EXIT_FAILURE); } - fwrite(spkimage, size, 1, fp); - fwrite(footer, 16, 1, fp); + fwrite(spkimage, size, 1, fp); + fwrite(footer, 16, 1, fp); - fclose(fp); + fclose(fp); - printf("File %s is successfully created.\n", args->outputfile); - free(args->outputfile); + printf("File %s is successfully created.\n", args->outputfile); + free(args->outputfile); - memset(spkimage, 0, size); - free(spkimage); + memset(spkimage, 0, size); + free(spkimage); - exit(EXIT_SUCCESS); + exit(EXIT_SUCCESS); } diff --git a/ports/cxd56/mkspk/mkspk.h b/ports/cxd56/mkspk/mkspk.h index 5c1b979c04..8cdac1185a 100644 --- a/ports/cxd56/mkspk/mkspk.h +++ b/ports/cxd56/mkspk/mkspk.h @@ -60,7 +60,7 @@ ****************************************************************************/ struct spk_header - { +{ uint8_t magic[4]; uint8_t cpu; uint8_t reserved[11]; @@ -70,18 +70,18 @@ struct spk_header uint16_t binaries; uint16_t phoffs; uint16_t mode; - }; +}; struct spk_prog_info - { +{ uint32_t load_address; uint32_t offset; uint32_t size; uint32_t memsize; - }; +}; struct elf_file - { +{ Elf32_Ehdr *ehdr; Elf32_Phdr *phdr; Elf32_Shdr *shdr; @@ -90,4 +90,4 @@ struct elf_file char *shstring; char *string; char *data; - }; +}; diff --git a/ports/cxd56/mphalport.h b/ports/cxd56/mphalport.h index 50e805cf50..ba5ca39b97 100644 --- a/ports/cxd56/mphalport.h +++ b/ports/cxd56/mphalport.h @@ -32,6 +32,6 @@ #include "lib/utils/interrupt_char.h" #include "supervisor/shared/tick.h" -#define mp_hal_ticks_ms() ((mp_uint_t) supervisor_ticks_ms32()) +#define mp_hal_ticks_ms() ((mp_uint_t)supervisor_ticks_ms32()) #endif // MICROPY_INCLUDED_CXD56_MPHALPORT_H diff --git a/ports/cxd56/supervisor/port.c b/ports/cxd56/supervisor/port.c index 523d6a496b..fa7591918d 100644 --- a/ports/cxd56/supervisor/port.c +++ b/ports/cxd56/supervisor/port.c @@ -48,14 +48,16 @@ #define SPRESENSE_MEM_ALIGN (32) -uint32_t* heap; +uint32_t *heap; uint32_t heap_size; safe_mode_t port_init(void) { boardctl(BOARDIOC_INIT, 0); // Wait until RTC is available - while (g_rtc_enabled == false); + while (g_rtc_enabled == false) { + ; + } heap = memalign(SPRESENSE_MEM_ALIGN, 128 * 1024); uint32_t size = CONFIG_RAM_START + CONFIG_RAM_SIZE - (uint32_t)heap - 2 * SPRESENSE_MEM_ALIGN; @@ -76,18 +78,18 @@ void reset_cpu(void) { } void reset_port(void) { -#if CIRCUITPY_ANALOGIO + #if CIRCUITPY_ANALOGIO analogin_reset(); -#endif -#if CIRCUITPY_PULSEIO + #endif + #if CIRCUITPY_PULSEIO pulseout_reset(); -#endif -#if CIRCUITPY_PWMIO + #endif + #if CIRCUITPY_PWMIO pwmout_reset(); -#endif -#if CIRCUITPY_BUSIO + #endif + #if CIRCUITPY_BUSIO busio_uart_reset(); -#endif + #endif reset_all_pins(); } @@ -134,13 +136,12 @@ uint32_t port_get_saved_word(void) { } static background_callback_t callback; -static void usb_background_do(void* unused) { +static void usb_background_do(void *unused) { usb_background(); } volatile bool _tick_enabled; -void board_timerhook(void) -{ +void board_timerhook(void) { // Do things common to all ports when the tick occurs if (_tick_enabled) { supervisor_tick(); @@ -149,7 +150,7 @@ void board_timerhook(void) background_callback_add(&callback, usb_background_do, NULL); } -uint64_t port_get_raw_ticks(uint8_t* subticks) { +uint64_t port_get_raw_ticks(uint8_t *subticks) { uint64_t count = cxd56_rtc_count(); *subticks = count % 32; diff --git a/ports/cxd56/tools/flash_writer.py b/ports/cxd56/tools/flash_writer.py index 840f10c32f..a61342e3ea 100755 --- a/ports/cxd56/tools/flash_writer.py +++ b/ports/cxd56/tools/flash_writer.py @@ -49,17 +49,17 @@ import_serial_module = True # When SDK release, plase set SDK_RELEASE as True. SDK_RELEASE = False -if SDK_RELEASE : - PRINT_RAW_COMMAND = False - REBOOT_AT_END = True -else : - PRINT_RAW_COMMAND = True - REBOOT_AT_END = True +if SDK_RELEASE: + PRINT_RAW_COMMAND = False + REBOOT_AT_END = True +else: + PRINT_RAW_COMMAND = True + REBOOT_AT_END = True try: - import serial + import serial except: - import_serial_module = False + import_serial_module = False # supported environment various # CXD56_PORT @@ -73,508 +73,599 @@ MAX_DOT_COUNT = 70 # configure parameters and default value class ConfigArgs: - PROTOCOL_TYPE = None - SERIAL_PORT = "COM1" - SERVER_PORT = 4569 - SERVER_IP = "localhost" - EOL = bytes([10]) - WAIT_RESET = True - AUTO_RESET = False - DTR_RESET = False - XMODEM_BAUD = 0 - NO_SET_BOOTABLE = False - PACKAGE_NAME = [] - FILE_NAME = [] - ERASE_NAME = [] - PKGSYS_NAME = [] - PKGAPP_NAME = [] - PKGUPD_NAME = [] + PROTOCOL_TYPE = None + SERIAL_PORT = "COM1" + SERVER_PORT = 4569 + SERVER_IP = "localhost" + EOL = bytes([10]) + WAIT_RESET = True + AUTO_RESET = False + DTR_RESET = False + XMODEM_BAUD = 0 + NO_SET_BOOTABLE = False + PACKAGE_NAME = [] + FILE_NAME = [] + ERASE_NAME = [] + PKGSYS_NAME = [] + PKGAPP_NAME = [] + PKGUPD_NAME = [] + ROM_MSG = [b"Welcome to nash"] XMDM_MSG = "Waiting for XMODEM (CRC or 1K) transfer. Ctrl-X to cancel." -class ConfigArgsLoader(): - def __init__(self): - self.parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) - self.parser.add_argument("package_name", help="the name of the package to install", nargs='*') - self.parser.add_argument("-f", "--file", dest="file_name", help="save file", action='append') - self.parser.add_argument("-e", "--erase", dest="erase_name", help="erase file", action='append') - self.parser.add_argument("-S", "--sys", dest="pkgsys_name", help="the name of the system package to install", action='append') - self.parser.add_argument("-A", "--app", dest="pkgapp_name", help="the name of the application package to install", action='append') - self.parser.add_argument("-U", "--upd", dest="pkgupd_name", help="the name of the updater package to install", action='append') +class ConfigArgsLoader: + def __init__(self): + self.parser = argparse.ArgumentParser(formatter_class=argparse.RawTextHelpFormatter) + self.parser.add_argument( + "package_name", help="the name of the package to install", nargs="*" + ) + self.parser.add_argument( + "-f", "--file", dest="file_name", help="save file", action="append" + ) + self.parser.add_argument( + "-e", "--erase", dest="erase_name", help="erase file", action="append" + ) - self.parser.add_argument("-a", "--auto-reset", dest="auto_reset", - action="store_true", default=None, - help="try to auto reset develop board if possible") - self.parser.add_argument("-d", "--dtr-reset", dest="dtr_reset", - action="store_true", default=None, - help="try to auto reset develop board if possible") - self.parser.add_argument("-n", "--no-set-bootable", dest="no_set_bootable", - action="store_true", default=None, - help="not to set bootable") + self.parser.add_argument( + "-S", + "--sys", + dest="pkgsys_name", + help="the name of the system package to install", + action="append", + ) + self.parser.add_argument( + "-A", + "--app", + dest="pkgapp_name", + help="the name of the application package to install", + action="append", + ) + self.parser.add_argument( + "-U", + "--upd", + dest="pkgupd_name", + help="the name of the updater package to install", + action="append", + ) - group = self.parser.add_argument_group() - group.add_argument("-i", "--server-ip", dest="server_ip", - help="the ip address connected to the telnet server") - group.add_argument("-p", "--server-port", dest="server_port", type=int, - help="the port connected to the telnet server") + self.parser.add_argument( + "-a", + "--auto-reset", + dest="auto_reset", + action="store_true", + default=None, + help="try to auto reset develop board if possible", + ) + self.parser.add_argument( + "-d", + "--dtr-reset", + dest="dtr_reset", + action="store_true", + default=None, + help="try to auto reset develop board if possible", + ) + self.parser.add_argument( + "-n", + "--no-set-bootable", + dest="no_set_bootable", + action="store_true", + default=None, + help="not to set bootable", + ) - group = self.parser.add_argument_group() - group.add_argument("-c", "--serial-port", dest="serial_port", help="the serial port") - group.add_argument("-b", "--xmodem-baudrate", dest="xmodem_baud", help="Use the faster baudrate in xmodem") + group = self.parser.add_argument_group() + group.add_argument( + "-i", + "--server-ip", + dest="server_ip", + help="the ip address connected to the telnet server", + ) + group.add_argument( + "-p", + "--server-port", + dest="server_port", + type=int, + help="the port connected to the telnet server", + ) - mutually_group = self.parser.add_mutually_exclusive_group() - mutually_group.add_argument("-t", "--telnet-protocol", dest="telnet_protocol", - action="store_true", default=None, - help="use the telnet protocol for binary transmission") - mutually_group.add_argument("-s", "--serial-protocol", dest="serial_protocol", - action="store_true", default=None, - help="use the serial port for binary transmission, default options") + group = self.parser.add_argument_group() + group.add_argument("-c", "--serial-port", dest="serial_port", help="the serial port") + group.add_argument( + "-b", "--xmodem-baudrate", dest="xmodem_baud", help="Use the faster baudrate in xmodem" + ) - mutually_group2 = self.parser.add_mutually_exclusive_group() - mutually_group2.add_argument("-F", "--force-wait-reset", dest="wait_reset", - action="store_true", default=None, - help="force wait for pressing RESET button") - mutually_group2.add_argument("-N", "--no-wait-reset", dest="wait_reset", - action="store_false", default=None, - help="if possible, skip to wait for pressing RESET button") + mutually_group = self.parser.add_mutually_exclusive_group() + mutually_group.add_argument( + "-t", + "--telnet-protocol", + dest="telnet_protocol", + action="store_true", + default=None, + help="use the telnet protocol for binary transmission", + ) + mutually_group.add_argument( + "-s", + "--serial-protocol", + dest="serial_protocol", + action="store_true", + default=None, + help="use the serial port for binary transmission, default options", + ) - def update_config(self): - args = self.parser.parse_args() + mutually_group2 = self.parser.add_mutually_exclusive_group() + mutually_group2.add_argument( + "-F", + "--force-wait-reset", + dest="wait_reset", + action="store_true", + default=None, + help="force wait for pressing RESET button", + ) + mutually_group2.add_argument( + "-N", + "--no-wait-reset", + dest="wait_reset", + action="store_false", + default=None, + help="if possible, skip to wait for pressing RESET button", + ) - ConfigArgs.PACKAGE_NAME = args.package_name - ConfigArgs.FILE_NAME = args.file_name - ConfigArgs.ERASE_NAME = args.erase_name - ConfigArgs.PKGSYS_NAME = args.pkgsys_name - ConfigArgs.PKGAPP_NAME = args.pkgapp_name - ConfigArgs.PKGUPD_NAME = args.pkgupd_name + def update_config(self): + args = self.parser.parse_args() - # Get serial port or telnet server ip etc - if args.serial_protocol == True: - ConfigArgs.PROTOCOL_TYPE = PROTOCOL_SERIAL - elif args.telnet_protocol == True: - ConfigArgs.PROTOCOL_TYPE = PROTOCOL_TELNET + ConfigArgs.PACKAGE_NAME = args.package_name + ConfigArgs.FILE_NAME = args.file_name + ConfigArgs.ERASE_NAME = args.erase_name + ConfigArgs.PKGSYS_NAME = args.pkgsys_name + ConfigArgs.PKGAPP_NAME = args.pkgapp_name + ConfigArgs.PKGUPD_NAME = args.pkgupd_name - if ConfigArgs.PROTOCOL_TYPE == None: - proto = os.environ.get("CXD56_PROTOCOL") - if proto is not None: - if 's' in proto: - ConfigArgs.PROTOCOL_TYPE = PROTOCOL_SERIAL - elif 't' in proto: - ConfigArgs.PROTOCOL_TYPE = PROTOCOL_TELNET + # Get serial port or telnet server ip etc + if args.serial_protocol == True: + ConfigArgs.PROTOCOL_TYPE = PROTOCOL_SERIAL + elif args.telnet_protocol == True: + ConfigArgs.PROTOCOL_TYPE = PROTOCOL_TELNET - if ConfigArgs.PROTOCOL_TYPE == None: - ConfigArgs.PROTOCOL_TYPE = PROTOCOL_SERIAL + if ConfigArgs.PROTOCOL_TYPE == None: + proto = os.environ.get("CXD56_PROTOCOL") + if proto is not None: + if "s" in proto: + ConfigArgs.PROTOCOL_TYPE = PROTOCOL_SERIAL + elif "t" in proto: + ConfigArgs.PROTOCOL_TYPE = PROTOCOL_TELNET - if ConfigArgs.PROTOCOL_TYPE == PROTOCOL_SERIAL: - if args.serial_port is not None: - ConfigArgs.SERIAL_PORT = args.serial_port - else: - # Get serial port from the environment - port = os.environ.get("CXD56_PORT") - if port is not None: - ConfigArgs.SERIAL_PORT = port - else: - print("CXD56_PORT is not set, Use " + ConfigArgs.SERIAL_PORT + ".") - else: - ConfigArgs.PROTOCOL_TYPE = PROTOCOL_TELNET - if args.server_port is not None: - ConfigArgs.SERVER_PORT = args.server_port - else: - port = os.environ.get("CXD56_TELNETSRV_PORT") - if port is not None: - ConfigArgs.SERVER_PORT = port - else: - print("CXD56_TELNETSRV_PORT is not set, Use " + str(ConfigArgs.SERVER_PORT) + ".") - if args.server_ip is not None: - ConfigArgs.SERVER_IP = args.server_ip - else: - ip = os.environ.get("CXD56_TELNETSRV_IP") - if ip is not None: - ConfigArgs.SERVER_IP = ip - else: - print("CXD56_TELNETSRV_IP is not set, Use " + ConfigArgs.SERVER_IP + ".") + if ConfigArgs.PROTOCOL_TYPE == None: + ConfigArgs.PROTOCOL_TYPE = PROTOCOL_SERIAL - if args.xmodem_baud is not None: - ConfigArgs.XMODEM_BAUD = args.xmodem_baud + if ConfigArgs.PROTOCOL_TYPE == PROTOCOL_SERIAL: + if args.serial_port is not None: + ConfigArgs.SERIAL_PORT = args.serial_port + else: + # Get serial port from the environment + port = os.environ.get("CXD56_PORT") + if port is not None: + ConfigArgs.SERIAL_PORT = port + else: + print("CXD56_PORT is not set, Use " + ConfigArgs.SERIAL_PORT + ".") + else: + ConfigArgs.PROTOCOL_TYPE = PROTOCOL_TELNET + if args.server_port is not None: + ConfigArgs.SERVER_PORT = args.server_port + else: + port = os.environ.get("CXD56_TELNETSRV_PORT") + if port is not None: + ConfigArgs.SERVER_PORT = port + else: + print( + "CXD56_TELNETSRV_PORT is not set, Use " + str(ConfigArgs.SERVER_PORT) + "." + ) + if args.server_ip is not None: + ConfigArgs.SERVER_IP = args.server_ip + else: + ip = os.environ.get("CXD56_TELNETSRV_IP") + if ip is not None: + ConfigArgs.SERVER_IP = ip + else: + print("CXD56_TELNETSRV_IP is not set, Use " + ConfigArgs.SERVER_IP + ".") - if args.auto_reset is not None: - ConfigArgs.AUTO_RESET = args.auto_reset + if args.xmodem_baud is not None: + ConfigArgs.XMODEM_BAUD = args.xmodem_baud - if args.dtr_reset is not None: - ConfigArgs.DTR_RESET = args.dtr_reset + if args.auto_reset is not None: + ConfigArgs.AUTO_RESET = args.auto_reset - if args.no_set_bootable is not None: - ConfigArgs.NO_SET_BOOTABLE = args.no_set_bootable + if args.dtr_reset is not None: + ConfigArgs.DTR_RESET = args.dtr_reset + + if args.no_set_bootable is not None: + ConfigArgs.NO_SET_BOOTABLE = args.no_set_bootable + + if args.wait_reset is not None: + ConfigArgs.WAIT_RESET = args.wait_reset - if args.wait_reset is not None: - ConfigArgs.WAIT_RESET = args.wait_reset class TelnetDev: - def __init__(self): - srv_ipaddr = ConfigArgs.SERVER_IP - srv_port = ConfigArgs.SERVER_PORT - self.recvbuf = b''; - try: - self.telnet = telnetlib.Telnet(host=srv_ipaddr, port=srv_port, timeout=10) - # There is a ack to be sent after connecting to the telnet server. - self.telnet.write(b"\xff") - except Exception as e: - print("Cannot connect to the server %s:%d" % (srv_ipaddr, srv_port)) - sys.exit(e.args[0]) + def __init__(self): + srv_ipaddr = ConfigArgs.SERVER_IP + srv_port = ConfigArgs.SERVER_PORT + self.recvbuf = b"" + try: + self.telnet = telnetlib.Telnet(host=srv_ipaddr, port=srv_port, timeout=10) + # There is a ack to be sent after connecting to the telnet server. + self.telnet.write(b"\xff") + except Exception as e: + print("Cannot connect to the server %s:%d" % (srv_ipaddr, srv_port)) + sys.exit(e.args[0]) - def readline(self, size=None): - res = b'' - ch = b'' - while ch != ConfigArgs.EOL: - ch = self.getc_raw(1, timeout=0.1) - if ch == b'': - return res - res += ch - return res + def readline(self, size=None): + res = b"" + ch = b"" + while ch != ConfigArgs.EOL: + ch = self.getc_raw(1, timeout=0.1) + if ch == b"": + return res + res += ch + return res - def getc_raw(self, size, timeout=1): - res = b'' - tm = time.monotonic() - while size > 0: - while self.recvbuf == b'': - self.recvbuf = self.telnet.read_eager() - if self.recvbuf == b'': - if (time.monotonic() - tm) > timeout: - return res - time.sleep(0.1) - res += self.recvbuf[0:1] - self.recvbuf = self.recvbuf[1:] - size -= 1 - return res + def getc_raw(self, size, timeout=1): + res = b"" + tm = time.monotonic() + while size > 0: + while self.recvbuf == b"": + self.recvbuf = self.telnet.read_eager() + if self.recvbuf == b"": + if (time.monotonic() - tm) > timeout: + return res + time.sleep(0.1) + res += self.recvbuf[0:1] + self.recvbuf = self.recvbuf[1:] + size -= 1 + return res - def write(self, buffer): - self.telnet.write(buffer) + def write(self, buffer): + self.telnet.write(buffer) - def discard_inputs(self, timeout=1.0): - while True: - ch = self.getc_raw(1, timeout=timeout) - if ch == b'': - break + def discard_inputs(self, timeout=1.0): + while True: + ch = self.getc_raw(1, timeout=timeout) + if ch == b"": + break - def getc(self, size, timeout=1): - c = self.getc_raw(size, timeout) - return c + def getc(self, size, timeout=1): + c = self.getc_raw(size, timeout) + return c - def putc(self, buffer, timeout=1): - self.telnet.write(buffer) - self.show_progress(len(buffer)) + def putc(self, buffer, timeout=1): + self.telnet.write(buffer) + self.show_progress(len(buffer)) - def reboot(self): - # no-op - pass + def reboot(self): + # no-op + pass - def set_file_size(self, filesize): - self.bytes_transfered = 0 - self.filesize = filesize - self.count = 0 + def set_file_size(self, filesize): + self.bytes_transfered = 0 + self.filesize = filesize + self.count = 0 + + def show_progress(self, sendsize): + if PRINT_RAW_COMMAND: + if self.count < MAX_DOT_COUNT: + self.bytes_transfered = self.bytes_transfered + sendsize + cur_count = int(self.bytes_transfered * MAX_DOT_COUNT / self.filesize) + if MAX_DOT_COUNT < cur_count: + cur_count = MAX_DOT_COUNT + for idx in range(cur_count - self.count): + print("#", end="") + sys.stdout.flush() + self.count = cur_count + if self.count == MAX_DOT_COUNT: + print("\n") - def show_progress(self, sendsize): - if PRINT_RAW_COMMAND: - if self.count < MAX_DOT_COUNT: - self.bytes_transfered = self.bytes_transfered + sendsize - cur_count = int(self.bytes_transfered * MAX_DOT_COUNT / self.filesize) - if MAX_DOT_COUNT < cur_count: - cur_count = MAX_DOT_COUNT - for idx in range(cur_count - self.count): - print('#',end='') - sys.stdout.flush() - self.count = cur_count - if self.count == MAX_DOT_COUNT: - print("\n") class SerialDev: - def __init__(self): - if import_serial_module is False: - print("Cannot import serial module, maybe it's not install yet.") - print("\n", end="") - print("Please install python-setuptool by Cygwin installer.") - print("After that use easy_intall command to install serial module") - print(" $ cd tool/") - print(" $ python3 -m easy_install pyserial-2.7.tar.gz") - quit() - else: - port = ConfigArgs.SERIAL_PORT - try: - self.serial = serial.Serial(port, baudrate=115200, - parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, - bytesize=serial.EIGHTBITS, timeout=0.1) - except Exception as e: - print("Cannot open port : " + port) - sys.exit(e.args[0]) + def __init__(self): + if import_serial_module is False: + print("Cannot import serial module, maybe it's not install yet.") + print("\n", end="") + print("Please install python-setuptool by Cygwin installer.") + print("After that use easy_intall command to install serial module") + print(" $ cd tool/") + print(" $ python3 -m easy_install pyserial-2.7.tar.gz") + quit() + else: + port = ConfigArgs.SERIAL_PORT + try: + self.serial = serial.Serial( + port, + baudrate=115200, + parity=serial.PARITY_NONE, + stopbits=serial.STOPBITS_ONE, + bytesize=serial.EIGHTBITS, + timeout=0.1, + ) + except Exception as e: + print("Cannot open port : " + port) + sys.exit(e.args[0]) - def readline(self, size=None): - return self.serial.readline(size) + def readline(self, size=None): + return self.serial.readline(size) - def write(self, buffer): - self.serial.write(buffer) - self.serial.flush() + def write(self, buffer): + self.serial.write(buffer) + self.serial.flush() - def discard_inputs(self, timeout=1.0): - time.sleep(timeout) - self.serial.flushInput() + def discard_inputs(self, timeout=1.0): + time.sleep(timeout) + self.serial.flushInput() - def getc(self, size, timeout=1): - self.serial.timeout = timeout - c = self.serial.read(size) - self.serial.timeout = 0.1 - return c + def getc(self, size, timeout=1): + self.serial.timeout = timeout + c = self.serial.read(size) + self.serial.timeout = 0.1 + return c - def putc(self, buffer, timeout=1): - self.serial.timeout = timeout - self.serial.write(buffer) - self.serial.flush() - self.serial.timeout = 0.1 - self.show_progress(len(buffer)) + def putc(self, buffer, timeout=1): + self.serial.timeout = timeout + self.serial.write(buffer) + self.serial.flush() + self.serial.timeout = 0.1 + self.show_progress(len(buffer)) - # Note: windows platform dependent code - def putc_win(self, buffer, timeout=1): - self.serial.write(buffer) - self.show_progress(len(buffer)) - while True: - if self.serial.out_waiting == 0: - break + # Note: windows platform dependent code + def putc_win(self, buffer, timeout=1): + self.serial.write(buffer) + self.show_progress(len(buffer)) + while True: + if self.serial.out_waiting == 0: + break - def setBaudrate(self, baudrate): -# self.serial.setBaudrate(baudrate) - self.serial.baudrate = baudrate + def setBaudrate(self, baudrate): + # self.serial.setBaudrate(baudrate) + self.serial.baudrate = baudrate - def reboot(self): - # Target Reset by DTR - self.serial.setDTR(False) - self.serial.setDTR(True) - self.serial.setDTR(False) + def reboot(self): + # Target Reset by DTR + self.serial.setDTR(False) + self.serial.setDTR(True) + self.serial.setDTR(False) - def set_file_size(self, filesize): - self.bytes_transfered = 0 - self.filesize = filesize - self.count = 0 + def set_file_size(self, filesize): + self.bytes_transfered = 0 + self.filesize = filesize + self.count = 0 + + def show_progress(self, sendsize): + if PRINT_RAW_COMMAND: + if self.count < MAX_DOT_COUNT: + self.bytes_transfered = self.bytes_transfered + sendsize + cur_count = int(self.bytes_transfered * MAX_DOT_COUNT / self.filesize) + if MAX_DOT_COUNT < cur_count: + cur_count = MAX_DOT_COUNT + for idx in range(cur_count - self.count): + print("#", end="") + sys.stdout.flush() + self.count = cur_count + if self.count == MAX_DOT_COUNT: + print("\n") - def show_progress(self, sendsize): - if PRINT_RAW_COMMAND: - if self.count < MAX_DOT_COUNT: - self.bytes_transfered = self.bytes_transfered + sendsize - cur_count = int(self.bytes_transfered * MAX_DOT_COUNT / self.filesize) - if MAX_DOT_COUNT < cur_count: - cur_count = MAX_DOT_COUNT - for idx in range(cur_count - self.count): - print('#',end='') - sys.stdout.flush() - self.count = cur_count - if self.count == MAX_DOT_COUNT: - print("\n") class FlashWriter: - def __init__(self, protocol_sel=PROTOCOL_SERIAL): - if protocol_sel == PROTOCOL_TELNET: - self.serial = TelnetDev() - else: - self.serial = SerialDev() + def __init__(self, protocol_sel=PROTOCOL_SERIAL): + if protocol_sel == PROTOCOL_TELNET: + self.serial = TelnetDev() + else: + self.serial = SerialDev() - def cancel_autoboot(self) : - boot_msg = '' - self.serial.reboot() # Target reboot before send 'r' - while boot_msg == '' : - rx = self.serial.readline().strip() - self.serial.write(b"r") # Send "r" key to avoid auto boot - for msg in ROM_MSG : - if msg in rx : - boot_msg = msg - break - while True : - rx = self.serial.readline().decode(errors="replace").strip() - if "updater" in rx : - # Workaround : Sometime first character is dropped. - # Send line feed as air shot before actual command. - self.serial.write(b"\n") # Send line feed - self.serial.discard_inputs()# Clear input buffer to sync - return boot_msg.decode(errors="ignore") + def cancel_autoboot(self): + boot_msg = "" + self.serial.reboot() # Target reboot before send 'r' + while boot_msg == "": + rx = self.serial.readline().strip() + self.serial.write(b"r") # Send "r" key to avoid auto boot + for msg in ROM_MSG: + if msg in rx: + boot_msg = msg + break + while True: + rx = self.serial.readline().decode(errors="replace").strip() + if "updater" in rx: + # Workaround : Sometime first character is dropped. + # Send line feed as air shot before actual command. + self.serial.write(b"\n") # Send line feed + self.serial.discard_inputs() # Clear input buffer to sync + return boot_msg.decode(errors="ignore") - def recv(self): - rx = self.serial.readline() - if PRINT_RAW_COMMAND : - serial_line = rx.decode(errors="replace") - if serial_line.strip() != "" and not serial_line.startswith(XMDM_MSG): - print(serial_line, end="") - return rx + def recv(self): + rx = self.serial.readline() + if PRINT_RAW_COMMAND: + serial_line = rx.decode(errors="replace") + if serial_line.strip() != "" and not serial_line.startswith(XMDM_MSG): + print(serial_line, end="") + return rx - def wait(self, string): - while True: - rx = self.recv() - if string.encode() in rx: - time.sleep(0.1) - break + def wait(self, string): + while True: + rx = self.recv() + if string.encode() in rx: + time.sleep(0.1) + break - def wait_for_prompt(self): - prompt_pat = re.compile(b"updater") - while True: - rx = self.recv() - if prompt_pat.search(rx): - time.sleep(0.1) - break + def wait_for_prompt(self): + prompt_pat = re.compile(b"updater") + while True: + rx = self.recv() + if prompt_pat.search(rx): + time.sleep(0.1) + break - def send(self, string): - self.serial.write(str(string).encode() + b"\n") - rx = self.serial.readline() - if PRINT_RAW_COMMAND : - print(rx.decode(errors="replace"), end="") + def send(self, string): + self.serial.write(str(string).encode() + b"\n") + rx = self.serial.readline() + if PRINT_RAW_COMMAND: + print(rx.decode(errors="replace"), end="") - def read_output(self, prompt_text) : - output = [] - while True : - rx = self.serial.readline() - if prompt_text.encode() in rx : - time.sleep(0.1) - break - if rx != "" : - output.append(rx.decode(errors="ignore").rstrip()) - return output + def read_output(self, prompt_text): + output = [] + while True: + rx = self.serial.readline() + if prompt_text.encode() in rx: + time.sleep(0.1) + break + if rx != "": + output.append(rx.decode(errors="ignore").rstrip()) + return output - def install_files(self, files, command) : - if ConfigArgs.XMODEM_BAUD: - command += " -b " + ConfigArgs.XMODEM_BAUD - if os.name == 'nt': - modem = xmodem.XMODEM(self.serial.getc, self.serial.putc_win, 'xmodem1k') - else: - modem = xmodem.XMODEM(self.serial.getc, self.serial.putc, 'xmodem1k') - for file in files: - with open(file, "rb") as bin : - self.send(command) - print("Install " + file) - self.wait(XMDM_MSG) - print("|0%" + - "-" * (int(MAX_DOT_COUNT / 2) - 6) + - "50%" + - "-" * (MAX_DOT_COUNT - int(MAX_DOT_COUNT / 2) - 5) + - "100%|") - if ConfigArgs.XMODEM_BAUD: - self.serial.setBaudrate(ConfigArgs.XMODEM_BAUD) - self.serial.discard_inputs() # Clear input buffer to sync - self.serial.set_file_size(os.path.getsize(file)) - modem.send(bin) - if ConfigArgs.XMODEM_BAUD: - self.serial.setBaudrate(115200) - self.wait_for_prompt() + def install_files(self, files, command): + if ConfigArgs.XMODEM_BAUD: + command += " -b " + ConfigArgs.XMODEM_BAUD + if os.name == "nt": + modem = xmodem.XMODEM(self.serial.getc, self.serial.putc_win, "xmodem1k") + else: + modem = xmodem.XMODEM(self.serial.getc, self.serial.putc, "xmodem1k") + for file in files: + with open(file, "rb") as bin: + self.send(command) + print("Install " + file) + self.wait(XMDM_MSG) + print( + "|0%" + + "-" * (int(MAX_DOT_COUNT / 2) - 6) + + "50%" + + "-" * (MAX_DOT_COUNT - int(MAX_DOT_COUNT / 2) - 5) + + "100%|" + ) + if ConfigArgs.XMODEM_BAUD: + self.serial.setBaudrate(ConfigArgs.XMODEM_BAUD) + self.serial.discard_inputs() # Clear input buffer to sync + self.serial.set_file_size(os.path.getsize(file)) + modem.send(bin) + if ConfigArgs.XMODEM_BAUD: + self.serial.setBaudrate(115200) + self.wait_for_prompt() - def save_files(self, files) : - if ConfigArgs.XMODEM_BAUD: - command = "save_file -b " + ConfigArgs.XMODEM_BAUD + " -x " - else: - command = "save_file -x " - if os.name == 'nt': - modem = xmodem.XMODEM(self.serial.getc, self.serial.putc_win, 'xmodem1k') - else: - modem = xmodem.XMODEM(self.serial.getc, self.serial.putc, 'xmodem1k') - for file in files: - with open(file, "rb") as bin : - self.send(command + os.path.basename(file)) - print("Save " + file) - self.wait(XMDM_MSG) - if ConfigArgs.XMODEM_BAUD: - self.serial.setBaudrate(ConfigArgs.XMODEM_BAUD) - self.serial.discard_inputs() # Clear input buffer to sync - self.serial.set_file_size(os.path.getsize(file)) - modem.send(bin) - if ConfigArgs.XMODEM_BAUD: - self.serial.setBaudrate(115200) - self.wait_for_prompt() - self.send("chmod d+rw " + os.path.basename(file)) - self.wait_for_prompt() + def save_files(self, files): + if ConfigArgs.XMODEM_BAUD: + command = "save_file -b " + ConfigArgs.XMODEM_BAUD + " -x " + else: + command = "save_file -x " + if os.name == "nt": + modem = xmodem.XMODEM(self.serial.getc, self.serial.putc_win, "xmodem1k") + else: + modem = xmodem.XMODEM(self.serial.getc, self.serial.putc, "xmodem1k") + for file in files: + with open(file, "rb") as bin: + self.send(command + os.path.basename(file)) + print("Save " + file) + self.wait(XMDM_MSG) + if ConfigArgs.XMODEM_BAUD: + self.serial.setBaudrate(ConfigArgs.XMODEM_BAUD) + self.serial.discard_inputs() # Clear input buffer to sync + self.serial.set_file_size(os.path.getsize(file)) + modem.send(bin) + if ConfigArgs.XMODEM_BAUD: + self.serial.setBaudrate(115200) + self.wait_for_prompt() + self.send("chmod d+rw " + os.path.basename(file)) + self.wait_for_prompt() - def delete_files(self, files) : - for file in files : - self.delete_binary(file) + def delete_files(self, files): + for file in files: + self.delete_binary(file) + + def delete_binary(self, bin_name): + self.send("rm " + bin_name) + self.wait_for_prompt() - def delete_binary(self, bin_name) : - self.send("rm " + bin_name) - self.wait_for_prompt() def main(): - try: - config_loader = ConfigArgsLoader() - config_loader.update_config() - except: - return errno.EINVAL + try: + config_loader = ConfigArgsLoader() + config_loader.update_config() + except: + return errno.EINVAL - # Wait to reset the board - writer = FlashWriter(ConfigArgs.PROTOCOL_TYPE) + # Wait to reset the board + writer = FlashWriter(ConfigArgs.PROTOCOL_TYPE) - do_wait_reset = True - if ConfigArgs.AUTO_RESET: - if subprocess.call("cd " + sys.path[0] + "; ./reset_board.sh", shell=True) == 0: - print("auto reset board sucess!!") - do_wait_reset = False - bootrom_msg = writer.cancel_autoboot() + do_wait_reset = True + if ConfigArgs.AUTO_RESET: + if subprocess.call("cd " + sys.path[0] + "; ./reset_board.sh", shell=True) == 0: + print("auto reset board sucess!!") + do_wait_reset = False + bootrom_msg = writer.cancel_autoboot() - if ConfigArgs.DTR_RESET: - do_wait_reset = False - bootrom_msg = writer.cancel_autoboot() + if ConfigArgs.DTR_RESET: + do_wait_reset = False + bootrom_msg = writer.cancel_autoboot() - if ConfigArgs.WAIT_RESET == False and do_wait_reset == True: - rx = writer.recv() - time.sleep(1) - for i in range(3): - writer.send("") - rx = writer.recv() - if "updater".encode() in rx: - # No need to wait for reset - do_wait_reset = False - break - time.sleep(1) + if ConfigArgs.WAIT_RESET == False and do_wait_reset == True: + rx = writer.recv() + time.sleep(1) + for i in range(3): + writer.send("") + rx = writer.recv() + if "updater".encode() in rx: + # No need to wait for reset + do_wait_reset = False + break + time.sleep(1) - if do_wait_reset: - # Wait to reset the board - print('Please press RESET button on target board') - sys.stdout.flush() - bootrom_msg = writer.cancel_autoboot() + if do_wait_reset: + # Wait to reset the board + print("Please press RESET button on target board") + sys.stdout.flush() + bootrom_msg = writer.cancel_autoboot() - # Remove files - if ConfigArgs.ERASE_NAME : - print(">>> Remove exisiting files ...") - writer.delete_files(ConfigArgs.ERASE_NAME) + # Remove files + if ConfigArgs.ERASE_NAME: + print(">>> Remove exisiting files ...") + writer.delete_files(ConfigArgs.ERASE_NAME) - # Install files - if ConfigArgs.PACKAGE_NAME or ConfigArgs.PKGSYS_NAME or ConfigArgs.PKGAPP_NAME or ConfigArgs.PKGUPD_NAME: - print(">>> Install files ...") - if ConfigArgs.PACKAGE_NAME : - writer.install_files(ConfigArgs.PACKAGE_NAME, "install") - if ConfigArgs.PKGSYS_NAME : - writer.install_files(ConfigArgs.PKGSYS_NAME, "install") - if ConfigArgs.PKGAPP_NAME : - writer.install_files(ConfigArgs.PKGAPP_NAME, "install") - if ConfigArgs.PKGUPD_NAME : - writer.install_files(ConfigArgs.PKGUPD_NAME, "install -k updater.key") + # Install files + if ( + ConfigArgs.PACKAGE_NAME + or ConfigArgs.PKGSYS_NAME + or ConfigArgs.PKGAPP_NAME + or ConfigArgs.PKGUPD_NAME + ): + print(">>> Install files ...") + if ConfigArgs.PACKAGE_NAME: + writer.install_files(ConfigArgs.PACKAGE_NAME, "install") + if ConfigArgs.PKGSYS_NAME: + writer.install_files(ConfigArgs.PKGSYS_NAME, "install") + if ConfigArgs.PKGAPP_NAME: + writer.install_files(ConfigArgs.PKGAPP_NAME, "install") + if ConfigArgs.PKGUPD_NAME: + writer.install_files(ConfigArgs.PKGUPD_NAME, "install -k updater.key") - # Save files - if ConfigArgs.FILE_NAME : - print(">>> Save files ...") - writer.save_files(ConfigArgs.FILE_NAME) + # Save files + if ConfigArgs.FILE_NAME: + print(">>> Save files ...") + writer.save_files(ConfigArgs.FILE_NAME) - # Set auto boot - if not ConfigArgs.NO_SET_BOOTABLE: - print(">>> Save Configuration to FlashROM ...") - writer.send("set bootable M0P") - writer.wait_for_prompt() + # Set auto boot + if not ConfigArgs.NO_SET_BOOTABLE: + print(">>> Save Configuration to FlashROM ...") + writer.send("set bootable M0P") + writer.wait_for_prompt() - # Sync all cached data to flash - writer.send("sync") - writer.wait_for_prompt() + # Sync all cached data to flash + writer.send("sync") + writer.wait_for_prompt() - if REBOOT_AT_END : - print("Restarting the board ...") - writer.send("reboot") + if REBOOT_AT_END: + print("Restarting the board ...") + writer.send("reboot") + + return 0 - return 0 if __name__ == "__main__": - try: - sys.exit(main()) - except KeyboardInterrupt: - print("Canceled by keyboard interrupt.") - pass + try: + sys.exit(main()) + except KeyboardInterrupt: + print("Canceled by keyboard interrupt.") + pass diff --git a/ports/cxd56/tools/xmodem.py b/ports/cxd56/tools/xmodem.py index c934300560..cf78338645 100644 --- a/ports/cxd56/tools/xmodem.py +++ b/ports/cxd56/tools/xmodem.py @@ -1,4 +1,4 @@ -''' +""" =============================== XMODEM file transfer protocol =============================== @@ -105,13 +105,12 @@ YMODEM Batch Transmission Session (1 file) <-- ACK -''' +""" -__author__ = 'Wijnand Modderman ' -__copyright__ = ['Copyright (c) 2010 Wijnand Modderman', - 'Copyright (c) 1981 Chuck Forsberg'] -__license__ = 'MIT' -__version__ = '0.3.2' +__author__ = "Wijnand Modderman " +__copyright__ = ["Copyright (c) 2010 Wijnand Modderman", "Copyright (c) 1981 Chuck Forsberg"] +__license__ = "MIT" +__version__ = "0.3.2" import logging import time @@ -120,7 +119,7 @@ from functools import partial import collections # Loggerr -log = logging.getLogger('xmodem') +log = logging.getLogger("xmodem") # Protocol bytes SOH = bytes([0x01]) @@ -130,11 +129,11 @@ ACK = bytes([0x06]) DLE = bytes([0x10]) NAK = bytes([0x15]) CAN = bytes([0x18]) -CRC = bytes([0x43]) # C +CRC = bytes([0x43]) # C class XMODEM(object): - ''' + """ XMODEM Protocol handler, expects an object to read from and an object to write to. @@ -156,59 +155,283 @@ class XMODEM(object): :param pad: Padding character to make the packets match the packet size :type pad: char - ''' + """ # crctab calculated by Mark G. Mendel, Network Systems Corporation crctable = [ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0, + 0x0000, + 0x1021, + 0x2042, + 0x3063, + 0x4084, + 0x50A5, + 0x60C6, + 0x70E7, + 0x8108, + 0x9129, + 0xA14A, + 0xB16B, + 0xC18C, + 0xD1AD, + 0xE1CE, + 0xF1EF, + 0x1231, + 0x0210, + 0x3273, + 0x2252, + 0x52B5, + 0x4294, + 0x72F7, + 0x62D6, + 0x9339, + 0x8318, + 0xB37B, + 0xA35A, + 0xD3BD, + 0xC39C, + 0xF3FF, + 0xE3DE, + 0x2462, + 0x3443, + 0x0420, + 0x1401, + 0x64E6, + 0x74C7, + 0x44A4, + 0x5485, + 0xA56A, + 0xB54B, + 0x8528, + 0x9509, + 0xE5EE, + 0xF5CF, + 0xC5AC, + 0xD58D, + 0x3653, + 0x2672, + 0x1611, + 0x0630, + 0x76D7, + 0x66F6, + 0x5695, + 0x46B4, + 0xB75B, + 0xA77A, + 0x9719, + 0x8738, + 0xF7DF, + 0xE7FE, + 0xD79D, + 0xC7BC, + 0x48C4, + 0x58E5, + 0x6886, + 0x78A7, + 0x0840, + 0x1861, + 0x2802, + 0x3823, + 0xC9CC, + 0xD9ED, + 0xE98E, + 0xF9AF, + 0x8948, + 0x9969, + 0xA90A, + 0xB92B, + 0x5AF5, + 0x4AD4, + 0x7AB7, + 0x6A96, + 0x1A71, + 0x0A50, + 0x3A33, + 0x2A12, + 0xDBFD, + 0xCBDC, + 0xFBBF, + 0xEB9E, + 0x9B79, + 0x8B58, + 0xBB3B, + 0xAB1A, + 0x6CA6, + 0x7C87, + 0x4CE4, + 0x5CC5, + 0x2C22, + 0x3C03, + 0x0C60, + 0x1C41, + 0xEDAE, + 0xFD8F, + 0xCDEC, + 0xDDCD, + 0xAD2A, + 0xBD0B, + 0x8D68, + 0x9D49, + 0x7E97, + 0x6EB6, + 0x5ED5, + 0x4EF4, + 0x3E13, + 0x2E32, + 0x1E51, + 0x0E70, + 0xFF9F, + 0xEFBE, + 0xDFDD, + 0xCFFC, + 0xBF1B, + 0xAF3A, + 0x9F59, + 0x8F78, + 0x9188, + 0x81A9, + 0xB1CA, + 0xA1EB, + 0xD10C, + 0xC12D, + 0xF14E, + 0xE16F, + 0x1080, + 0x00A1, + 0x30C2, + 0x20E3, + 0x5004, + 0x4025, + 0x7046, + 0x6067, + 0x83B9, + 0x9398, + 0xA3FB, + 0xB3DA, + 0xC33D, + 0xD31C, + 0xE37F, + 0xF35E, + 0x02B1, + 0x1290, + 0x22F3, + 0x32D2, + 0x4235, + 0x5214, + 0x6277, + 0x7256, + 0xB5EA, + 0xA5CB, + 0x95A8, + 0x8589, + 0xF56E, + 0xE54F, + 0xD52C, + 0xC50D, + 0x34E2, + 0x24C3, + 0x14A0, + 0x0481, + 0x7466, + 0x6447, + 0x5424, + 0x4405, + 0xA7DB, + 0xB7FA, + 0x8799, + 0x97B8, + 0xE75F, + 0xF77E, + 0xC71D, + 0xD73C, + 0x26D3, + 0x36F2, + 0x0691, + 0x16B0, + 0x6657, + 0x7676, + 0x4615, + 0x5634, + 0xD94C, + 0xC96D, + 0xF90E, + 0xE92F, + 0x99C8, + 0x89E9, + 0xB98A, + 0xA9AB, + 0x5844, + 0x4865, + 0x7806, + 0x6827, + 0x18C0, + 0x08E1, + 0x3882, + 0x28A3, + 0xCB7D, + 0xDB5C, + 0xEB3F, + 0xFB1E, + 0x8BF9, + 0x9BD8, + 0xABBB, + 0xBB9A, + 0x4A75, + 0x5A54, + 0x6A37, + 0x7A16, + 0x0AF1, + 0x1AD0, + 0x2AB3, + 0x3A92, + 0xFD2E, + 0xED0F, + 0xDD6C, + 0xCD4D, + 0xBDAA, + 0xAD8B, + 0x9DE8, + 0x8DC9, + 0x7C26, + 0x6C07, + 0x5C64, + 0x4C45, + 0x3CA2, + 0x2C83, + 0x1CE0, + 0x0CC1, + 0xEF1F, + 0xFF3E, + 0xCF5D, + 0xDF7C, + 0xAF9B, + 0xBFBA, + 0x8FD9, + 0x9FF8, + 0x6E17, + 0x7E36, + 0x4E55, + 0x5E74, + 0x2E93, + 0x3EB2, + 0x0ED1, + 0x1EF0, ] - def __init__(self, getc, putc, mode='xmodem', pad=b'\x1a'): + def __init__(self, getc, putc, mode="xmodem", pad=b"\x1a"): self.getc = getc self.putc = putc self.mode = mode self.pad = pad def abort(self, count=2, timeout=60): - ''' + """ Send an abort sequence using CAN bytes. - ''' + """ for counter in range(0, count): self.putc(CAN, timeout) def send(self, stream, retry=32, timeout=360, quiet=0, callback=None): - ''' + """ Send a stream via the XMODEM protocol. >>> stream = file('/etc/issue', 'rb') @@ -235,14 +458,11 @@ class XMODEM(object): Expected callback signature: def callback(total_packets, success_count, error_count) :type callback: callable - ''' + """ # initialize protocol try: - packet_size = dict( - xmodem = 128, - xmodem1k = 1024, - )[self.mode] + packet_size = dict(xmodem=128, xmodem1k=1024)[self.mode] except AttributeError: raise ValueError("An invalid mode was supplied") @@ -260,14 +480,13 @@ class XMODEM(object): break elif char == CAN: if not quiet: - print('received CAN', file=sys.stderr) + print("received CAN", file=sys.stderr) if cancel: return False else: cancel = 1 else: - log.error('send ERROR expected NAK/CRC, got %s' % \ - (ord(char),)) + log.error("send ERROR expected NAK/CRC, got %s" % (ord(char),)) error_count += 1 if error_count >= retry: @@ -282,7 +501,7 @@ class XMODEM(object): while True: data = stream.read(packet_size) if not data: - log.info('sending EOT') + log.info("sending EOT") # end of stream break total_packets += 1 @@ -299,11 +518,11 @@ class XMODEM(object): else: # packet_size == 1024 self.putc(STX) self.putc(bytes([sequence])) - self.putc(bytes([0xff - sequence])) + self.putc(bytes([0xFF - sequence])) self.putc(data) if crc_mode: self.putc(bytes([crc >> 8])) - self.putc(bytes([crc & 0xff])) + self.putc(bytes([crc & 0xFF])) else: self.putc(bytes([crc])) @@ -321,13 +540,13 @@ class XMODEM(object): # excessive amounts of retransmissions requested, # abort transfer self.abort(timeout=timeout) - log.warning('excessive NAKs, transfer aborted') + log.warning("excessive NAKs, transfer aborted") return False # return to loop and resend continue else: - log.error('Not ACK, Not NAK') + log.error("Not ACK, Not NAK") error_count += 1 if isinstance(callback, collections.Callable): callback(total_packets, success_count, error_count) @@ -335,7 +554,7 @@ class XMODEM(object): # excessive amounts of retransmissions requested, # abort transfer self.abort(timeout=timeout) - log.warning('excessive protocol errors, transfer aborted') + log.warning("excessive protocol errors, transfer aborted") return False # return to loop and resend @@ -343,7 +562,7 @@ class XMODEM(object): # protocol error self.abort(timeout=timeout) - log.error('protocol error') + log.error("protocol error") return False # keep track of sequence @@ -353,7 +572,7 @@ class XMODEM(object): # end of transmission self.putc(EOT) - #An ACK should be returned + # An ACK should be returned char = self.getc(1, timeout) if char == ACK: break @@ -361,13 +580,13 @@ class XMODEM(object): error_count += 1 if error_count >= retry: self.abort(timeout=timeout) - log.warning('EOT was not ACKd, transfer aborted') + log.warning("EOT was not ACKd, transfer aborted") return False return True def recv(self, stream, crc_mode=1, retry=16, timeout=60, delay=1, quiet=0): - ''' + """ Receive a stream via the XMODEM protocol. >>> stream = file('/etc/issue', 'wb') @@ -376,7 +595,7 @@ class XMODEM(object): Returns the number of bytes received on success or ``None`` in case of failure. - ''' + """ # initiate protocol error_count = 0 @@ -403,7 +622,7 @@ class XMODEM(object): error_count += 1 continue elif char == SOH: - #crc_mode = 0 + # crc_mode = 0 break elif char == STX: break @@ -442,7 +661,7 @@ class XMODEM(object): cancel = 1 else: if not quiet: - print('recv ERROR expected SOH/EOT, got', ord(char), file=sys.stderr) + print("recv ERROR expected SOH/EOT, got", ord(char), file=sys.stderr) error_count += 1 if error_count >= retry: self.abort() @@ -451,7 +670,7 @@ class XMODEM(object): error_count = 0 cancel = 0 seq1 = ord(self.getc(1)) - seq2 = 0xff - ord(self.getc(1)) + seq2 = 0xFF - ord(self.getc(1)) if seq1 == sequence and seq2 == sequence: # sequence is ok, read packet # packet_size + checksum @@ -459,14 +678,14 @@ class XMODEM(object): if crc_mode: csum = (ord(data[-2]) << 8) + ord(data[-1]) data = data[:-2] - log.debug('CRC (%04x <> %04x)' % \ - (csum, self.calc_crc(data))) + log.debug("CRC (%04x <> %04x)" % (csum, self.calc_crc(data))) valid = csum == self.calc_crc(data) else: csum = data[-1] data = data[:-1] - log.debug('checksum (checksum(%02x <> %02x)' % \ - (ord(csum), self.calc_checksum(data))) + log.debug( + "checksum (checksum(%02x <> %02x)" % (ord(csum), self.calc_checksum(data)) + ) valid = ord(csum) == self.calc_checksum(data) # valid data, append chunk @@ -480,14 +699,13 @@ class XMODEM(object): else: # consume data self.getc(packet_size + 1 + crc_mode) - self.debug('expecting sequence %d, got %d/%d' % \ - (sequence, seq1, seq2)) + self.debug("expecting sequence %d, got %d/%d" % (sequence, seq1, seq2)) # something went wrong, request retransmission self.putc(NAK) def calc_checksum(self, data, checksum=0): - ''' + """ Calculate the checksum for a given block of data, can also be used to update a checksum. @@ -496,11 +714,11 @@ class XMODEM(object): >>> hex(csum) '0x3c' - ''' + """ return (sum(map(ord, data)) + checksum) % 256 def calc_crc(self, data, crc=0): - ''' + """ Calculate the Cyclic Redundancy Check for a given block of data, can also be used to update a CRC. @@ -509,51 +727,50 @@ class XMODEM(object): >>> hex(crc) '0xd5e3' - ''' + """ for char in data: - crc = (crc << 8) ^ self.crctable[((crc >> 8) ^ int(char)) & 0xff] - return crc & 0xffff + crc = (crc << 8) ^ self.crctable[((crc >> 8) ^ int(char)) & 0xFF] + return crc & 0xFFFF -XMODEM1k = partial(XMODEM, mode='xmodem1k') +XMODEM1k = partial(XMODEM, mode="xmodem1k") def run(): import optparse import subprocess - parser = optparse.OptionParser(usage='%prog [] filename filename') - parser.add_option('-m', '--mode', default='xmodem', - help='XMODEM mode (xmodem, xmodem1k)') + parser = optparse.OptionParser(usage="%prog [] filename filename") + parser.add_option("-m", "--mode", default="xmodem", help="XMODEM mode (xmodem, xmodem1k)") options, args = parser.parse_args() if len(args) != 3: - parser.error('invalid arguments') + parser.error("invalid arguments") return 1 - elif args[0] not in ('send', 'recv'): - parser.error('invalid mode') + elif args[0] not in ("send", "recv"): + parser.error("invalid mode") return 1 def _func(so, si): import select import subprocess - print('si', si) - print('so', so) + print("si", si) + print("so", so) def getc(size, timeout=3): - w,t,f = select.select([so], [], [], timeout) + w, t, f = select.select([so], [], [], timeout) if w: data = so.read(size) else: data = None - print('getc(', repr(data), ')') + print("getc(", repr(data), ")") return data def putc(data, timeout=3): - w,t,f = select.select([], [si], [], timeout) + w, t, f = select.select([], [si], [], timeout) if t: si.write(data) si.flush() @@ -561,30 +778,31 @@ def run(): else: size = None - print('putc(', repr(data), repr(size), ')') + print("putc(", repr(data), repr(size), ")") return size return getc, putc def _pipe(*command): - pipe = subprocess.Popen(command, - stdout=subprocess.PIPE, stdin=subprocess.PIPE) + pipe = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE) return pipe.stdout, pipe.stdin - if args[0] == 'recv': + if args[0] == "recv": import io - getc, putc = _func(*_pipe('sz', '--xmodem', args[2])) - stream = open(args[1], 'wb') + + getc, putc = _func(*_pipe("sz", "--xmodem", args[2])) + stream = open(args[1], "wb") xmodem = XMODEM(getc, putc, mode=options.mode) status = xmodem.recv(stream, retry=8) stream.close() - elif args[0] == 'send': - getc, putc = _func(*_pipe('rz', '--xmodem', args[2])) - stream = open(args[1], 'rb') + elif args[0] == "send": + getc, putc = _func(*_pipe("rz", "--xmodem", args[2])) + stream = open(args[1], "rb") xmodem = XMODEM(getc, putc, mode=options.mode) status = xmodem.send(stream, retry=8) stream.close() -if __name__ == '__main__': + +if __name__ == "__main__": sys.exit(run()) diff --git a/ports/esp32s2/background.c b/ports/esp32s2/background.c index 3160d9974e..80b60bebe3 100644 --- a/ports/esp32s2/background.c +++ b/ports/esp32s2/background.c @@ -48,6 +48,8 @@ void port_background_task(void) { #endif } -void port_start_background_task(void) {} +void port_start_background_task(void) { +} -void port_finish_background_task(void) {} +void port_finish_background_task(void) { +} diff --git a/ports/esp32s2/bindings/espidf/__init__.c b/ports/esp32s2/bindings/espidf/__init__.c index 708c30c391..97e1136f87 100644 --- a/ports/esp32s2/bindings/espidf/__init__.c +++ b/ports/esp32s2/bindings/espidf/__init__.c @@ -125,13 +125,13 @@ STATIC MP_DEFINE_CONST_DICT(espidf_module_globals, espidf_module_globals_table); const mp_obj_module_t espidf_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&espidf_module_globals, + .globals = (mp_obj_dict_t *)&espidf_module_globals, }; void raise_esp_error(esp_err_t err) { const compressed_string_t *msg = NULL; - const mp_obj_type_t * exception_type = &mp_type_espidf_IDFError; - switch(err) { + const mp_obj_type_t *exception_type = &mp_type_espidf_IDFError; + switch (err) { case ESP_FAIL: msg = translate("Generic Failure"); break; @@ -177,9 +177,9 @@ void raise_esp_error(esp_err_t err) { const char *group = "ESP-IDF"; // tests must be in descending order - MP_STATIC_ASSERT( ESP_ERR_FLASH_BASE > ESP_ERR_MESH_BASE ); - MP_STATIC_ASSERT( ESP_ERR_MESH_BASE > ESP_ERR_WIFI_BASE ); - if(err >= ESP_ERR_FLASH_BASE) { + MP_STATIC_ASSERT(ESP_ERR_FLASH_BASE > ESP_ERR_MESH_BASE); + MP_STATIC_ASSERT(ESP_ERR_MESH_BASE > ESP_ERR_WIFI_BASE); + if (err >= ESP_ERR_FLASH_BASE) { group = "Flash"; } else if (err >= ESP_ERR_MESH_BASE) { group = "Mesh"; diff --git a/ports/esp32s2/bindings/espidf/__init__.h b/ports/esp32s2/bindings/espidf/__init__.h index 9248b01acd..866edb1288 100644 --- a/ports/esp32s2/bindings/espidf/__init__.h +++ b/ports/esp32s2/bindings/espidf/__init__.h @@ -37,6 +37,6 @@ extern const mp_obj_type_t mp_type_espidf_MemoryError; NORETURN void mp_raise_espidf_MemoryError(void); void raise_esp_error(esp_err_t err) NORETURN; -#define CHECK_ESP_RESULT(x) do { int res = (x); if(res != ESP_OK) raise_esp_error(res); } while(0) +#define CHECK_ESP_RESULT(x) do { int res = (x); if (res != ESP_OK) raise_esp_error(res); } while (0) #endif // MICROPY_INCLUDED_ESP32S2_BINDINGS_ESPIDF___INIT___H diff --git a/ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/board.c b/ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/board.c index aaef97c7d1..e40b6335bc 100644 --- a/ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/board.c +++ b/ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h b/ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h index 9d95e8e437..a04065d25b 100644 --- a/ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h +++ b/ports/esp32s2/boards/adafruit_feather_esp32s2_nopsram/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Feather ESP32S2 without PSRAM" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/board.c b/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/board.c index c8be187470..799494006d 100644 --- a/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/board.c +++ b/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/board.c @@ -55,10 +55,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ /* busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; diff --git a/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h b/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h index 9d95e8e437..a04065d25b 100644 --- a/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h +++ b/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Feather ESP32S2 without PSRAM" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/pins.c b/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/pins.c index 7e1a723742..0504f9694e 100644 --- a/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/pins.c +++ b/ports/esp32s2/boards/adafruit_feather_esp32s2_tftback_nopsram/pins.c @@ -67,6 +67,6 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, - // { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display)} + // { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display)} }; MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/board.c b/ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/board.c index 63a16c1206..020e6f6a1f 100644 --- a/ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/board.c +++ b/ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/board.c @@ -35,7 +35,7 @@ #include "components/log/include/esp_log.h" -static const char* TAG = "board"; +static const char *TAG = "board"; #define DELAY 0x80 @@ -115,16 +115,16 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO36, &pin_GPIO35, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -135,7 +135,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_epaperdisplay_obj_t* display = &displays[0].epaper_display; + displayio_epaperdisplay_obj_t *display = &displays[0].epaper_display; display->base.type = &displayio_epaperdisplay_type; common_hal_displayio_epaperdisplay_construct( display, @@ -176,7 +176,7 @@ void reset_board(void) { } void board_deinit(void) { - displayio_epaperdisplay_obj_t* display = &displays[0].epaper_display; + displayio_epaperdisplay_obj_t *display = &displays[0].epaper_display; if (display->base.type == &displayio_epaperdisplay_type) { size_t i = 0; while (common_hal_displayio_epaperdisplay_get_busy(display)) { diff --git a/ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h b/ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h index 8dfe912712..ecfa1d78b3 100644 --- a/ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h +++ b/ports/esp32s2/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Adafruit MagTag" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h b/ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h index b25d7d1169..ec992383aa 100644 --- a/ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h +++ b/ports/esp32s2/boards/adafruit_metro_esp32s2/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Adafruit Metro ESP32S2" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/electroniccats_bastwifi/board.c b/ports/esp32s2/boards/electroniccats_bastwifi/board.c index aaef97c7d1..e40b6335bc 100644 --- a/ports/esp32s2/boards/electroniccats_bastwifi/board.c +++ b/ports/esp32s2/boards/electroniccats_bastwifi/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h b/ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h index 1ec61e9461..cc4fd40df2 100644 --- a/ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h +++ b/ports/esp32s2/boards/electroniccats_bastwifi/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "BastWiFi" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/espressif_kaluga_1/board.c b/ports/esp32s2/boards/espressif_kaluga_1/board.c index aaef97c7d1..e40b6335bc 100644 --- a/ports/esp32s2/boards/espressif_kaluga_1/board.c +++ b/ports/esp32s2/boards/espressif_kaluga_1/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h b/ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h index 2c0f175abf..21f6ae2456 100644 --- a/ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h +++ b/ports/esp32s2/boards/espressif_kaluga_1/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Kaluga 1" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/espressif_saola_1_wroom/board.c b/ports/esp32s2/boards/espressif_saola_1_wroom/board.c index aaef97c7d1..e40b6335bc 100644 --- a/ports/esp32s2/boards/espressif_saola_1_wroom/board.c +++ b/ports/esp32s2/boards/espressif_saola_1_wroom/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h b/ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h index 3f628c0f1e..2aac10fe79 100644 --- a/ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h +++ b/ports/esp32s2/boards/espressif_saola_1_wroom/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Saola 1 w/Wroom" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/espressif_saola_1_wrover/board.c b/ports/esp32s2/boards/espressif_saola_1_wrover/board.c index aaef97c7d1..e40b6335bc 100644 --- a/ports/esp32s2/boards/espressif_saola_1_wrover/board.c +++ b/ports/esp32s2/boards/espressif_saola_1_wrover/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h b/ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h index 9615228910..a5aa83814d 100644 --- a/ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h +++ b/ports/esp32s2/boards/espressif_saola_1_wrover/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Saola 1 w/Wrover" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/franzininho_wifi_wroom/board.c b/ports/esp32s2/boards/franzininho_wifi_wroom/board.c index aaef97c7d1..e40b6335bc 100644 --- a/ports/esp32s2/boards/franzininho_wifi_wroom/board.c +++ b/ports/esp32s2/boards/franzininho_wifi_wroom/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h b/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h index 0960e96b60..c0a8659b1d 100644 --- a/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h +++ b/ports/esp32s2/boards/franzininho_wifi_wroom/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Franzininho WIFI w/Wroom" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/franzininho_wifi_wrover/board.c b/ports/esp32s2/boards/franzininho_wifi_wrover/board.c index aaef97c7d1..e40b6335bc 100644 --- a/ports/esp32s2/boards/franzininho_wifi_wrover/board.c +++ b/ports/esp32s2/boards/franzininho_wifi_wrover/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h b/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h index fd10ee0b58..b17a65c10c 100644 --- a/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h +++ b/ports/esp32s2/boards/franzininho_wifi_wrover/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Franzininho WIFI w/Wrover" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/board.c b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/board.c index 4aa7b3b24f..1002fa6b76 100644 --- a/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/board.c +++ b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/board.c @@ -62,21 +62,21 @@ uint8_t display_init_sequence[] = { 0x21, 0, // display on 0x29, 0 | DELAY, 255, - }; +}; static void display_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct( spi, &pin_GPIO36, // CLK &pin_GPIO35, // MOSI NULL // MISO not connected - ); + ); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct( @@ -88,9 +88,9 @@ static void display_init(void) { 40000000, // baudrate 0, // polarity 0 // phase - ); + ); - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; // workaround as board_init() is called before reset_port() in main.c @@ -126,7 +126,7 @@ static void display_init(void) { 60, // native_frames_per_second true, // backlight_on_high false // SH1107_addressing - ); + ); common_hal_never_reset_pin(&pin_GPIO33); // backlight pin } @@ -137,10 +137,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ // Display display_init(); diff --git a/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h index c9020c2002..c9159b6f32 100644 --- a/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h +++ b/ports/esp32s2/boards/lilygo_ttgo_t8_s2_st7789/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "LILYGO TTGO T8 ESP32-S2 w/Display" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/microdev_micro_s2/board.c b/ports/esp32s2/boards/microdev_micro_s2/board.c index d8fd3a0a2b..a0e399b1ef 100644 --- a/ports/esp32s2/boards/microdev_micro_s2/board.c +++ b/ports/esp32s2/boards/microdev_micro_s2/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ // SPI Flash and RAM common_hal_never_reset_pin(&pin_GPIO26); diff --git a/ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h b/ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h index 272ab20fa5..47bcde7e93 100644 --- a/ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h +++ b/ports/esp32s2/boards/microdev_micro_s2/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "microS2" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/muselab_nanoesp32_s2/board.c b/ports/esp32s2/boards/muselab_nanoesp32_s2/board.c index aaef97c7d1..e40b6335bc 100644 --- a/ports/esp32s2/boards/muselab_nanoesp32_s2/board.c +++ b/ports/esp32s2/boards/muselab_nanoesp32_s2/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ } bool board_requests_safe_mode(void) { diff --git a/ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h b/ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h index 6b05ac06f4..1612153976 100644 --- a/ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h +++ b/ports/esp32s2/boards/muselab_nanoesp32_s2/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "nanoESP32-S2" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/targett_module_clip_wroom/board.c b/ports/esp32s2/boards/targett_module_clip_wroom/board.c index 9c58dd2c8a..00b94a0259 100644 --- a/ports/esp32s2/boards/targett_module_clip_wroom/board.c +++ b/ports/esp32s2/boards/targett_module_clip_wroom/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ // Crystal common_hal_never_reset_pin(&pin_GPIO15); diff --git a/ports/esp32s2/boards/targett_module_clip_wroom/mpconfigboard.h b/ports/esp32s2/boards/targett_module_clip_wroom/mpconfigboard.h index 6cf69138e7..fe57007a94 100644 --- a/ports/esp32s2/boards/targett_module_clip_wroom/mpconfigboard.h +++ b/ports/esp32s2/boards/targett_module_clip_wroom/mpconfigboard.h @@ -24,14 +24,14 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup -//Essentially the same as the Saola board but without the neopixel +// Essentially the same as the Saola board but without the neopixel #define MICROPY_HW_BOARD_NAME "Targett Module Clip w/Wroom" #define MICROPY_HW_MCU_NAME "ESP32S2" -//#define MICROPY_HW_NEOPIXEL (&pin_GPIO18) +// #define MICROPY_HW_NEOPIXEL (&pin_GPIO18) #define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) diff --git a/ports/esp32s2/boards/targett_module_clip_wroom/pins.c b/ports/esp32s2/boards/targett_module_clip_wroom/pins.c index 99db096457..a8ca8ba3ed 100644 --- a/ports/esp32s2/boards/targett_module_clip_wroom/pins.c +++ b/ports/esp32s2/boards/targett_module_clip_wroom/pins.c @@ -43,6 +43,6 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_IO45), MP_ROM_PTR(&pin_GPIO45) }, { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, - //{ MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO18) }, + // { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO18) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/targett_module_clip_wrover/board.c b/ports/esp32s2/boards/targett_module_clip_wrover/board.c index f5e66acb61..00b94a0259 100644 --- a/ports/esp32s2/boards/targett_module_clip_wrover/board.c +++ b/ports/esp32s2/boards/targett_module_clip_wrover/board.c @@ -34,12 +34,12 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ - //Crystal + // Crystal common_hal_never_reset_pin(&pin_GPIO15); common_hal_never_reset_pin(&pin_GPIO16); } diff --git a/ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h b/ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h index 3c74d27fa4..c36ab50d11 100644 --- a/ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h +++ b/ports/esp32s2/boards/targett_module_clip_wrover/mpconfigboard.h @@ -24,14 +24,14 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup -//Same setup as the Saola board but with no Neopixel on board +// Same setup as the Saola board but with no Neopixel on board #define MICROPY_HW_BOARD_NAME "Targett Module Clip w/Wrover" #define MICROPY_HW_MCU_NAME "ESP32S2" -//#define MICROPY_HW_NEOPIXEL (&pin_GPIO18) +// #define MICROPY_HW_NEOPIXEL (&pin_GPIO18) #define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) diff --git a/ports/esp32s2/boards/targett_module_clip_wrover/pins.c b/ports/esp32s2/boards/targett_module_clip_wrover/pins.c index 99db096457..a8ca8ba3ed 100644 --- a/ports/esp32s2/boards/targett_module_clip_wrover/pins.c +++ b/ports/esp32s2/boards/targett_module_clip_wrover/pins.c @@ -43,6 +43,6 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_IO45), MP_ROM_PTR(&pin_GPIO45) }, { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, - //{ MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO18) }, + // { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO18) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c b/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c index d8fd3a0a2b..a0e399b1ef 100644 --- a/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ // SPI Flash and RAM common_hal_never_reset_pin(&pin_GPIO26); diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h b/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h index e100ac118e..57f35018da 100644 --- a/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "FeatherS2" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/board.c b/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/board.c index d8fd3a0a2b..a0e399b1ef 100644 --- a/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/board.c +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ // SPI Flash and RAM common_hal_never_reset_pin(&pin_GPIO26); diff --git a/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h b/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h index d550ff64fe..7304512aa8 100644 --- a/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +++ b/ports/esp32s2/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "FeatherS2 PreRelease" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/boards/unexpectedmaker_tinys2/board.c b/ports/esp32s2/boards/unexpectedmaker_tinys2/board.c index d8fd3a0a2b..a0e399b1ef 100644 --- a/ports/esp32s2/boards/unexpectedmaker_tinys2/board.c +++ b/ports/esp32s2/boards/unexpectedmaker_tinys2/board.c @@ -34,10 +34,10 @@ void board_init(void) { common_hal_never_reset_pin(&pin_GPIO20); // Debug UART -#ifdef DEBUG + #ifdef DEBUG common_hal_never_reset_pin(&pin_GPIO43); common_hal_never_reset_pin(&pin_GPIO44); -#endif /* DEBUG */ + #endif /* DEBUG */ // SPI Flash and RAM common_hal_never_reset_pin(&pin_GPIO26); diff --git a/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h b/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h index 85f252328e..e7d50f0894 100644 --- a/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h +++ b/ports/esp32s2/boards/unexpectedmaker_tinys2/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "TinyS2" #define MICROPY_HW_MCU_NAME "ESP32S2" diff --git a/ports/esp32s2/common-hal/alarm/SleepMemory.c b/ports/esp32s2/common-hal/alarm/SleepMemory.c index 38e3de2b6d..b25bf28d25 100644 --- a/ports/esp32s2/common-hal/alarm/SleepMemory.c +++ b/ports/esp32s2/common-hal/alarm/SleepMemory.c @@ -47,20 +47,20 @@ uint32_t common_hal_alarm_sleep_memory_get_length(alarm_sleep_memory_obj_t *self return sizeof(_sleep_mem); } -bool common_hal_alarm_sleep_memory_set_bytes(alarm_sleep_memory_obj_t *self, uint32_t start_index, const uint8_t* values, uint32_t len) { +bool common_hal_alarm_sleep_memory_set_bytes(alarm_sleep_memory_obj_t *self, uint32_t start_index, const uint8_t *values, uint32_t len) { if (start_index + len > sizeof(_sleep_mem)) { return false; } - memcpy((uint8_t *) (_sleep_mem + start_index), values, len); + memcpy((uint8_t *)(_sleep_mem + start_index), values, len); return true; } -void common_hal_alarm_sleep_memory_get_bytes(alarm_sleep_memory_obj_t *self, uint32_t start_index, uint8_t* values, uint32_t len) { +void common_hal_alarm_sleep_memory_get_bytes(alarm_sleep_memory_obj_t *self, uint32_t start_index, uint8_t *values, uint32_t len) { if (start_index + len > sizeof(_sleep_mem)) { return; } - memcpy(values, (uint8_t *) (_sleep_mem + start_index), len); + memcpy(values, (uint8_t *)(_sleep_mem + start_index), len); } diff --git a/ports/esp32s2/common-hal/alarm/pin/PinAlarm.c b/ports/esp32s2/common-hal/alarm/pin/PinAlarm.c index df8d10ef9e..9ccb5700cb 100644 --- a/ports/esp32s2/common-hal/alarm/pin/PinAlarm.c +++ b/ports/esp32s2/common-hal/alarm/pin/PinAlarm.c @@ -72,11 +72,11 @@ gpio_isr_handle_t gpio_interrupt_handle; static volatile uint32_t pin_31_0_status = 0; static volatile uint32_t pin_63_32_status = 0; void gpio_interrupt(void *arg) { - (void) arg; + (void)arg; - gpio_ll_get_intr_status(&GPIO, xPortGetCoreID(), (uint32_t*) &pin_31_0_status); + gpio_ll_get_intr_status(&GPIO, xPortGetCoreID(), (uint32_t *)&pin_31_0_status); gpio_ll_clear_intr_status(&GPIO, pin_31_0_status); - gpio_ll_get_intr_status_high(&GPIO, xPortGetCoreID(), (uint32_t*) &pin_63_32_status); + gpio_ll_get_intr_status_high(&GPIO, xPortGetCoreID(), (uint32_t *)&pin_63_32_status); gpio_ll_clear_intr_status_high(&GPIO, pin_63_32_status); // disable the interrupts that fired, maybe all of them @@ -102,12 +102,12 @@ bool alarm_pin_pinalarm_woke_us_up(void) { mp_obj_t alarm_pin_pinalarm_get_wakeup_alarm(size_t n_alarms, const mp_obj_t *alarms) { // First, check to see if we match any given alarms. - uint64_t pin_status = ((uint64_t) pin_63_32_status) << 32 | pin_31_0_status; + uint64_t pin_status = ((uint64_t)pin_63_32_status) << 32 | pin_31_0_status; for (size_t i = 0; i < n_alarms; i++) { if (!MP_OBJ_IS_TYPE(alarms[i], &alarm_pin_pinalarm_type)) { continue; } - alarm_pin_pinalarm_obj_t *alarm = MP_OBJ_TO_PTR(alarms[i]); + alarm_pin_pinalarm_obj_t *alarm = MP_OBJ_TO_PTR(alarms[i]); if ((pin_status & (1ull << alarm->pin->number)) != 0) { return alarms[i]; } @@ -136,8 +136,8 @@ mp_obj_t alarm_pin_pinalarm_get_wakeup_alarm(size_t n_alarms, const mp_obj_t *al alarm->pin = NULL; // Map the pin number back to a pin object. for (size_t i = 0; i < mcu_pin_globals.map.used; i++) { - const mcu_pin_obj_t* pin_obj = MP_OBJ_TO_PTR(mcu_pin_globals.map.table[i].value); - if ((size_t) pin_obj->number == pin_number) { + const mcu_pin_obj_t *pin_obj = MP_OBJ_TO_PTR(mcu_pin_globals.map.table[i].value); + if ((size_t)pin_obj->number == pin_number) { alarm->pin = mcu_pin_globals.map.table[i].value; break; } @@ -182,7 +182,7 @@ void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ob if (!MP_OBJ_IS_TYPE(alarms[i], &alarm_pin_pinalarm_type)) { continue; } - alarm_pin_pinalarm_obj_t *alarm = MP_OBJ_TO_PTR(alarms[i]); + alarm_pin_pinalarm_obj_t *alarm = MP_OBJ_TO_PTR(alarms[i]); gpio_num_t pin_number = alarm->pin->number; if (alarm->value) { diff --git a/ports/esp32s2/common-hal/alarm/pin/__init__.c b/ports/esp32s2/common-hal/alarm/pin/__init__.c index b39693c6af..ca8cfac7f7 100644 --- a/ports/esp32s2/common-hal/alarm/pin/__init__.c +++ b/ports/esp32s2/common-hal/alarm/pin/__init__.c @@ -3,20 +3,20 @@ #include "esp_sleep.h" #include "driver/rtc_io.h" -mp_obj_t common_hal_alarm_io_pin_state (alarm_io_obj_t *self_in) { +mp_obj_t common_hal_alarm_io_pin_state(alarm_io_obj_t *self_in) { if (!rtc_gpio_is_valid_gpio(self_in->gpio)) { mp_raise_ValueError(translate("io must be rtc io")); } if (self_in->pull && !self_in->level) { - for (uint8_t i = 0; i<=4; i+=2) { + for (uint8_t i = 0; i <= 4; i += 2) { if (self_in->gpio == i) { mp_raise_ValueError(translate("IOs 0, 2 & 4 do not support internal pullup in sleep")); } } } - switch(esp_sleep_enable_ext0_wakeup(self_in->gpio, self_in->level)) { + switch (esp_sleep_enable_ext0_wakeup(self_in->gpio, self_in->level)) { case ESP_ERR_INVALID_ARG: mp_raise_ValueError(translate("trigger level must be 0 or 1")); case ESP_ERR_INVALID_STATE: @@ -25,11 +25,13 @@ mp_obj_t common_hal_alarm_io_pin_state (alarm_io_obj_t *self_in) { break; } - if (self_in->pull) { (self_in->level) ? rtc_gpio_pulldown_en(self_in->gpio) : rtc_gpio_pullup_en(self_in->gpio); } + if (self_in->pull) { + (self_in->level) ? rtc_gpio_pulldown_en(self_in->gpio) : rtc_gpio_pullup_en(self_in->gpio); + } return self_in; } -void common_hal_alarm_io_disable (void) { +void common_hal_alarm_io_disable(void) { esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_EXT0 | ESP_SLEEP_WAKEUP_EXT1); } diff --git a/ports/esp32s2/common-hal/alarm/time/TimeAlarm.c b/ports/esp32s2/common-hal/alarm/time/TimeAlarm.c index bcde0ab3c0..93e4f18091 100644 --- a/ports/esp32s2/common-hal/alarm/time/TimeAlarm.c +++ b/ports/esp32s2/common-hal/alarm/time/TimeAlarm.c @@ -61,7 +61,7 @@ STATIC bool woke_up = false; // This is run in the timer task. We use it to wake the main CircuitPython task. void timer_callback(void *arg) { - (void) arg; + (void)arg; woke_up = true; xTaskNotifyGive(circuitpython_task); } @@ -88,7 +88,7 @@ void alarm_time_timealarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ if (timealarm_set) { mp_raise_ValueError(translate("Only one alarm.time alarm can be set.")); } - timealarm = MP_OBJ_TO_PTR(alarms[i]); + timealarm = MP_OBJ_TO_PTR(alarms[i]); timealarm_set = true; } if (!timealarm_set) { @@ -110,7 +110,7 @@ void alarm_time_timealarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ // Compute how long to actually sleep, considering the time now. mp_float_t now_secs = uint64_to_float(common_hal_time_monotonic_ms()) / 1000.0f; mp_float_t wakeup_in_secs = MAX(0.0f, timealarm->monotonic_time - now_secs); - const uint64_t sleep_for_us = (uint64_t) (wakeup_in_secs * 1000000); + const uint64_t sleep_for_us = (uint64_t)(wakeup_in_secs * 1000000); esp_sleep_enable_timer_wakeup(sleep_for_us); // Also set the RTC interrupt so it can wake our task. This will be wiped out diff --git a/ports/esp32s2/common-hal/alarm/touch/TouchAlarm.c b/ports/esp32s2/common-hal/alarm/touch/TouchAlarm.c index 3095bc9e8b..8c139afaf3 100644 --- a/ports/esp32s2/common-hal/alarm/touch/TouchAlarm.c +++ b/ports/esp32s2/common-hal/alarm/touch/TouchAlarm.c @@ -62,7 +62,7 @@ mp_obj_t alarm_touch_touchalarm_get_wakeup_alarm(const size_t n_alarms, const mp // Map the pin number back to a pin object. for (size_t i = 0; i < mcu_pin_globals.map.used; i++) { - const mcu_pin_obj_t* pin_obj = MP_OBJ_TO_PTR(mcu_pin_globals.map.table[i].value); + const mcu_pin_obj_t *pin_obj = MP_OBJ_TO_PTR(mcu_pin_globals.map.table[i].value); if (pin_obj->touch_channel == wake_channel) { alarm->pin = mcu_pin_globals.map.table[i].value; break; @@ -74,7 +74,7 @@ mp_obj_t alarm_touch_touchalarm_get_wakeup_alarm(const size_t n_alarms, const mp // This is used to wake the main CircuitPython task. void touch_interrupt(void *arg) { - (void) arg; + (void)arg; woke_up = true; BaseType_t task_wakeup; vTaskNotifyGiveFromISR(circuitpython_task, &task_wakeup); @@ -121,7 +121,7 @@ void alarm_touch_touchalarm_set_alarm(const bool deep_sleep, const size_t n_alar // configure trigger threshold uint32_t touch_value; touch_pad_read_benchmark(touch_channel, &touch_value); - touch_pad_set_thresh(touch_channel, touch_value * 0.1); //10% + touch_pad_set_thresh(touch_channel, touch_value * 0.1); // 10% } } @@ -161,7 +161,7 @@ void alarm_touch_touchalarm_prepare_for_deep_sleep(void) { // configure trigger threshold uint32_t touch_value; touch_pad_sleep_channel_read_smooth(touch_channel, &touch_value); - touch_pad_sleep_set_threshold(touch_channel, touch_value * 0.1); //10% + touch_pad_sleep_set_threshold(touch_channel, touch_value * 0.1); // 10% // enable touchpad wakeup esp_sleep_enable_touchpad_wakeup(); diff --git a/ports/esp32s2/common-hal/analogio/AnalogIn.c b/ports/esp32s2/common-hal/analogio/AnalogIn.c index b2c09fc076..add4c3e14e 100644 --- a/ports/esp32s2/common-hal/analogio/AnalogIn.c +++ b/ports/esp32s2/common-hal/analogio/AnalogIn.c @@ -41,8 +41,8 @@ #define ATTENUATION ADC_ATTEN_DB_11 #define DATA_WIDTH ADC_WIDTH_BIT_13 -void common_hal_analogio_analogin_construct(analogio_analogin_obj_t* self, - const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, + const mcu_pin_obj_t *pin) { if (pin->adc_index == 0 || pin->adc_channel == ADC_CHANNEL_MAX) { mp_raise_ValueError(translate("Pin does not have ADC capabilities")); } @@ -78,14 +78,14 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { esp_adc_cal_characterize(self->pin->adc_index, ATTENUATION, DATA_WIDTH, DEFAULT_VREF, &adc_chars); uint32_t adc_reading = 0; - //Multisampling + // Multisampling for (int i = 0; i < NO_OF_SAMPLES; i++) { if (self->pin->adc_index == ADC_UNIT_1) { adc_reading += adc1_get_raw((adc1_channel_t)self->pin->adc_channel); } else { int raw; esp_err_t r = adc2_get_raw((adc2_channel_t)self->pin->adc_channel, DATA_WIDTH, &raw); - if ( r != ESP_OK ) { + if (r != ESP_OK) { mp_raise_ValueError(translate("ADC2 is being used by WiFi")); } adc_reading += raw; @@ -95,7 +95,7 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { // This corrects non-linear regions of the ADC range with a LUT, so it's a better reading than raw uint32_t voltage = esp_adc_cal_raw_to_voltage(adc_reading, &adc_chars); - return voltage * ((1 << 16) - 1)/3300; + return voltage * ((1 << 16) - 1) / 3300; } float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t *self) { diff --git a/ports/esp32s2/common-hal/analogio/AnalogIn.h b/ports/esp32s2/common-hal/analogio/AnalogIn.h index b9c4866f29..8c1f8a2ffb 100644 --- a/ports/esp32s2/common-hal/analogio/AnalogIn.h +++ b/ports/esp32s2/common-hal/analogio/AnalogIn.h @@ -36,7 +36,7 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t * pin; + const mcu_pin_obj_t *pin; } analogio_analogin_obj_t; #endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_ANALOGIO_ANALOGIN_H diff --git a/ports/esp32s2/common-hal/analogio/AnalogOut.c b/ports/esp32s2/common-hal/analogio/AnalogOut.c index 080a01b047..589c477a78 100644 --- a/ports/esp32s2/common-hal/analogio/AnalogOut.c +++ b/ports/esp32s2/common-hal/analogio/AnalogOut.c @@ -39,8 +39,8 @@ #include "common-hal/microcontroller/Pin.h" -void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, - const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, + const mcu_pin_obj_t *pin) { if (pin == &pin_GPIO17) { self->channel = DAC_CHANNEL_1; } else if (pin == &pin_GPIO18) { @@ -52,7 +52,7 @@ void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, } bool common_hal_analogio_analogout_deinited(analogio_analogout_obj_t *self) { - return (self->channel == DAC_CHANNEL_MAX); + return self->channel == DAC_CHANNEL_MAX; } void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { @@ -61,7 +61,7 @@ void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { } void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, - uint16_t value) { + uint16_t value) { uint8_t dac_value = (value * 255) / 65535; dac_output_enable(self->channel); dac_output_voltage(self->channel, dac_value); diff --git a/ports/esp32s2/common-hal/analogio/AnalogOut.h b/ports/esp32s2/common-hal/analogio/AnalogOut.h index 6285151ba0..6dc823ce53 100644 --- a/ports/esp32s2/common-hal/analogio/AnalogOut.h +++ b/ports/esp32s2/common-hal/analogio/AnalogOut.h @@ -34,7 +34,7 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t * pin; + const mcu_pin_obj_t *pin; uint8_t channel; } analogio_analogout_obj_t; diff --git a/ports/esp32s2/common-hal/audiobusio/I2SOut.c b/ports/esp32s2/common-hal/audiobusio/I2SOut.c index eb9b6f8e16..6548f46071 100644 --- a/ports/esp32s2/common-hal/audiobusio/I2SOut.c +++ b/ports/esp32s2/common-hal/audiobusio/I2SOut.c @@ -47,9 +47,9 @@ #include "driver/i2s.h" // Caller validates that pins are free. -void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, - const mcu_pin_obj_t* bit_clock, const mcu_pin_obj_t* word_select, - const mcu_pin_obj_t* data, bool left_justified) { +void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, + const mcu_pin_obj_t *bit_clock, const mcu_pin_obj_t *word_select, + const mcu_pin_obj_t *data, bool left_justified) { port_i2s_allocate_init(&self->peripheral, left_justified); @@ -68,11 +68,11 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, claim_pin(data); } -bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t *self) { return self->peripheral.instance == -1; } -void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self) { if (common_hal_audiobusio_i2sout_deinited(self)) { return; } @@ -98,31 +98,31 @@ void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { self->peripheral.instance = -1; } -void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, - mp_obj_t sample, bool loop) { +void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, + mp_obj_t sample, bool loop) { if (common_hal_audiobusio_i2sout_get_playing(self)) { common_hal_audiobusio_i2sout_stop(self); } port_i2s_play(&self->peripheral, sample, loop); } -void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t *self) { port_i2s_pause(&self->peripheral); } -void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t *self) { port_i2s_resume(&self->peripheral); } -bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t *self) { return port_i2s_paused(&self->peripheral); } -void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t *self) { port_i2s_stop(&self->peripheral); } -bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t *self) { return port_i2s_playing(&self->peripheral); } diff --git a/ports/esp32s2/common-hal/audiobusio/__init__.c b/ports/esp32s2/common-hal/audiobusio/__init__.c index 01c77c5313..60d00aaa61 100644 --- a/ports/esp32s2/common-hal/audiobusio/__init__.c +++ b/ports/esp32s2/common-hal/audiobusio/__init__.c @@ -42,10 +42,14 @@ static QueueHandle_t i2s_queues[I2S_NUM_MAX]; static TaskHandle_t i2s_tasks[I2S_NUM_MAX]; static int8_t port_i2s_allocate(void) { -#if defined(I2S_NUM_1) - if(!i2s_instance[1]) return 1; -#endif - if(!i2s_instance[0]) return 0; + #if defined(I2S_NUM_1) + if (!i2s_instance[1]) { + return 1; + } + #endif + if (!i2s_instance[0]) { + return 0; + } mp_raise_RuntimeError(translate("Peripheral in use")); } @@ -62,7 +66,7 @@ void port_i2s_reset_instance(int i) { } void i2s_reset(void) { - for (int i=0; i < I2S_NUM_MAX; i++) { + for (int i = 0; i < I2S_NUM_MAX; i++) { port_i2s_reset_instance(i); } } @@ -88,7 +92,7 @@ static void i2s_fill_buffer(i2s_t *self) { uint32_t sample_buffer_length; audioio_get_buffer_result_t get_buffer_result = audiosample_get_buffer(self->sample, false, 0, - &self->sample_data, &sample_buffer_length); + &self->sample_data, &sample_buffer_length); self->sample_end = self->sample_data + sample_buffer_length; if (get_buffer_result == GET_BUFFER_DONE) { if (self->loop) { @@ -118,27 +122,27 @@ static void i2s_fill_buffer(i2s_t *self) { if (self->samples_signed) { assert(self->channel_count == 1); if (self->bytes_per_sample == 1) { - audiosample_convert_s8m_s16s(signed_samples, (int8_t*)(void*)self->sample_data, framecount); + audiosample_convert_s8m_s16s(signed_samples, (int8_t *)(void *)self->sample_data, framecount); } else { - audiosample_convert_s16m_s16s(signed_samples, (int16_t*)(void*)self->sample_data, framecount); + audiosample_convert_s16m_s16s(signed_samples, (int16_t *)(void *)self->sample_data, framecount); } } else { if (self->channel_count == 1) { if (self->bytes_per_sample == 1) { - audiosample_convert_u8m_s16s(signed_samples, (uint8_t*)(void*)self->sample_data, framecount); + audiosample_convert_u8m_s16s(signed_samples, (uint8_t *)(void *)self->sample_data, framecount); } else { - audiosample_convert_u16m_s16s(signed_samples, (uint16_t*)(void*)self->sample_data, framecount); + audiosample_convert_u16m_s16s(signed_samples, (uint16_t *)(void *)self->sample_data, framecount); } } else { if (self->bytes_per_sample == 1) { - audiosample_convert_u8s_s16s(signed_samples, (uint8_t*)(void*)self->sample_data, framecount); + audiosample_convert_u8s_s16s(signed_samples, (uint8_t *)(void *)self->sample_data, framecount); } else { - audiosample_convert_u16s_s16s(signed_samples, (uint16_t*)(void*)self->sample_data, framecount); + audiosample_convert_u16s_s16s(signed_samples, (uint16_t *)(void *)self->sample_data, framecount); } } } size_t expanded_bytes_written = 0; - CHECK_ESP_RESULT(i2s_write(self->instance, signed_samples, bytes_per_output_frame*framecount, &expanded_bytes_written, 0)); + CHECK_ESP_RESULT(i2s_write(self->instance, signed_samples, bytes_per_output_frame * framecount, &expanded_bytes_written, 0)); assert(expanded_bytes_written % 4 == 0); bytes_written = expanded_bytes_written / bytes_per_output_frame * bytes_per_input_frame; } @@ -157,7 +161,7 @@ static void i2s_callback_fun(void *self_in) { static void i2s_event_task(void *self_in) { i2s_t *self = self_in; - while(true) { + while (true) { i2s_event_type_t event; BaseType_t result = xQueueReceive(i2s_queues[self->instance], &event, portMAX_DELAY); if (result && event == I2S_EVENT_TX_DONE) { @@ -199,7 +203,7 @@ void port_i2s_play(i2s_t *self, mp_obj_t sample, bool loop) { uint32_t max_buffer_length; uint8_t spacing; audiosample_get_buffer_structure(sample, false, &single_buffer, &samples_signed, - &max_buffer_length, &spacing); + &max_buffer_length, &spacing); self->samples_signed = samples_signed; self->playing = true; self->paused = false; diff --git a/ports/esp32s2/common-hal/busio/I2C.c b/ports/esp32s2/common-hal/busio/I2C.c index a1d0b8f9c4..d97ccd9f15 100644 --- a/ports/esp32s2/common-hal/busio/I2C.c +++ b/ports/esp32s2/common-hal/busio/I2C.c @@ -55,7 +55,7 @@ void i2c_reset(void) { } void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, - const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, uint32_t frequency, uint32_t timeout) { + const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint32_t frequency, uint32_t timeout) { // Pins 45 and 46 are "strapping" pins that impact start up behavior. They usually need to // be pulled-down so pulling them up for I2C is a bad idea. To make this hard, we don't // support I2C on these pins. @@ -65,7 +65,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, mp_raise_ValueError(translate("Invalid pins")); } -#if CIRCUITPY_REQUIRE_I2C_PULLUPS + #if CIRCUITPY_REQUIRE_I2C_PULLUPS // Test that the pins are in a high state. (Hopefully indicating they are pulled up.) gpio_set_direction(sda->number, GPIO_MODE_DEF_INPUT); gpio_set_direction(scl->number, GPIO_MODE_DEF_INPUT); @@ -86,7 +86,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, reset_pin_number(scl->number); mp_raise_RuntimeError(translate("No pull up found on SDA or SCL; check your wiring")); } -#endif + #endif if (xSemaphoreCreateMutexStatic(&self->semaphore) != &self->semaphore) { @@ -124,10 +124,10 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, } if (i2c_driver_install(self->i2c_num, - I2C_MODE_MASTER, - 0, - 0, - 0) != ESP_OK) { + I2C_MODE_MASTER, + 0, + 0, + 0) != ESP_OK) { mp_raise_OSError(MP_EIO); } @@ -182,11 +182,11 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { } uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, - const uint8_t *data, size_t len, bool transmit_stop_bit) { + const uint8_t *data, size_t len, bool transmit_stop_bit) { i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, addr << 1, true); - i2c_master_write(cmd, (uint8_t*) data, len, true); + i2c_master_write(cmd, (uint8_t *)data, len, true); if (transmit_stop_bit) { i2c_master_stop(cmd); } @@ -202,7 +202,7 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *data, size_t len) { + uint8_t *data, size_t len) { i2c_cmd_handle_t cmd = i2c_cmd_link_create(); i2c_master_start(cmd); i2c_master_write_byte(cmd, addr << 1 | 1, true); // | 1 to indicate read diff --git a/ports/esp32s2/common-hal/busio/I2C.h b/ports/esp32s2/common-hal/busio/I2C.h index 1a989e30a4..9629e7b18e 100644 --- a/ports/esp32s2/common-hal/busio/I2C.h +++ b/ports/esp32s2/common-hal/busio/I2C.h @@ -36,8 +36,8 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t* scl_pin; - const mcu_pin_obj_t* sda_pin; + const mcu_pin_obj_t *scl_pin; + const mcu_pin_obj_t *sda_pin; i2c_port_t i2c_num; StaticSemaphore_t semaphore; bool has_lock; diff --git a/ports/esp32s2/common-hal/busio/SPI.c b/ports/esp32s2/common-hal/busio/SPI.c index c4d54ec81c..917b391112 100644 --- a/ports/esp32s2/common-hal/busio/SPI.c +++ b/ports/esp32s2/common-hal/busio/SPI.c @@ -73,18 +73,27 @@ void spi_reset(void) { // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -static bool bus_uses_iomux_pins(spi_host_device_t host, const spi_bus_config_t* bus_config) -{ - if (bus_config->sclk_io_num>=0 && - bus_config->sclk_io_num != spi_periph_signal[host].spiclk_iomux_pin) return false; - if (bus_config->quadwp_io_num>=0 && - bus_config->quadwp_io_num != spi_periph_signal[host].spiwp_iomux_pin) return false; - if (bus_config->quadhd_io_num>=0 && - bus_config->quadhd_io_num != spi_periph_signal[host].spihd_iomux_pin) return false; +static bool bus_uses_iomux_pins(spi_host_device_t host, const spi_bus_config_t *bus_config) { + if (bus_config->sclk_io_num >= 0 && + bus_config->sclk_io_num != spi_periph_signal[host].spiclk_iomux_pin) { + return false; + } + if (bus_config->quadwp_io_num >= 0 && + bus_config->quadwp_io_num != spi_periph_signal[host].spiwp_iomux_pin) { + return false; + } + if (bus_config->quadhd_io_num >= 0 && + bus_config->quadhd_io_num != spi_periph_signal[host].spihd_iomux_pin) { + return false; + } if (bus_config->mosi_io_num >= 0 && - bus_config->mosi_io_num != spi_periph_signal[host].spid_iomux_pin) return false; - if (bus_config->miso_io_num>=0 && - bus_config->miso_io_num != spi_periph_signal[host].spiq_iomux_pin) return false; + bus_config->mosi_io_num != spi_periph_signal[host].spid_iomux_pin) { + return false; + } + if (bus_config->miso_io_num >= 0 && + bus_config->miso_io_num != spi_periph_signal[host].spiq_iomux_pin) { + return false; + } return true; } @@ -100,20 +109,18 @@ static void spi_interrupt_handler(void *arg) { } // The interrupt may get invoked by the bus lock. -static void spi_bus_intr_enable(void *self) -{ +static void spi_bus_intr_enable(void *self) { esp_intr_enable(((busio_spi_obj_t *)self)->interrupt); } // The interrupt is always disabled by the ISR itself, not exposed -static void spi_bus_intr_disable(void *self) -{ +static void spi_bus_intr_disable(void *self) { esp_intr_disable(((busio_spi_obj_t *)self)->interrupt); } void common_hal_busio_spi_construct(busio_spi_obj_t *self, - const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, - const mcu_pin_obj_t * miso) { + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso) { spi_bus_config_t bus_config; bus_config.mosi_io_num = mosi != NULL ? mosi->number : -1; @@ -123,8 +130,8 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, bus_config.quadhd_io_num = -1; bus_config.max_transfer_sz = 0; // Uses the default bus_config.flags = SPICOMMON_BUSFLAG_MASTER | SPICOMMON_BUSFLAG_SCLK | - (mosi != NULL ? SPICOMMON_BUSFLAG_MOSI : 0) | - (miso != NULL ? SPICOMMON_BUSFLAG_MISO : 0); + (mosi != NULL ? SPICOMMON_BUSFLAG_MOSI : 0) | + (miso != NULL ? SPICOMMON_BUSFLAG_MISO : 0); bus_config.intr_flags = 0; // RAM and Flash is often on SPI1 and is unsupported by the IDF so use it as @@ -161,8 +168,8 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, // The returned lock is stored in the bus lock but must be freed separately with // spi_bus_lock_unregister_dev. result = spi_bus_lock_register_dev(spi_bus_get_attr(host_id)->lock, - &config, - &self->lock); + &config, + &self->lock); if (result == ESP_ERR_NO_MEM) { common_hal_busio_spi_deinit(self); mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); @@ -170,8 +177,8 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, lock_dev_handle[host_id] = self->lock; result = esp_intr_alloc(spicommon_irqsource_for_host(host_id), - bus_config.intr_flags | ESP_INTR_FLAG_INTRDISABLED, - spi_interrupt_handler, self, &self->interrupt); + bus_config.intr_flags | ESP_INTR_FLAG_INTRDISABLED, + spi_interrupt_handler, self, &self->interrupt); if (result == ESP_ERR_NO_MEM) { common_hal_busio_spi_deinit(self); mp_raise_msg(&mp_type_MemoryError, translate("ESP-IDF memory allocation failed")); @@ -179,7 +186,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, intr_handle[host_id] = self->interrupt; spi_bus_lock_set_bg_control(spi_bus_get_attr(host_id)->lock, spi_bus_intr_enable, spi_bus_intr_disable, self); - spi_hal_context_t* hal = &self->hal_context; + spi_hal_context_t *hal = &self->hal_context; // spi_hal_init clears the given hal context so set everything after. spi_hal_init(hal, host_id); @@ -256,7 +263,7 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, - uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { + uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { if (baudrate == self->target_frequency && polarity == self->polarity && phase == self->phase && @@ -269,13 +276,13 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, self->bits = bits; self->target_frequency = baudrate; self->hal_context.timing_conf = &self->timing_conf; - esp_err_t result = spi_hal_get_clock_conf(&self->hal_context, - self->target_frequency, - 128 /* duty_cycle */, - self->connected_through_gpio, - 0 /* input_delay_ns */, - &self->real_frequency, - &self->timing_conf); + esp_err_t result = spi_hal_get_clock_conf(&self->hal_context, + self->target_frequency, + 128 /* duty_cycle */, + self->connected_through_gpio, + 0 /* input_delay_ns */, + &self->real_frequency, + &self->timing_conf); if (result != ESP_OK) { return false; } @@ -306,7 +313,7 @@ void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { } bool common_hal_busio_spi_write(busio_spi_obj_t *self, - const uint8_t *data, size_t len) { + const uint8_t *data, size_t len) { if (self->MOSI_pin == NULL) { mp_raise_ValueError(translate("No MOSI Pin")); } @@ -314,7 +321,7 @@ bool common_hal_busio_spi_write(busio_spi_obj_t *self, } bool common_hal_busio_spi_read(busio_spi_obj_t *self, - uint8_t *data, size_t len, uint8_t write_value) { + uint8_t *data, size_t len, uint8_t write_value) { if (self->MISO_pin == NULL) { mp_raise_ValueError(translate("No MISO Pin")); @@ -339,7 +346,7 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou mp_raise_ValueError(translate("No MISO Pin")); } - spi_hal_context_t* hal = &self->hal_context; + spi_hal_context_t *hal = &self->hal_context; hal->send_buffer = NULL; hal->rcv_buffer = NULL; // Reset timing_conf in case we've moved since the last time we used it. @@ -377,7 +384,7 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou hal->tx_bitlen = this_length * self->bits; hal->rx_bitlen = this_length * self->bits; if (data_out != NULL) { - hal->send_buffer = (uint8_t*) data_out + offset; + hal->send_buffer = (uint8_t *)data_out + offset; } if (data_in != NULL) { hal->rcv_buffer = data_in + offset; @@ -399,14 +406,14 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou return true; } -uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self) { +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { return self->real_frequency; } -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { return self->phase; } -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { return self->polarity; } diff --git a/ports/esp32s2/common-hal/busio/SPI.h b/ports/esp32s2/common-hal/busio/SPI.h index d6203feae6..488c0954ed 100644 --- a/ports/esp32s2/common-hal/busio/SPI.h +++ b/ports/esp32s2/common-hal/busio/SPI.h @@ -36,9 +36,9 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t* clock_pin; - const mcu_pin_obj_t* MOSI_pin; - const mcu_pin_obj_t* MISO_pin; + const mcu_pin_obj_t *clock_pin; + const mcu_pin_obj_t *MOSI_pin; + const mcu_pin_obj_t *MISO_pin; spi_host_device_t host_id; spi_bus_lock_dev_handle_t lock; spi_hal_context_t hal_context; diff --git a/ports/esp32s2/common-hal/busio/UART.c b/ports/esp32s2/common-hal/busio/UART.c index 98cebba67f..7da5c0f944 100644 --- a/ports/esp32s2/common-hal/busio/UART.c +++ b/ports/esp32s2/common-hal/busio/UART.c @@ -53,11 +53,11 @@ void uart_reset(void) { } void common_hal_busio_uart_construct(busio_uart_obj_t *self, - const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, - const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, - const mcu_pin_obj_t * rs485_dir, bool rs485_invert, + const mcu_pin_obj_t *tx, const mcu_pin_obj_t *rx, + const mcu_pin_obj_t *rts, const mcu_pin_obj_t *cts, + const mcu_pin_obj_t *rs485_dir, bool rs485_invert, uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, - mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, + mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { if (bits > 8) { @@ -163,7 +163,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, uart_set_parity(self->uart_num, parity_mode); // Stop is 1 or 2 always. - uart_stop_bits_t stop_bits= UART_STOP_BITS_1; + uart_stop_bits_t stop_bits = UART_STOP_BITS_1; if (stop == 2) { stop_bits = UART_STOP_BITS_2; } @@ -292,7 +292,7 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, } while (len > 0) { - int count = uart_tx_chars(self->uart_num, (const char*) data, len); + int count = uart_tx_chars(self->uart_num, (const char *)data, len); if (count < 0) { *errcode = MP_EAGAIN; return MP_STREAM_ERROR; @@ -322,7 +322,7 @@ void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrat } mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { - return (mp_float_t) (self->timeout_ms / 1000.0f); + return (mp_float_t)(self->timeout_ms / 1000.0f); } void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { diff --git a/ports/esp32s2/common-hal/busio/UART.h b/ports/esp32s2/common-hal/busio/UART.h index 751fb2e002..0d19221c8f 100644 --- a/ports/esp32s2/common-hal/busio/UART.h +++ b/ports/esp32s2/common-hal/busio/UART.h @@ -34,10 +34,10 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t* rx_pin; - const mcu_pin_obj_t* tx_pin; - const mcu_pin_obj_t* rts_pin; - const mcu_pin_obj_t* cts_pin; + const mcu_pin_obj_t *rx_pin; + const mcu_pin_obj_t *tx_pin; + const mcu_pin_obj_t *rts_pin; + const mcu_pin_obj_t *cts_pin; uart_port_t uart_num; uint8_t character_bits; bool rx_error; diff --git a/ports/esp32s2/common-hal/canio/CAN.c b/ports/esp32s2/common-hal/canio/CAN.c index 768fde2431..720034755b 100644 --- a/ports/esp32s2/common-hal/canio/CAN.c +++ b/ports/esp32s2/common-hal/canio/CAN.c @@ -39,89 +39,74 @@ STATIC bool reserved_can; twai_timing_config_t get_t_config(int baudrate) { - switch(baudrate) { - case 1000000: - { - // TWAI_TIMING_CONFIG_abc expands to a C designated initializer list - // { .brp = 4, ...}. This is only acceptable to the compiler as an - // initializer and 'return TWAI_TIMING_CONFIG_1MBITS()` is not valid. - // Instead, introduce a temporary, named variable and return it. - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_1MBITS(); - return t_config; - } - case 800000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_800KBITS(); - return t_config; - } - case 500000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS(); - return t_config; - } - case 250000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_250KBITS(); - return t_config; - } - case 125000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_125KBITS(); - return t_config; - } - case 100000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_100KBITS(); - return t_config; - } - case 50000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_50KBITS(); - return t_config; - } - case 25000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_25KBITS(); - return t_config; - } - case 20000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_20KBITS(); - return t_config; - } - case 16000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_16KBITS(); - return t_config; - } - case 12500: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_12_5KBITS(); - return t_config; - } - case 10000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_10KBITS(); - return t_config; - } - case 5000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_5KBITS(); - return t_config; - } - case 1000: - { - twai_timing_config_t t_config = TWAI_TIMING_CONFIG_1KBITS(); - return t_config; - } - default: - mp_raise_ValueError(translate("Baudrate not supported by peripheral")); + switch (baudrate) { + case 1000000: { + // TWAI_TIMING_CONFIG_abc expands to a C designated initializer list + // { .brp = 4, ...}. This is only acceptable to the compiler as an + // initializer and 'return TWAI_TIMING_CONFIG_1MBITS()` is not valid. + // Instead, introduce a temporary, named variable and return it. + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_1MBITS(); + return t_config; + } + case 800000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_800KBITS(); + return t_config; + } + case 500000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_500KBITS(); + return t_config; + } + case 250000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_250KBITS(); + return t_config; + } + case 125000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_125KBITS(); + return t_config; + } + case 100000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_100KBITS(); + return t_config; + } + case 50000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_50KBITS(); + return t_config; + } + case 25000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_25KBITS(); + return t_config; + } + case 20000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_20KBITS(); + return t_config; + } + case 16000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_16KBITS(); + return t_config; + } + case 12500: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_12_5KBITS(); + return t_config; + } + case 10000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_10KBITS(); + return t_config; + } + case 5000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_5KBITS(); + return t_config; + } + case 1000: { + twai_timing_config_t t_config = TWAI_TIMING_CONFIG_1KBITS(); + return t_config; + } + default: + mp_raise_ValueError(translate("Baudrate not supported by peripheral")); } } -void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mcu_pin_obj_t *rx, int baudrate, bool loopback, bool silent) -{ -#define DIV_ROUND(a, b) (((a) + (b)/2) / (b)) +void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mcu_pin_obj_t *rx, int baudrate, bool loopback, bool silent) { +#define DIV_ROUND(a, b) (((a) + (b) / 2) / (b)) #define DIV_ROUND_UP(a, b) (((a) + (b) - 1) / (b)) if (reserved_can) { mp_raise_ValueError(translate("All CAN peripherals are in use")); @@ -170,25 +155,21 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mc reserved_can = true; } -bool common_hal_canio_can_loopback_get(canio_can_obj_t *self) -{ +bool common_hal_canio_can_loopback_get(canio_can_obj_t *self) { return self->loopback; } -int common_hal_canio_can_baudrate_get(canio_can_obj_t *self) -{ +int common_hal_canio_can_baudrate_get(canio_can_obj_t *self) { return self->baudrate; } -int common_hal_canio_can_transmit_error_count_get(canio_can_obj_t *self) -{ +int common_hal_canio_can_transmit_error_count_get(canio_can_obj_t *self) { twai_status_info_t info; twai_get_status_info(&info); return info.tx_error_counter; } -int common_hal_canio_can_receive_error_count_get(canio_can_obj_t *self) -{ +int common_hal_canio_can_receive_error_count_get(canio_can_obj_t *self) { twai_status_info_t info; twai_get_status_info(&info); return info.rx_error_counter; @@ -224,7 +205,9 @@ static void can_restart(void) { } void canio_maybe_auto_restart(canio_can_obj_t *self) { - if (self->auto_restart) can_restart(); + if (self->auto_restart) { + can_restart(); + } } void common_hal_canio_can_restart(canio_can_obj_t *self) { @@ -242,8 +225,7 @@ void common_hal_canio_can_auto_restart_set(canio_can_obj_t *self, bool value) { canio_maybe_auto_restart(self); } -void common_hal_canio_can_send(canio_can_obj_t *self, mp_obj_t message_in) -{ +void common_hal_canio_can_send(canio_can_obj_t *self, mp_obj_t message_in) { canio_maybe_auto_restart(self); canio_message_obj_t *message = message_in; bool rtr = message->base.type == &canio_remote_transmission_request_type; @@ -275,8 +257,7 @@ void common_hal_canio_can_check_for_deinit(canio_can_obj_t *self) { } } -void common_hal_canio_can_deinit(canio_can_obj_t *self) -{ +void common_hal_canio_can_deinit(canio_can_obj_t *self) { if (self->tx_pin) { (void)twai_stop(); (void)twai_driver_uninstall(); diff --git a/ports/esp32s2/common-hal/canio/CAN.h b/ports/esp32s2/common-hal/canio/CAN.h index 85fb6972be..82f30bc6f1 100644 --- a/ports/esp32s2/common-hal/canio/CAN.h +++ b/ports/esp32s2/common-hal/canio/CAN.h @@ -42,8 +42,8 @@ typedef struct canio_can_obj { int baudrate; const mcu_pin_obj_t *rx_pin; const mcu_pin_obj_t *tx_pin; - bool loopback:1; - bool silent:1; - bool auto_restart:1; - bool fifo_in_use:1; + bool loopback : 1; + bool silent : 1; + bool auto_restart : 1; + bool fifo_in_use : 1; } canio_can_obj_t; diff --git a/ports/esp32s2/common-hal/canio/Listener.c b/ports/esp32s2/common-hal/canio/Listener.c index fddbfeb583..5e968f2393 100644 --- a/ports/esp32s2/common-hal/canio/Listener.c +++ b/ports/esp32s2/common-hal/canio/Listener.c @@ -41,16 +41,15 @@ // IDE = "extended ID" flag of packet header. We always add this bit to the // mask because a match is always for just one kind of address length -#define FILTER16_IDE (1<<3) -#define FILTER32_IDE (1<<2) +#define FILTER16_IDE (1 << 3) +#define FILTER32_IDE (1 << 2) // Work around a problem reported at // https://github.com/espressif/esp-idf/issues/6020 where // twai_ll_set_acc_filter does not work under -Os optimization __attribute__((optimize("O0"))) __attribute__((noinline)) -static void canio_set_acc_filter(twai_dev_t* hw, uint32_t code, uint32_t mask, bool single_filter) -{ +static void canio_set_acc_filter(twai_dev_t *hw, uint32_t code, uint32_t mask, bool single_filter) { uint32_t code_swapped = __builtin_bswap32(code); uint32_t mask_swapped = __builtin_bswap32(mask); for (int i = 0; i < 4; i++) { diff --git a/ports/esp32s2/common-hal/canio/Listener.h b/ports/esp32s2/common-hal/canio/Listener.h index d24900e435..cc8545e375 100644 --- a/ports/esp32s2/common-hal/canio/Listener.h +++ b/ports/esp32s2/common-hal/canio/Listener.h @@ -32,9 +32,9 @@ typedef struct canio_listener_obj { mp_obj_base_t base; canio_can_obj_t *can; - bool extended:1; - bool standard:1; - bool pending:1; + bool extended : 1; + bool standard : 1; + bool pending : 1; twai_message_t message_in; uint32_t timeout_ms; } canio_listener_obj_t; diff --git a/ports/esp32s2/common-hal/countio/Counter.c b/ports/esp32s2/common-hal/countio/Counter.c index fe52d93add..bdc8b290fe 100644 --- a/ports/esp32s2/common-hal/countio/Counter.c +++ b/ports/esp32s2/common-hal/countio/Counter.c @@ -30,8 +30,8 @@ #include "py/runtime.h" #include "supervisor/shared/translate.h" -void common_hal_countio_counter_construct(countio_counter_obj_t* self, - const mcu_pin_obj_t* pin) { +void common_hal_countio_counter_construct(countio_counter_obj_t *self, + const mcu_pin_obj_t *pin) { claim_pin(pin); // Prepare configuration for the PCNT unit @@ -55,11 +55,11 @@ void common_hal_countio_counter_construct(countio_counter_obj_t* self, self->unit = (pcnt_unit_t)unit; } -bool common_hal_countio_counter_deinited(countio_counter_obj_t* self) { +bool common_hal_countio_counter_deinited(countio_counter_obj_t *self) { return self->unit == PCNT_UNIT_MAX; } -void common_hal_countio_counter_deinit(countio_counter_obj_t* self) { +void common_hal_countio_counter_deinit(countio_counter_obj_t *self) { if (common_hal_countio_counter_deinited(self)) { return; } @@ -67,18 +67,18 @@ void common_hal_countio_counter_deinit(countio_counter_obj_t* self) { peripherals_pcnt_deinit(&self->unit); } -mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t* self) { +mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t *self) { int16_t count; pcnt_get_counter_value(self->unit, &count); - return count+self->count; + return count + self->count; } -void common_hal_countio_counter_set_count(countio_counter_obj_t* self, - mp_int_t new_count) { +void common_hal_countio_counter_set_count(countio_counter_obj_t *self, + mp_int_t new_count) { self->count = new_count; pcnt_counter_clear(self->unit); } -void common_hal_countio_counter_reset(countio_counter_obj_t* self) { - common_hal_countio_counter_set_count(self, 0); +void common_hal_countio_counter_reset(countio_counter_obj_t *self) { + common_hal_countio_counter_set_count(self, 0); } diff --git a/ports/esp32s2/common-hal/countio/__init__.c b/ports/esp32s2/common-hal/countio/__init__.c index b95b20d153..d47de33e53 100644 --- a/ports/esp32s2/common-hal/countio/__init__.c +++ b/ports/esp32s2/common-hal/countio/__init__.c @@ -1 +1 @@ -//No countio module functions +// No countio module functions diff --git a/ports/esp32s2/common-hal/digitalio/DigitalInOut.c b/ports/esp32s2/common-hal/digitalio/DigitalInOut.c index a2a0209f93..f2c40ce9ba 100644 --- a/ports/esp32s2/common-hal/digitalio/DigitalInOut.c +++ b/ports/esp32s2/common-hal/digitalio/DigitalInOut.c @@ -33,12 +33,12 @@ #include "components/soc/include/hal/gpio_hal.h" void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { never_reset_pin_number(self->pin->number); } digitalinout_result_t common_hal_digitalio_digitalinout_construct( - digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { + digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { claim_pin(pin); self->pin = pin; @@ -69,20 +69,20 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self } void common_hal_digitalio_digitalinout_switch_to_input( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { common_hal_digitalio_digitalinout_set_pull(self, pull); gpio_set_direction(self->pin->number, GPIO_MODE_DEF_INPUT); } digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( - digitalio_digitalinout_obj_t *self, bool value, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, bool value, + digitalio_drive_mode_t drive_mode) { common_hal_digitalio_digitalinout_set_value(self, value); return common_hal_digitalio_digitalinout_set_drive_mode(self, drive_mode); } digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { uint32_t iomux = READ_PERI_REG(GPIO_PIN_MUX_REG[self->pin->number]); if ((iomux & FUN_IE) != 0) { return DIRECTION_INPUT; @@ -91,13 +91,13 @@ digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( } void common_hal_digitalio_digitalinout_set_value( - digitalio_digitalinout_obj_t *self, bool value) { + digitalio_digitalinout_obj_t *self, bool value) { self->output_value = value; gpio_set_level(self->pin->number, value); } bool common_hal_digitalio_digitalinout_get_value( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { if (common_hal_digitalio_digitalinout_get_direction(self) == DIRECTION_INPUT) { return gpio_get_level(self->pin->number) == 1; } @@ -105,8 +105,8 @@ bool common_hal_digitalio_digitalinout_get_value( } digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( - digitalio_digitalinout_obj_t *self, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, + digitalio_drive_mode_t drive_mode) { gpio_num_t number = self->pin->number; gpio_mode_t mode; if (drive_mode == DRIVE_MODE_OPEN_DRAIN) { @@ -122,7 +122,7 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( } digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { if (GPIO_HAL_GET_HW(GPIO_PORT_0)->pin[self->pin->number].pad_driver == 1) { return DRIVE_MODE_OPEN_DRAIN; } @@ -130,7 +130,7 @@ digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( } void common_hal_digitalio_digitalinout_set_pull( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { gpio_num_t number = self->pin->number; gpio_pullup_dis(number); gpio_pulldown_dis(number); @@ -142,7 +142,7 @@ void common_hal_digitalio_digitalinout_set_pull( } digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { gpio_num_t gpio_num = self->pin->number; if (REG_GET_BIT(GPIO_PIN_MUX_REG[gpio_num], FUN_PU) == 1) { return PULL_UP; diff --git a/ports/esp32s2/common-hal/displayio/ParallelBus.c b/ports/esp32s2/common-hal/displayio/ParallelBus.c index f77b37b57c..5fd2be8522 100644 --- a/ports/esp32s2/common-hal/displayio/ParallelBus.c +++ b/ports/esp32s2/common-hal/displayio/ParallelBus.c @@ -38,9 +38,9 @@ * - data0 pin must be byte aligned */ -void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* self, - const mcu_pin_obj_t* data0, const mcu_pin_obj_t* command, const mcu_pin_obj_t* chip_select, - const mcu_pin_obj_t* write, const mcu_pin_obj_t* read, const mcu_pin_obj_t* reset) { +void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t *self, + const mcu_pin_obj_t *data0, const mcu_pin_obj_t *command, const mcu_pin_obj_t *chip_select, + const mcu_pin_obj_t *write, const mcu_pin_obj_t *read, const mcu_pin_obj_t *reset) { uint8_t data_pin = data0->number; if (data_pin % 8 != 0) { @@ -59,8 +59,8 @@ void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* sel // Enable pins with "enable_w1ts" for (uint8_t i = 0; i < 8; i++) { - g->enable_w1ts = (0x1 << (data_pin + i)); - g->func_out_sel_cfg[data_pin + i].val= 256; /* setup output pin for simple GPIO Output, (0x100 = 256) */ + g->enable_w1ts = (0x1 << (data_pin + i)); + g->func_out_sel_cfg[data_pin + i].val = 256; /* setup output pin for simple GPIO Output, (0x100 = 256) */ } @@ -70,10 +70,10 @@ void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* sel if (data_pin < 31) { - self->bus = (uint32_t*) &g->out; //pointer to GPIO output register (for pins 0-31) - } else { - self->bus = (uint32_t*) &g->out1.val; //pointer to GPIO output register (for pins >= 32) - } + self->bus = (uint32_t *)&g->out; // pointer to GPIO output register (for pins 0-31) + } else { + self->bus = (uint32_t *)&g->out1.val; // pointer to GPIO output register (for pins >= 32) + } /* SNIP - common setup of command, chip select, write and read pins, same as from SAMD and NRF ports */ self->command.base.type = &digitalio_digitalinout_type; @@ -95,20 +95,20 @@ void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* sel self->data0_pin = data_pin; if (write->number < 32) { - self->write_clear_register = (uint32_t*) &g->out_w1tc; - self->write_set_register = (uint32_t*) &g->out_w1ts; + self->write_clear_register = (uint32_t *)&g->out_w1tc; + self->write_set_register = (uint32_t *)&g->out_w1ts; } else { - self->write_clear_register = (uint32_t*) &g->out1_w1tc.val; - self->write_set_register = (uint32_t*) &g->out1_w1ts.val; + self->write_clear_register = (uint32_t *)&g->out1_w1tc.val; + self->write_set_register = (uint32_t *)&g->out1_w1ts.val; } // Check to see if the data and write pins are on the same register: - if ( ( ((self->data0_pin < 32) && (write->number < 32)) ) || - ( ((self->data0_pin > 31) && (write->number > 31)) ) ) { - self->data_write_same_register = true; // data pins and write pin are on the same register + if ((((self->data0_pin < 32) && (write->number < 32))) || + (((self->data0_pin > 31) && (write->number > 31)))) { + self->data_write_same_register = true; // data pins and write pin are on the same register } else { - self->data_write_same_register = false; // data pins and write pins are on different registers - } + self->data_write_same_register = false; // data pins and write pins are on different registers + } self->write_mask = 1 << (write->number % 32); /* the write pin triggers the LCD to latch the data */ @@ -133,8 +133,8 @@ void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* sel } -void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) { - /* SNIP - same as from SAMD and NRF ports */ +void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t *self) { + /* SNIP - same as from SAMD and NRF ports */ for (uint8_t i = 0; i < 8; i++) { reset_pin_number(self->data0_pin + i); } @@ -147,8 +147,8 @@ void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) } bool common_hal_displayio_parallelbus_reset(mp_obj_t obj) { - /* SNIP - same as from SAMD and NRF ports */ - displayio_parallelbus_obj_t* self = MP_OBJ_TO_PTR(obj); + /* SNIP - same as from SAMD and NRF ports */ + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); if (self->reset.base.type == &mp_type_NoneType) { return false; } @@ -161,24 +161,24 @@ bool common_hal_displayio_parallelbus_reset(mp_obj_t obj) { } bool common_hal_displayio_parallelbus_bus_free(mp_obj_t obj) { - /* SNIP - same as from SAMD and NRF ports */ + /* SNIP - same as from SAMD and NRF ports */ return true; } bool common_hal_displayio_parallelbus_begin_transaction(mp_obj_t obj) { - /* SNIP - same as from SAMD and NRF ports */ - displayio_parallelbus_obj_t* self = MP_OBJ_TO_PTR(obj); + /* SNIP - same as from SAMD and NRF ports */ + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_digitalio_digitalinout_set_value(&self->chip_select, false); return true; } void common_hal_displayio_parallelbus_send(mp_obj_t obj, display_byte_type_t byte_type, - display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { - displayio_parallelbus_obj_t* self = MP_OBJ_TO_PTR(obj); + display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_digitalio_digitalinout_set_value(&self->command, byte_type == DISPLAY_DATA); - uint32_t* clear_write = self->write_clear_register; - uint32_t* set_write = self->write_set_register; + uint32_t *clear_write = self->write_clear_register; + uint32_t *set_write = self->write_set_register; const uint32_t mask = self->write_mask; @@ -188,41 +188,40 @@ void common_hal_displayio_parallelbus_send(mp_obj_t obj, display_byte_type_t byt */ *clear_write = mask; // Clear the write pin to prepare the registers before storing the - // register value into data_buffer + // register value into data_buffer const uint32_t data_buffer = *self->bus; // store the initial output register values into the data output buffer - uint8_t* data_address = ((uint8_t*) &data_buffer) + (self->data0_pin / 8); /* address inside data_buffer where - * each data byte will be written to the data pin registers - */ + uint8_t *data_address = ((uint8_t *)&data_buffer) + (self->data0_pin / 8); /* address inside data_buffer where + * each data byte will be written to the data pin registers + */ - if ( self->data_write_same_register ) { // data and write pins are on the same register - for (uint32_t i = 0; i < data_length; i++) { + if (self->data_write_same_register) { // data and write pins are on the same register + for (uint32_t i = 0; i < data_length; i++) { - /* Note: If the write pin and data pins are controlled by the same GPIO register, we can eliminate - * the "clear_write" step below, since the write pin is cleared when the data_buffer is written - * to the bus. - */ + /* Note: If the write pin and data pins are controlled by the same GPIO register, we can eliminate + * the "clear_write" step below, since the write pin is cleared when the data_buffer is written + * to the bus. + */ - *(data_address) = data[i]; // stuff the data byte into the data_buffer at the correct offset byte location - *self->bus = data_buffer; // write the data to the output register - *set_write = mask; // set the write pin - } - } - else { // data and write pins are on different registers - for (uint32_t i = 0; i < data_length; i++) { - *clear_write = mask; // clear the write pin (See comment above, this may not be necessary). - *(data_address) = data[i]; // stuff the data byte into the data_buffer at the correct offset byte location - *self->bus = data_buffer; // write the data to the output register - *set_write = mask; // set the write pin + *(data_address) = data[i]; // stuff the data byte into the data_buffer at the correct offset byte location + *self->bus = data_buffer; // write the data to the output register + *set_write = mask; // set the write pin + } + } else { // data and write pins are on different registers + for (uint32_t i = 0; i < data_length; i++) { + *clear_write = mask; // clear the write pin (See comment above, this may not be necessary). + *(data_address) = data[i]; // stuff the data byte into the data_buffer at the correct offset byte location + *self->bus = data_buffer; // write the data to the output register + *set_write = mask; // set the write pin - } - } + } + } } void common_hal_displayio_parallelbus_end_transaction(mp_obj_t obj) { - /* SNIP - same as from SAMD and NRF ports */ - displayio_parallelbus_obj_t* self = MP_OBJ_TO_PTR(obj); + /* SNIP - same as from SAMD and NRF ports */ + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_digitalio_digitalinout_set_value(&self->chip_select, true); } diff --git a/ports/esp32s2/common-hal/displayio/ParallelBus.h b/ports/esp32s2/common-hal/displayio/ParallelBus.h index 84302118bd..59eb64f34d 100644 --- a/ports/esp32s2/common-hal/displayio/ParallelBus.h +++ b/ports/esp32s2/common-hal/displayio/ParallelBus.h @@ -31,7 +31,7 @@ typedef struct { mp_obj_base_t base; - uint32_t* bus; // pointer where 8 bits of data are written to the display + uint32_t *bus; // pointer where 8 bits of data are written to the display digitalio_digitalinout_obj_t command; digitalio_digitalinout_obj_t chip_select; digitalio_digitalinout_obj_t reset; @@ -39,8 +39,8 @@ typedef struct { digitalio_digitalinout_obj_t read; uint8_t data0_pin; // pin number for the lowest number data pin. Must be 8-bit aligned bool data_write_same_register; // if data and write pins are in the sare - uint32_t* write_set_register; // pointer to the write group for setting the write bit to latch the data on the LCD - uint32_t* write_clear_register; // pointer to the write group for clearing the write bit to latch the data on the LCD + uint32_t *write_set_register; // pointer to the write group for setting the write bit to latch the data on the LCD + uint32_t *write_clear_register; // pointer to the write group for clearing the write bit to latch the data on the LCD uint32_t write_mask; // bit mask for the single bit for the write pin register } displayio_parallelbus_obj_t; diff --git a/ports/esp32s2/common-hal/dualbank/__init__.c b/ports/esp32s2/common-hal/dualbank/__init__.c index 1414f131d1..04f5d6203d 100644 --- a/ports/esp32s2/common-hal/dualbank/__init__.c +++ b/ports/esp32s2/common-hal/dualbank/__init__.c @@ -62,10 +62,10 @@ void common_hal_dualbank_flash(const void *buf, const size_t len, const size_t o update_partition = esp_ota_get_next_update_partition(NULL); ESP_LOGI(TAG, "Running partition type %d subtype %d (offset 0x%08x)", - running->type, running->subtype, running->address); + running->type, running->subtype, running->address); ESP_LOGI(TAG, "Writing partition type %d subtype %d (offset 0x%08x)\n", - update_partition->type, update_partition->subtype, update_partition->address); + update_partition->type, update_partition->subtype, update_partition->address); assert(update_partition != NULL); } diff --git a/ports/esp32s2/common-hal/dualbank/__init__.h b/ports/esp32s2/common-hal/dualbank/__init__.h index 8b18336c94..eb325b9fb7 100644 --- a/ports/esp32s2/common-hal/dualbank/__init__.h +++ b/ports/esp32s2/common-hal/dualbank/__init__.h @@ -29,4 +29,4 @@ extern void dualbank_reset(void); -#endif //MICROPY_INCLUDED_ESP32S2_COMMON_HAL_DUALBANK___INIT___H +#endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_DUALBANK___INIT___H diff --git a/ports/esp32s2/common-hal/frequencyio/FrequencyIn.c b/ports/esp32s2/common-hal/frequencyio/FrequencyIn.c index 12d612abb0..cd13cddc66 100644 --- a/ports/esp32s2/common-hal/frequencyio/FrequencyIn.c +++ b/ports/esp32s2/common-hal/frequencyio/FrequencyIn.c @@ -29,7 +29,7 @@ #include "py/runtime.h" static void IRAM_ATTR pcnt_overflow_handler(void *self_in) { - frequencyio_frequencyin_obj_t * self = self_in; + frequencyio_frequencyin_obj_t *self = self_in; // reset counter pcnt_counter_clear(self->unit); @@ -41,7 +41,7 @@ static void IRAM_ATTR pcnt_overflow_handler(void *self_in) { } static void IRAM_ATTR timer_interrupt_handler(void *self_in) { - frequencyio_frequencyin_obj_t * self = self_in; + frequencyio_frequencyin_obj_t *self = self_in; // get counter value int16_t count; pcnt_get_counter_value(self->unit, &count); @@ -63,7 +63,7 @@ static void IRAM_ATTR timer_interrupt_handler(void *self_in) { device->hw_timer[self->timer.idx].config.alarm_en = 1; } -static void init_pcnt(frequencyio_frequencyin_obj_t* self) { +static void init_pcnt(frequencyio_frequencyin_obj_t *self) { // Prepare configuration for the PCNT unit const pcnt_config_t pcnt_config = { // Set PCNT input signal and control GPIOs @@ -95,7 +95,7 @@ static void init_pcnt(frequencyio_frequencyin_obj_t* self) { pcnt_intr_enable(self->unit); } -static void init_timer(frequencyio_frequencyin_obj_t* self) { +static void init_timer(frequencyio_frequencyin_obj_t *self) { // Prepare configuration for the timer module const timer_config_t config = { .alarm_en = true, @@ -124,8 +124,8 @@ static void init_timer(frequencyio_frequencyin_obj_t* self) { timer_start(self->timer.group, self->timer.idx); } -void common_hal_frequencyio_frequencyin_construct(frequencyio_frequencyin_obj_t* self, - const mcu_pin_obj_t* pin, const uint16_t capture_period) { +void common_hal_frequencyio_frequencyin_construct(frequencyio_frequencyin_obj_t *self, + const mcu_pin_obj_t *pin, const uint16_t capture_period) { if ((capture_period == 0) || (capture_period > 500)) { mp_raise_ValueError(translate("Invalid capture period. Valid range: 1 - 500")); } @@ -142,11 +142,11 @@ void common_hal_frequencyio_frequencyin_construct(frequencyio_frequencyin_obj_t* claim_pin(pin); } -bool common_hal_frequencyio_frequencyin_deinited(frequencyio_frequencyin_obj_t* self) { +bool common_hal_frequencyio_frequencyin_deinited(frequencyio_frequencyin_obj_t *self) { return self->unit == PCNT_UNIT_MAX; } -void common_hal_frequencyio_frequencyin_deinit(frequencyio_frequencyin_obj_t* self) { +void common_hal_frequencyio_frequencyin_deinit(frequencyio_frequencyin_obj_t *self) { if (common_hal_frequencyio_frequencyin_deinited(self)) { return; } @@ -159,21 +159,21 @@ void common_hal_frequencyio_frequencyin_deinit(frequencyio_frequencyin_obj_t* se } } -uint32_t common_hal_frequencyio_frequencyin_get_item(frequencyio_frequencyin_obj_t* self) { +uint32_t common_hal_frequencyio_frequencyin_get_item(frequencyio_frequencyin_obj_t *self) { return self->frequency; } -void common_hal_frequencyio_frequencyin_pause(frequencyio_frequencyin_obj_t* self) { +void common_hal_frequencyio_frequencyin_pause(frequencyio_frequencyin_obj_t *self) { pcnt_counter_pause(self->unit); timer_pause(self->timer.group, self->timer.idx); } -void common_hal_frequencyio_frequencyin_resume(frequencyio_frequencyin_obj_t* self) { +void common_hal_frequencyio_frequencyin_resume(frequencyio_frequencyin_obj_t *self) { pcnt_counter_resume(self->unit); timer_start(self->timer.group, self->timer.idx); } -void common_hal_frequencyio_frequencyin_clear(frequencyio_frequencyin_obj_t* self) { +void common_hal_frequencyio_frequencyin_clear(frequencyio_frequencyin_obj_t *self) { self->frequency = 0; pcnt_counter_clear(self->unit); timer_set_counter_value(self->timer.group, self->timer.idx, 0); diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.c b/ports/esp32s2/common-hal/microcontroller/Pin.c index ff6d0ed356..5c00ca49e1 100644 --- a/ports/esp32s2/common-hal/microcontroller/Pin.c +++ b/ports/esp32s2/common-hal/microcontroller/Pin.c @@ -59,20 +59,20 @@ STATIC void floating_gpio_reset(gpio_num_t pin_number) { } void never_reset_pin_number(gpio_num_t pin_number) { - if (pin_number == -1 ) { - return; + if (pin_number == -1) { + return; } never_reset_pins[pin_number / 32] |= 1 << pin_number % 32; } -void common_hal_never_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { never_reset_pin_number(pin->number); } // Mark pin as free and return it to a quiescent state. void reset_pin_number(gpio_num_t pin_number) { - if (pin_number == -1 ) { - return; + if (pin_number == -1) { + return; } never_reset_pins[pin_number / 32] &= ~(1 << pin_number % 32); in_use[pin_number / 32] &= ~(1 << pin_number % 32); @@ -88,7 +88,7 @@ void reset_pin_number(gpio_num_t pin_number) { #endif } -void common_hal_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_reset_pin(const mcu_pin_obj_t *pin) { if (pin == NULL) { return; } @@ -112,7 +112,7 @@ void reset_all_pins(void) { #endif } -void claim_pin(const mcu_pin_obj_t* pin) { +void claim_pin(const mcu_pin_obj_t *pin) { in_use[pin->number / 32] |= (1 << (pin->number % 32)); #ifdef MICROPY_HW_NEOPIXEL if (pin == MICROPY_HW_NEOPIXEL) { @@ -121,7 +121,7 @@ void claim_pin(const mcu_pin_obj_t* pin) { #endif } -void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) { +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { claim_pin(pin); } diff --git a/ports/esp32s2/common-hal/microcontroller/Pin.h b/ports/esp32s2/common-hal/microcontroller/Pin.h index f6c0087031..e7b488f048 100644 --- a/ports/esp32s2/common-hal/microcontroller/Pin.h +++ b/ports/esp32s2/common-hal/microcontroller/Pin.h @@ -42,8 +42,8 @@ void reset_all_pins(void); // reset_pin_number takes the pin number instead of the pointer so that objects don't // need to store a full pointer. void reset_pin_number(gpio_num_t pin_number); -void common_hal_reset_pin(const mcu_pin_obj_t* pin); -void claim_pin(const mcu_pin_obj_t* pin); +void common_hal_reset_pin(const mcu_pin_obj_t *pin); +void claim_pin(const mcu_pin_obj_t *pin); bool pin_number_is_free(gpio_num_t pin_number); void never_reset_pin_number(gpio_num_t pin_number); diff --git a/ports/esp32s2/common-hal/microcontroller/Processor.c b/ports/esp32s2/common-hal/microcontroller/Processor.c index fffd1a1b19..eb65f2d101 100644 --- a/ports/esp32s2/common-hal/microcontroller/Processor.c +++ b/ports/esp32s2/common-hal/microcontroller/Processor.c @@ -66,17 +66,21 @@ STATIC uint8_t swap_nibbles(uint8_t v) { void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { memset(raw_id, 0, COMMON_HAL_MCU_PROCESSOR_UID_LENGTH); - uint8_t *ptr = &raw_id[COMMON_HAL_MCU_PROCESSOR_UID_LENGTH-1]; + uint8_t *ptr = &raw_id[COMMON_HAL_MCU_PROCESSOR_UID_LENGTH - 1]; // MAC address contains 48 bits (6 bytes), 32 in the low order word uint32_t mac_address_part = REG_READ(EFUSE_RD_MAC_SPI_SYS_0_REG); - *ptr-- = swap_nibbles(mac_address_part & 0xff); mac_address_part >>= 8; - *ptr-- = swap_nibbles(mac_address_part & 0xff); mac_address_part >>= 8; - *ptr-- = swap_nibbles(mac_address_part & 0xff); mac_address_part >>= 8; + *ptr-- = swap_nibbles(mac_address_part & 0xff); + mac_address_part >>= 8; + *ptr-- = swap_nibbles(mac_address_part & 0xff); + mac_address_part >>= 8; + *ptr-- = swap_nibbles(mac_address_part & 0xff); + mac_address_part >>= 8; *ptr-- = swap_nibbles(mac_address_part & 0xff); // and 16 in the high order word mac_address_part = REG_READ(EFUSE_RD_MAC_SPI_SYS_1_REG); - *ptr-- = swap_nibbles(mac_address_part & 0xff); mac_address_part >>= 8; + *ptr-- = swap_nibbles(mac_address_part & 0xff); + mac_address_part >>= 8; *ptr-- = swap_nibbles(mac_address_part & 0xff); } diff --git a/ports/esp32s2/common-hal/microcontroller/__init__.c b/ports/esp32s2/common-hal/microcontroller/__init__.c index e425cbf543..85eb0b522b 100644 --- a/ports/esp32s2/common-hal/microcontroller/__init__.c +++ b/ports/esp32s2/common-hal/microcontroller/__init__.c @@ -68,12 +68,13 @@ void common_hal_mcu_enable_interrupts(void) { } void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { - if(runmode == RUNMODE_SAFE_MODE) + if (runmode == RUNMODE_SAFE_MODE) { safe_mode_on_next_reset(PROGRAMMATIC_SAFE_MODE); + } } void common_hal_mcu_reset(void) { - filesystem_flush(); //TODO: implement as part of flash improvements + filesystem_flush(); // TODO: implement as part of flash improvements esp_restart(); } @@ -91,7 +92,7 @@ const nvm_bytearray_obj_t common_hal_mcu_nvm_obj = { .base = { .type = &nvm_bytearray_type, }, - .start_address = (uint8_t*) CIRCUITPY_INTERNAL_NVM_START_ADDR, + .start_address = (uint8_t *)CIRCUITPY_INTERNAL_NVM_START_ADDR, .len = CIRCUITPY_INTERNAL_NVM_SIZE, }; #endif diff --git a/ports/esp32s2/common-hal/neopixel_write/__init__.c b/ports/esp32s2/common-hal/neopixel_write/__init__.c index 63d50bf14a..89d90ae996 100644 --- a/ports/esp32s2/common-hal/neopixel_write/__init__.c +++ b/ports/esp32s2/common-hal/neopixel_write/__init__.c @@ -58,15 +58,14 @@ static uint32_t ws2812_t0l_ticks = 0; static uint32_t ws2812_t1l_ticks = 0; static void IRAM_ATTR ws2812_rmt_adapter(const void *src, rmt_item32_t *dest, size_t src_size, - size_t wanted_num, size_t *translated_size, size_t *item_num) -{ + size_t wanted_num, size_t *translated_size, size_t *item_num) { if (src == NULL || dest == NULL) { *translated_size = 0; *item_num = 0; return; } - const rmt_item32_t bit0 = {{{ ws2812_t0h_ticks, 1, ws2812_t0l_ticks, 0 }}}; //Logical 0 - const rmt_item32_t bit1 = {{{ ws2812_t1h_ticks, 1, ws2812_t1l_ticks, 0 }}}; //Logical 1 + const rmt_item32_t bit0 = {{{ ws2812_t0h_ticks, 1, ws2812_t0l_ticks, 0 }}}; // Logical 0 + const rmt_item32_t bit1 = {{{ ws2812_t1h_ticks, 1, ws2812_t1l_ticks, 0 }}}; // Logical 1 size_t size = 0; size_t num = 0; uint8_t *psrc = (uint8_t *)src; @@ -75,9 +74,9 @@ static void IRAM_ATTR ws2812_rmt_adapter(const void *src, rmt_item32_t *dest, si for (int i = 0; i < 8; i++) { // MSB first if (*psrc & (1 << (7 - i))) { - pdest->val = bit1.val; + pdest->val = bit1.val; } else { - pdest->val = bit0.val; + pdest->val = bit0.val; } num++; pdest++; @@ -89,7 +88,7 @@ static void IRAM_ATTR ws2812_rmt_adapter(const void *src, rmt_item32_t *dest, si *item_num = num; } -void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout, uint8_t *pixels, uint32_t numBytes) { +void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, uint8_t *pixels, uint32_t numBytes) { // Reserve channel uint8_t number = digitalinout->pin->number; rmt_channel_t channel = esp32s2_peripherals_find_and_reserve_rmt(); @@ -118,7 +117,7 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout rmt_translator_init(config.channel, ws2812_rmt_adapter); // Write and wait to finish - if(rmt_write_sample(config.channel, pixels, (size_t)numBytes, true) != ESP_OK) { + if (rmt_write_sample(config.channel, pixels, (size_t)numBytes, true) != ESP_OK) { mp_raise_RuntimeError(translate("Input/output error")); } rmt_wait_tx_done(config.channel, pdMS_TO_TICKS(100)); diff --git a/ports/esp32s2/common-hal/nvm/ByteArray.c b/ports/esp32s2/common-hal/nvm/ByteArray.c index 71321e7e65..3130873792 100644 --- a/ports/esp32s2/common-hal/nvm/ByteArray.c +++ b/ports/esp32s2/common-hal/nvm/ByteArray.c @@ -33,7 +33,7 @@ uint32_t common_hal_nvm_bytearray_get_length(nvm_bytearray_obj_t *self) { return self->len; } -static void get_nvs_handle(nvs_handle_t * nvs_handle) { +static void get_nvs_handle(nvs_handle_t *nvs_handle) { // Initialize NVS esp_err_t err = nvs_flash_init(); if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) { @@ -51,7 +51,7 @@ static void get_nvs_handle(nvs_handle_t * nvs_handle) { } bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, - uint32_t start_index, uint8_t* values, uint32_t len) { + uint32_t start_index, uint8_t *values, uint32_t len) { char index[9]; // start nvs @@ -77,7 +77,7 @@ bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, } void common_hal_nvm_bytearray_get_bytes(nvm_bytearray_obj_t *self, - uint32_t start_index, uint32_t len, uint8_t* values) { + uint32_t start_index, uint32_t len, uint8_t *values) { char index[9]; // start nvs diff --git a/ports/esp32s2/common-hal/nvm/ByteArray.h b/ports/esp32s2/common-hal/nvm/ByteArray.h index 44b63d7241..3bd5191fcd 100644 --- a/ports/esp32s2/common-hal/nvm/ByteArray.h +++ b/ports/esp32s2/common-hal/nvm/ByteArray.h @@ -31,7 +31,7 @@ typedef struct { mp_obj_base_t base; - uint8_t* start_address; + uint8_t *start_address; uint32_t len; } nvm_bytearray_obj_t; diff --git a/ports/esp32s2/common-hal/os/__init__.c b/ports/esp32s2/common-hal/os/__init__.c index 4d6a6a2bfc..ee53bec04b 100644 --- a/ports/esp32s2/common-hal/os/__init__.c +++ b/ports/esp32s2/common-hal/os/__init__.c @@ -52,13 +52,13 @@ STATIC MP_DEFINE_ATTRTUPLE( (mp_obj_t)&os_uname_info_release_obj, (mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj -); + ); mp_obj_t common_hal_os_uname(void) { return (mp_obj_t)&os_uname_info_obj; } -bool common_hal_os_urandom(uint8_t* buffer, uint32_t length) { +bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { uint32_t i = 0; while (i < length) { uint32_t new_random = esp_random(); diff --git a/ports/esp32s2/common-hal/ps2io/Ps2.c b/ports/esp32s2/common-hal/ps2io/Ps2.c index 003f0d827e..f4845b0fa8 100644 --- a/ports/esp32s2/common-hal/ps2io/Ps2.c +++ b/ports/esp32s2/common-hal/ps2io/Ps2.c @@ -62,7 +62,7 @@ static void IRAM_ATTR ps2_interrupt_handler(void *self_in) { // Grab the current time first. uint64_t current_tick = port_get_raw_ticks(NULL); - ps2io_ps2_obj_t * self = self_in; + ps2io_ps2_obj_t *self = self_in; int data_bit = gpio_get_level(self->data_pin) ? 1 : 0; // test for timeout @@ -85,7 +85,7 @@ static void IRAM_ATTR ps2_interrupt_handler(void *self_in) { // start bit should be 0 self->last_errors |= ERROR_STARTBIT; self->state = STATE_RECV_ERR; - } else { + } else { self->state = STATE_RECV; } @@ -113,7 +113,7 @@ static void IRAM_ATTR ps2_interrupt_handler(void *self_in) { } else if (self->state == STATE_RECV_STOP) { ++self->bitcount; - if (! data_bit) { + if (!data_bit) { self->last_errors |= ERROR_STOPBIT; } else if (self->waiting_cmd_response) { self->cmd_response = self->bits; @@ -135,31 +135,31 @@ static void IRAM_ATTR ps2_interrupt_handler(void *self_in) { } } -static void enable_interrupt(ps2io_ps2_obj_t* self) { +static void enable_interrupt(ps2io_ps2_obj_t *self) { // turn on falling edge interrupt gpio_install_isr_service(ESP_INTR_FLAG_IRAM); gpio_set_intr_type(self->clk_pin, GPIO_INTR_NEGEDGE); - gpio_isr_handler_add(self->clk_pin, ps2_interrupt_handler, (void*)self); + gpio_isr_handler_add(self->clk_pin, ps2_interrupt_handler, (void *)self); } -static void disable_interrupt(ps2io_ps2_obj_t* self) { +static void disable_interrupt(ps2io_ps2_obj_t *self) { // turn off fallling edge interrupt gpio_isr_handler_remove(self->clk_pin); } -static void resume_interrupt(ps2io_ps2_obj_t* self) { +static void resume_interrupt(ps2io_ps2_obj_t *self) { self->state = STATE_IDLE; - gpio_isr_handler_add(self->clk_pin, ps2_interrupt_handler, (void*)self); + gpio_isr_handler_add(self->clk_pin, ps2_interrupt_handler, (void *)self); } /* gpio handling */ -static void clk_hi(ps2io_ps2_obj_t* self) { +static void clk_hi(ps2io_ps2_obj_t *self) { // external pull-up gpio_set_direction(self->clk_pin, GPIO_MODE_INPUT); } -static bool wait_clk_lo(ps2io_ps2_obj_t* self, uint32_t us) { +static bool wait_clk_lo(ps2io_ps2_obj_t *self, uint32_t us) { clk_hi(self); delay_us(1); while (gpio_get_level(self->clk_pin) && us) { @@ -169,7 +169,7 @@ static bool wait_clk_lo(ps2io_ps2_obj_t* self, uint32_t us) { return us; } -static bool wait_clk_hi(ps2io_ps2_obj_t* self, uint32_t us) { +static bool wait_clk_hi(ps2io_ps2_obj_t *self, uint32_t us) { clk_hi(self); delay_us(1); while (!gpio_get_level(self->clk_pin) && us) { @@ -179,17 +179,17 @@ static bool wait_clk_hi(ps2io_ps2_obj_t* self, uint32_t us) { return us; } -static void clk_lo(ps2io_ps2_obj_t* self) { +static void clk_lo(ps2io_ps2_obj_t *self) { gpio_set_direction(self->clk_pin, GPIO_MODE_OUTPUT); gpio_set_level(self->clk_pin, 0); } -static void data_hi(ps2io_ps2_obj_t* self) { +static void data_hi(ps2io_ps2_obj_t *self) { // external pull-up gpio_set_direction(self->data_pin, GPIO_MODE_INPUT); } -static bool wait_data_lo(ps2io_ps2_obj_t* self, uint32_t us) { +static bool wait_data_lo(ps2io_ps2_obj_t *self, uint32_t us) { data_hi(self); delay_us(1); while (gpio_get_level(self->data_pin) && us) { @@ -199,7 +199,7 @@ static bool wait_data_lo(ps2io_ps2_obj_t* self, uint32_t us) { return us; } -static bool wait_data_hi(ps2io_ps2_obj_t* self, uint32_t us) { +static bool wait_data_hi(ps2io_ps2_obj_t *self, uint32_t us) { data_hi(self); delay_us(1); while (!gpio_get_level(self->data_pin) && us) { @@ -209,25 +209,25 @@ static bool wait_data_hi(ps2io_ps2_obj_t* self, uint32_t us) { return us; } -static void data_lo(ps2io_ps2_obj_t* self) { +static void data_lo(ps2io_ps2_obj_t *self) { gpio_set_direction(self->data_pin, GPIO_MODE_OUTPUT); gpio_set_level(self->data_pin, 0); } -static void idle(ps2io_ps2_obj_t* self) { +static void idle(ps2io_ps2_obj_t *self) { clk_hi(self); data_hi(self); } -static void inhibit(ps2io_ps2_obj_t* self) { +static void inhibit(ps2io_ps2_obj_t *self) { clk_lo(self); data_hi(self); } /* ps2io module functions */ -void common_hal_ps2io_ps2_construct(ps2io_ps2_obj_t* self, - const mcu_pin_obj_t* data_pin, const mcu_pin_obj_t* clk_pin) { +void common_hal_ps2io_ps2_construct(ps2io_ps2_obj_t *self, + const mcu_pin_obj_t *data_pin, const mcu_pin_obj_t *clk_pin) { self->clk_pin = (gpio_num_t)clk_pin->number; self->data_pin = (gpio_num_t)data_pin->number; self->state = STATE_IDLE; @@ -243,11 +243,11 @@ void common_hal_ps2io_ps2_construct(ps2io_ps2_obj_t* self, claim_pin(data_pin); } -bool common_hal_ps2io_ps2_deinited(ps2io_ps2_obj_t* self) { +bool common_hal_ps2io_ps2_deinited(ps2io_ps2_obj_t *self) { return self->clk_pin == GPIO_NUM_MAX; } -void common_hal_ps2io_ps2_deinit(ps2io_ps2_obj_t* self) { +void common_hal_ps2io_ps2_deinit(ps2io_ps2_obj_t *self) { if (common_hal_ps2io_ps2_deinited(self)) { return; } @@ -258,11 +258,11 @@ void common_hal_ps2io_ps2_deinit(ps2io_ps2_obj_t* self) { self->data_pin = GPIO_NUM_MAX; } -uint16_t common_hal_ps2io_ps2_get_len(ps2io_ps2_obj_t* self) { +uint16_t common_hal_ps2io_ps2_get_len(ps2io_ps2_obj_t *self) { return self->bufcount; } -int16_t common_hal_ps2io_ps2_popleft(ps2io_ps2_obj_t* self) { +int16_t common_hal_ps2io_ps2_popleft(ps2io_ps2_obj_t *self) { common_hal_mcu_disable_interrupts(); if (self->bufcount <= 0) { common_hal_mcu_enable_interrupts(); @@ -275,7 +275,7 @@ int16_t common_hal_ps2io_ps2_popleft(ps2io_ps2_obj_t* self) { return b; } -uint16_t common_hal_ps2io_ps2_clear_errors(ps2io_ps2_obj_t* self) { +uint16_t common_hal_ps2io_ps2_clear_errors(ps2io_ps2_obj_t *self) { common_hal_mcu_disable_interrupts(); uint16_t errors = self->last_errors; self->last_errors = 0; @@ -286,7 +286,7 @@ uint16_t common_hal_ps2io_ps2_clear_errors(ps2io_ps2_obj_t* self) { // Based upon TMK implementation of PS/2 protocol // https://github.com/tmk/tmk_keyboard/blob/master/tmk_core/protocol/ps2_interrupt.c -int16_t common_hal_ps2io_ps2_sendcmd(ps2io_ps2_obj_t* self, uint8_t b) { +int16_t common_hal_ps2io_ps2_sendcmd(ps2io_ps2_obj_t *self, uint8_t b) { disable_interrupt(self); /* terminate a transmission if we have */ diff --git a/ports/esp32s2/common-hal/pulseio/PulseIn.c b/ports/esp32s2/common-hal/pulseio/PulseIn.c index 9feeea1479..a9533179bb 100644 --- a/ports/esp32s2/common-hal/pulseio/PulseIn.c +++ b/ports/esp32s2/common-hal/pulseio/PulseIn.c @@ -29,21 +29,21 @@ #include "py/runtime.h" STATIC uint8_t refcount = 0; -STATIC pulseio_pulsein_obj_t * handles[RMT_CHANNEL_MAX]; +STATIC pulseio_pulsein_obj_t *handles[RMT_CHANNEL_MAX]; // Requires rmt.c void esp32s2_peripherals_reset_all(void) to reset -STATIC void update_internal_buffer(pulseio_pulsein_obj_t* self) { +STATIC void update_internal_buffer(pulseio_pulsein_obj_t *self) { uint32_t length = 0; - rmt_item32_t *items = (rmt_item32_t *) xRingbufferReceive(self->buf_handle, &length, 0); + rmt_item32_t *items = (rmt_item32_t *)xRingbufferReceive(self->buf_handle, &length, 0); if (items) { length /= 4; - for (size_t i=0; i < length; i++) { + for (size_t i = 0; i < length; i++) { uint16_t pos = (self->start + self->len) % self->maxlen; self->buffer[pos] = items[i].duration0 * 3; // Check if second item exists before incrementing if (items[i].duration1) { - self->buffer[pos+1] = items[i].duration1 * 3; + self->buffer[pos + 1] = items[i].duration1 * 3; if (self->len < (self->maxlen - 1)) { self->len += 2; } else { @@ -57,7 +57,7 @@ STATIC void update_internal_buffer(pulseio_pulsein_obj_t* self) { } } } - vRingbufferReturnItem(self->buf_handle, (void *) items); + vRingbufferReturnItem(self->buf_handle, (void *)items); } } @@ -83,9 +83,9 @@ void pulsein_reset(void) { refcount = 0; } -void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu_pin_obj_t* pin, - uint16_t maxlen, bool idle_state) { - self->buffer = (uint16_t *) m_malloc(maxlen * sizeof(uint16_t), false); +void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin, + uint16_t maxlen, bool idle_state) { + self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t), false); if (self->buffer == NULL) { mp_raise_msg_varg(&mp_type_MemoryError, translate("Failed to allocate RX buffer of %d bytes"), maxlen * sizeof(uint16_t)); } @@ -115,7 +115,7 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu config.rx_config.idle_threshold = 30000; // 30*3=90ms idle required to register a sequence config.clk_div = 240; // All measurements are divided by 3 to accomodate 65ms pulses rmt_config(&config); - rmt_driver_install(channel, 1000, 0); //TODO: pick a more specific buffer size? + rmt_driver_install(channel, 1000, 0); // TODO: pick a more specific buffer size? // Store this object and the buffer handle for background updates self->channel = channel; @@ -130,11 +130,11 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu } } -bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t* self) { +bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self) { return handles[self->channel] ? false : true; } -void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { handles[self->channel] = NULL; esp32s2_peripherals_free_rmt(self->channel); reset_pin_number(self->pin->number); @@ -144,14 +144,14 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { } } -void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self) { self->paused = true; rmt_rx_stop(self->channel); } -void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, uint16_t trigger_duration) { +void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t *self, uint16_t trigger_duration) { // Make sure we're paused. - if ( !self->paused ) { + if (!self->paused) { common_hal_pulseio_pulsein_pause(self); } @@ -167,13 +167,13 @@ void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, uint16_t tri rmt_rx_start(self->channel, false); } -void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t *self) { // Buffer only updates in BG tasks or fetches, so no extra protection is needed self->start = 0; self->len = 0; } -uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, int16_t index) { +uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t *self, int16_t index) { update_internal_buffer(self); if (index < 0) { index += self->len; @@ -185,7 +185,7 @@ uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, int16_ return value; } -uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t *self) { update_internal_buffer(self); if (self->len == 0) { @@ -199,14 +199,14 @@ uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { return value; } -uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t *self) { return self->maxlen; } -bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t* self) { +bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t *self) { return self->paused; } -uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t *self) { return self->len; } diff --git a/ports/esp32s2/common-hal/pulseio/PulseIn.h b/ports/esp32s2/common-hal/pulseio/PulseIn.h index 289605ed05..3afd8db250 100644 --- a/ports/esp32s2/common-hal/pulseio/PulseIn.h +++ b/ports/esp32s2/common-hal/pulseio/PulseIn.h @@ -36,14 +36,14 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t* pin; + const mcu_pin_obj_t *pin; rmt_channel_t channel; bool idle_state; bool paused; RingbufHandle_t buf_handle; - uint16_t* buffer; + uint16_t *buffer; uint16_t maxlen; volatile uint16_t start; diff --git a/ports/esp32s2/common-hal/pulseio/PulseOut.c b/ports/esp32s2/common-hal/pulseio/PulseOut.c index e45492a893..d3490d1810 100644 --- a/ports/esp32s2/common-hal/pulseio/PulseOut.c +++ b/ports/esp32s2/common-hal/pulseio/PulseOut.c @@ -31,11 +31,11 @@ // Requires rmt.c void esp32s2_peripherals_reset_all(void) to reset -void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, - const pwmio_pwmout_obj_t* carrier, - const mcu_pin_obj_t* pin, - uint32_t frequency, - uint16_t duty_cycle) { +void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, + const pwmio_pwmout_obj_t *carrier, + const mcu_pin_obj_t *pin, + uint32_t frequency, + uint16_t duty_cycle) { if (carrier || !pin || !frequency) { mp_raise_NotImplementedError(translate("Port does not accept PWM carrier. Pass a pin, frequency and duty cycle instead")); } @@ -48,7 +48,7 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, // Configure Channel rmt_config_t config = RMT_DEFAULT_CONFIG_TX(pin->number, channel); config.tx_config.carrier_en = true; - config.tx_config.carrier_duty_percent = (duty_cycle * 100) / (1<<16); + config.tx_config.carrier_duty_percent = (duty_cycle * 100) / (1 << 16); config.tx_config.carrier_freq_hz = frequency; config.clk_div = 80; @@ -58,17 +58,17 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, self->channel = channel; } -bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t* self) { - return (self->channel == RMT_CHANNEL_MAX); +bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t *self) { + return self->channel == RMT_CHANNEL_MAX; } -void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { +void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { esp32s2_peripherals_free_rmt(self->channel); self->channel = RMT_CHANNEL_MAX; } -void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pulses, uint16_t length) { +void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pulses, uint16_t length) { rmt_item32_t items[length]; // Circuitpython allows 16 bit pulse values, while ESP32 only allows 15 bits diff --git a/ports/esp32s2/common-hal/pwmio/PWMOut.c b/ports/esp32s2/common-hal/pwmio/PWMOut.c index e1fdd4760a..81af22606c 100644 --- a/ports/esp32s2/common-hal/pwmio/PWMOut.c +++ b/ports/esp32s2/common-hal/pwmio/PWMOut.c @@ -39,7 +39,7 @@ STATIC bool never_reset_tim[LEDC_TIMER_MAX]; STATIC bool never_reset_chan[LEDC_CHANNEL_MAX]; void pwmout_reset(void) { - for (size_t i = 0; i < LEDC_CHANNEL_MAX; i++ ) { + for (size_t i = 0; i < LEDC_CHANNEL_MAX; i++) { if (reserved_channels[i] != INDEX_EMPTY && not_first_reset) { ledc_stop(LEDC_LOW_SPEED_MODE, i, 0); } @@ -47,7 +47,7 @@ void pwmout_reset(void) { reserved_channels[i] = INDEX_EMPTY; } } - for (size_t i = 0; i < LEDC_TIMER_MAX; i++ ) { + for (size_t i = 0; i < LEDC_TIMER_MAX; i++) { if (reserved_timer_freq[i]) { ledc_timer_rst(LEDC_LOW_SPEED_MODE, i); } @@ -58,16 +58,16 @@ void pwmout_reset(void) { not_first_reset = true; } -pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, - const mcu_pin_obj_t* pin, - uint16_t duty, - uint32_t frequency, - bool variable_frequency) { +pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, + const mcu_pin_obj_t *pin, + uint16_t duty, + uint32_t frequency, + bool variable_frequency) { // Calculate duty cycle uint32_t duty_bits = 0; - uint32_t interval = LEDC_APB_CLK_HZ/frequency; + uint32_t interval = LEDC_APB_CLK_HZ / frequency; for (size_t i = 0; i < 32; i++) { - if(!(interval >> i)) { + if (!(interval >> i)) { duty_bits = i - 1; break; } @@ -83,7 +83,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, size_t channel_index = INDEX_EMPTY; for (size_t i = 0; i < LEDC_TIMER_MAX; i++) { if ((reserved_timer_freq[i] == frequency) && !variable_frequency) { - //prioritize matched frequencies so we don't needlessly take slots + // prioritize matched frequencies so we don't needlessly take slots timer_index = i; break; } else if (reserved_timer_freq[i] == 0) { @@ -155,11 +155,11 @@ void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { never_reset_chan[self->chan_handle.channel] = false; } -bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { return self->deinited == true; } -void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { +void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { if (common_hal_pwmio_pwmout_deinited(self)) { return; } @@ -169,7 +169,7 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { } // Search if any other channel is using the timer bool taken = false; - for (size_t i =0; i < LEDC_CHANNEL_MAX; i++) { + for (size_t i = 0; i < LEDC_CHANNEL_MAX; i++) { if (reserved_channels[i] == self->tim_handle.timer_num) { taken = true; } @@ -186,23 +186,23 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { self->deinited = true; } -void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t* self, uint16_t duty) { +void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty) { ledc_set_duty(LEDC_LOW_SPEED_MODE, self->chan_handle.channel, duty >> (16 - self->duty_resolution)); ledc_update_duty(LEDC_LOW_SPEED_MODE, self->chan_handle.channel); } -uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t* self) { +uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t *self) { return ledc_get_duty(LEDC_LOW_SPEED_MODE, self->chan_handle.channel) << (16 - self->duty_resolution); } -void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t frequency) { +void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, uint32_t frequency) { ledc_set_freq(LEDC_LOW_SPEED_MODE, self->tim_handle.timer_num, frequency); } -uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t* self) { +uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t *self) { return ledc_get_freq(LEDC_LOW_SPEED_MODE, self->tim_handle.timer_num); } -bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *self) { return self->variable_frequency; } diff --git a/ports/esp32s2/common-hal/pwmio/PWMOut.h b/ports/esp32s2/common-hal/pwmio/PWMOut.h index 9055dee8e3..9480b8885a 100644 --- a/ports/esp32s2/common-hal/pwmio/PWMOut.h +++ b/ports/esp32s2/common-hal/pwmio/PWMOut.h @@ -36,8 +36,8 @@ typedef struct { ledc_channel_config_t chan_handle; uint16_t pin_number; uint8_t duty_resolution; - bool variable_frequency: 1; - bool deinited: 1; + bool variable_frequency : 1; + bool deinited : 1; } pwmio_pwmout_obj_t; void pwmout_reset(void); diff --git a/ports/esp32s2/common-hal/rotaryio/IncrementalEncoder.c b/ports/esp32s2/common-hal/rotaryio/IncrementalEncoder.c index 25529ac723..59fa54880a 100644 --- a/ports/esp32s2/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/esp32s2/common-hal/rotaryio/IncrementalEncoder.c @@ -30,8 +30,8 @@ #include "py/runtime.h" #include "supervisor/shared/translate.h" -void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t* self, - const mcu_pin_obj_t* pin_a, const mcu_pin_obj_t* pin_b) { +void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self, + const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b) { claim_pin(pin_a); claim_pin(pin_b); @@ -49,7 +49,7 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode .hctrl_mode = PCNT_MODE_KEEP, // Keep the primary counter mode if high }; - // Initialize PCNT unit + // Initialize PCNT unit const int8_t unit = peripherals_pcnt_init(pcnt_config); if (unit == -1) { mp_raise_RuntimeError(translate("All PCNT units in use")); @@ -60,11 +60,11 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode self->unit = (pcnt_unit_t)unit; } -bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t* self) { +bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t *self) { return self->unit == PCNT_UNIT_MAX; } -void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t* self) { +void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t *self) { if (common_hal_rotaryio_incrementalencoder_deinited(self)) { return; } @@ -73,14 +73,14 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o peripherals_pcnt_deinit(&self->unit); } -mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t* self) { +mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self) { int16_t count; pcnt_get_counter_value(self->unit, &count); - return (count/2)+self->position; + return (count / 2) + self->position; } -void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t* self, - mp_int_t new_position) { +void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, + mp_int_t new_position) { self->position = new_position; pcnt_counter_clear(self->unit); } diff --git a/ports/esp32s2/common-hal/socketpool/Socket.c b/ports/esp32s2/common-hal/socketpool/Socket.c index 5f93807bb6..385d71b54d 100644 --- a/ports/esp32s2/common-hal/socketpool/Socket.c +++ b/ports/esp32s2/common-hal/socketpool/Socket.c @@ -37,7 +37,7 @@ #include "components/lwip/lwip/src/include/lwip/sys.h" #include "components/lwip/lwip/src/include/lwip/netdb.h" -STATIC socketpool_socket_obj_t * open_socket_handles[CONFIG_LWIP_MAX_SOCKETS]; +STATIC socketpool_socket_obj_t *open_socket_handles[CONFIG_LWIP_MAX_SOCKETS]; void socket_reset(void) { for (size_t i = 0; i < MP_ARRAY_SIZE(open_socket_handles); i++) { @@ -52,7 +52,7 @@ void socket_reset(void) { } } -bool register_open_socket(socketpool_socket_obj_t* self) { +bool register_open_socket(socketpool_socket_obj_t *self) { for (size_t i = 0; i < MP_ARRAY_SIZE(open_socket_handles); i++) { if (open_socket_handles[i] == NULL) { open_socket_handles[i] = self; @@ -62,8 +62,8 @@ bool register_open_socket(socketpool_socket_obj_t* self) { return false; } -socketpool_socket_obj_t* common_hal_socketpool_socket_accept(socketpool_socket_obj_t* self, - uint8_t* ip, uint32_t *port) { +socketpool_socket_obj_t *common_hal_socketpool_socket_accept(socketpool_socket_obj_t *self, + uint8_t *ip, uint32_t *port) { struct sockaddr_in accept_addr; socklen_t socklen = sizeof(accept_addr); int newsoc = -1; @@ -87,7 +87,7 @@ socketpool_socket_obj_t* common_hal_socketpool_socket_accept(socketpool_socket_o if (!timed_out) { // harmless on failure but avoiding memcpy is faster - memcpy((void *)ip, (void*)&accept_addr.sin_addr.s_addr, sizeof(accept_addr.sin_addr.s_addr)); + memcpy((void *)ip, (void *)&accept_addr.sin_addr.s_addr, sizeof(accept_addr.sin_addr.s_addr)); *port = accept_addr.sin_port; } else { mp_raise_OSError(ETIMEDOUT); @@ -113,8 +113,8 @@ socketpool_socket_obj_t* common_hal_socketpool_socket_accept(socketpool_socket_o } } -bool common_hal_socketpool_socket_bind(socketpool_socket_obj_t* self, - const char* host, size_t hostlen, uint32_t port) { +bool common_hal_socketpool_socket_bind(socketpool_socket_obj_t *self, + const char *host, size_t hostlen, uint32_t port) { struct sockaddr_in bind_addr; bind_addr.sin_addr.s_addr = inet_addr(host); bind_addr.sin_family = AF_INET; @@ -129,7 +129,7 @@ bool common_hal_socketpool_socket_bind(socketpool_socket_obj_t* self, return result; } -void common_hal_socketpool_socket_close(socketpool_socket_obj_t* self) { +void common_hal_socketpool_socket_close(socketpool_socket_obj_t *self) { self->connected = false; if (self->num >= 0) { lwip_shutdown(self->num, 0); @@ -144,8 +144,8 @@ void common_hal_socketpool_socket_close(socketpool_socket_obj_t* self) { } } -bool common_hal_socketpool_socket_connect(socketpool_socket_obj_t* self, - const char* host, size_t hostlen, uint32_t port) { +bool common_hal_socketpool_socket_connect(socketpool_socket_obj_t *self, + const char *host, size_t hostlen, uint32_t port) { const struct addrinfo hints = { .ai_family = AF_INET, .ai_socktype = SOCK_STREAM, @@ -190,20 +190,20 @@ bool common_hal_socketpool_socket_connect(socketpool_socket_obj_t* self, } } -bool common_hal_socketpool_socket_get_closed(socketpool_socket_obj_t* self) { +bool common_hal_socketpool_socket_get_closed(socketpool_socket_obj_t *self) { return self->num < 0; } -bool common_hal_socketpool_socket_get_connected(socketpool_socket_obj_t* self) { +bool common_hal_socketpool_socket_get_connected(socketpool_socket_obj_t *self) { return self->connected; } -bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t* self, int backlog) { +bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t *self, int backlog) { return lwip_listen(self->num, backlog) == 0; } -mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t* self, - uint8_t* buf, uint32_t len, uint8_t* ip, uint *port) { +mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t *self, + uint8_t *buf, uint32_t len, uint8_t *ip, uint *port) { struct sockaddr_in source_addr; socklen_t socklen = sizeof(source_addr); @@ -213,9 +213,9 @@ mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t* se int received = -1; bool timed_out = false; while (received == -1 && - !timed_out && - !mp_hal_is_interrupted()) { - if (self->timeout_ms != (uint)-1 && self->timeout_ms != 0) { + !timed_out && + !mp_hal_is_interrupted()) { + if (self->timeout_ms != (uint)-1 && self->timeout_ms != 0) { timed_out = supervisor_ticks_ms64() - start_ticks >= self->timeout_ms; } RUN_BACKGROUND_TASKS; @@ -228,7 +228,7 @@ mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t* se } if (!timed_out) { - memcpy((void *)ip, (void*)&source_addr.sin_addr.s_addr, sizeof(source_addr.sin_addr.s_addr)); + memcpy((void *)ip, (void *)&source_addr.sin_addr.s_addr, sizeof(source_addr.sin_addr.s_addr)); *port = source_addr.sin_port; } else { mp_raise_OSError(ETIMEDOUT); @@ -242,7 +242,7 @@ mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t* se return received; } -mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t* self, const uint8_t* buf, uint32_t len) { +mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t *self, const uint8_t *buf, uint32_t len) { int received = 0; bool timed_out = false; @@ -251,13 +251,13 @@ mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t* self, uint64_t start_ticks = supervisor_ticks_ms64(); received = -1; while (received == -1 && - !timed_out && - !mp_hal_is_interrupted()) { + !timed_out && + !mp_hal_is_interrupted()) { if (self->timeout_ms != (uint)-1 && self->timeout_ms != 0) { timed_out = supervisor_ticks_ms64() - start_ticks >= self->timeout_ms; } RUN_BACKGROUND_TASKS; - received = lwip_recv(self->num, (void*) buf, len, 0); + received = lwip_recv(self->num, (void *)buf, len, 0); // In non-blocking mode, fail instead of looping if (received == -1 && self->timeout_ms == 0) { @@ -274,7 +274,7 @@ mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t* self, return received; } -mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t* self, const uint8_t* buf, uint32_t len) { +mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t *self, const uint8_t *buf, uint32_t len) { int sent = -1; if (self->num != -1) { // LWIP Socket @@ -290,8 +290,8 @@ mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t* self, const return sent; } -mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t* self, - const char* host, size_t hostlen, uint32_t port, const uint8_t* buf, uint32_t len) { +mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t *self, + const char *host, size_t hostlen, uint32_t port, const uint8_t *buf, uint32_t len) { // Set parameters const struct addrinfo hints = { @@ -323,6 +323,6 @@ mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t* self, return bytes_sent; } -void common_hal_socketpool_socket_settimeout(socketpool_socket_obj_t* self, uint32_t timeout_ms) { +void common_hal_socketpool_socket_settimeout(socketpool_socket_obj_t *self, uint32_t timeout_ms) { self->timeout_ms = timeout_ms; } diff --git a/ports/esp32s2/common-hal/socketpool/Socket.h b/ports/esp32s2/common-hal/socketpool/Socket.h index b86f5597c4..87f8b20dbb 100644 --- a/ports/esp32s2/common-hal/socketpool/Socket.h +++ b/ports/esp32s2/common-hal/socketpool/Socket.h @@ -41,11 +41,11 @@ typedef struct { int family; int ipproto; bool connected; - socketpool_socketpool_obj_t* pool; + socketpool_socketpool_obj_t *pool; mp_uint_t timeout_ms; } socketpool_socket_obj_t; void socket_reset(void); -bool register_open_socket(socketpool_socket_obj_t* self); +bool register_open_socket(socketpool_socket_obj_t *self); #endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_SOCKETPOOL_SOCKET_H diff --git a/ports/esp32s2/common-hal/socketpool/SocketPool.c b/ports/esp32s2/common-hal/socketpool/SocketPool.c index fbd6dca7af..4cea95ec41 100644 --- a/ports/esp32s2/common-hal/socketpool/SocketPool.c +++ b/ports/esp32s2/common-hal/socketpool/SocketPool.c @@ -34,13 +34,13 @@ #include "bindings/espidf/__init__.h" -void common_hal_socketpool_socketpool_construct(socketpool_socketpool_obj_t* self, mp_obj_t radio) { +void common_hal_socketpool_socketpool_construct(socketpool_socketpool_obj_t *self, mp_obj_t radio) { if (radio != MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj)) { mp_raise_ValueError(translate("SocketPool can only be used with wifi.radio")); } } -socketpool_socket_obj_t* common_hal_socketpool_socket(socketpool_socketpool_obj_t* self, +socketpool_socket_obj_t *common_hal_socketpool_socket(socketpool_socketpool_obj_t *self, socketpool_socketpool_addressfamily_t family, socketpool_socketpool_sock_t type) { int addr_family; @@ -87,8 +87,8 @@ socketpool_socket_obj_t* common_hal_socketpool_socket(socketpool_socketpool_obj_ } -mp_obj_t common_hal_socketpool_socketpool_gethostbyname(socketpool_socketpool_obj_t* self, - const char* host) { +mp_obj_t common_hal_socketpool_socketpool_gethostbyname(socketpool_socketpool_obj_t *self, + const char *host) { const struct addrinfo hints = { .ai_family = AF_INET, diff --git a/ports/esp32s2/common-hal/ssl/SSLContext.c b/ports/esp32s2/common-hal/ssl/SSLContext.c index afc3ecce22..a94c1df1eb 100644 --- a/ports/esp32s2/common-hal/ssl/SSLContext.c +++ b/ports/esp32s2/common-hal/ssl/SSLContext.c @@ -31,12 +31,12 @@ #include "py/runtime.h" -void common_hal_ssl_sslcontext_construct(ssl_sslcontext_obj_t* self) { +void common_hal_ssl_sslcontext_construct(ssl_sslcontext_obj_t *self) { } -ssl_sslsocket_obj_t* common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t* self, - socketpool_socket_obj_t* socket, bool server_side, const char* server_hostname) { +ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t *self, + socketpool_socket_obj_t *socket, bool server_side, const char *server_hostname) { if (socket->type != SOCK_STREAM) { mp_raise_RuntimeError(translate("Invalid socket for TLS")); @@ -47,7 +47,7 @@ ssl_sslsocket_obj_t* common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t* sock->ssl_context = self; sock->sock = socket; - esp_tls_t* tls_handle = esp_tls_init(); + esp_tls_t *tls_handle = esp_tls_init(); if (tls_handle == NULL) { mp_raise_espidf_MemoryError(); } diff --git a/ports/esp32s2/common-hal/ssl/SSLSocket.c b/ports/esp32s2/common-hal/ssl/SSLSocket.c index 10c29108c4..724d2aac92 100644 --- a/ports/esp32s2/common-hal/ssl/SSLSocket.c +++ b/ports/esp32s2/common-hal/ssl/SSLSocket.c @@ -35,27 +35,27 @@ #include "py/runtime.h" #include "supervisor/shared/tick.h" -ssl_sslsocket_obj_t* common_hal_ssl_sslsocket_accept(ssl_sslsocket_obj_t* self, - uint8_t* ip, uint32_t *port) { - socketpool_socket_obj_t * sock = common_hal_socketpool_socket_accept(self->sock, ip, port); - ssl_sslsocket_obj_t * sslsock = common_hal_ssl_sslcontext_wrap_socket(self->ssl_context, sock, false, NULL); +ssl_sslsocket_obj_t *common_hal_ssl_sslsocket_accept(ssl_sslsocket_obj_t *self, + uint8_t *ip, uint32_t *port) { + socketpool_socket_obj_t *sock = common_hal_socketpool_socket_accept(self->sock, ip, port); + ssl_sslsocket_obj_t *sslsock = common_hal_ssl_sslcontext_wrap_socket(self->ssl_context, sock, false, NULL); return sslsock; } -bool common_hal_ssl_sslsocket_bind(ssl_sslsocket_obj_t* self, - const char* host, size_t hostlen, uint32_t port) { +bool common_hal_ssl_sslsocket_bind(ssl_sslsocket_obj_t *self, + const char *host, size_t hostlen, uint32_t port) { return common_hal_socketpool_socket_bind(self->sock, host, hostlen, port); } -void common_hal_ssl_sslsocket_close(ssl_sslsocket_obj_t* self) { +void common_hal_ssl_sslsocket_close(ssl_sslsocket_obj_t *self) { common_hal_socketpool_socket_close(self->sock); esp_tls_conn_destroy(self->tls); self->tls = NULL; } -bool common_hal_ssl_sslsocket_connect(ssl_sslsocket_obj_t* self, - const char* host, size_t hostlen, uint32_t port) { - esp_tls_cfg_t* tls_config = NULL; +bool common_hal_ssl_sslsocket_connect(ssl_sslsocket_obj_t *self, + const char *host, size_t hostlen, uint32_t port) { + esp_tls_cfg_t *tls_config = NULL; tls_config = &self->ssl_context->ssl_config; int result = esp_tls_conn_new_sync(host, hostlen, port, tls_config, self->tls); self->sock->connected = result >= 0; @@ -88,19 +88,19 @@ bool common_hal_ssl_sslsocket_connect(ssl_sslsocket_obj_t* self, return self->sock->connected; } -bool common_hal_ssl_sslsocket_get_closed(ssl_sslsocket_obj_t* self) { +bool common_hal_ssl_sslsocket_get_closed(ssl_sslsocket_obj_t *self) { return self->tls == NULL && self->sock->num < 0; } -bool common_hal_ssl_sslsocket_get_connected(ssl_sslsocket_obj_t* self) { +bool common_hal_ssl_sslsocket_get_connected(ssl_sslsocket_obj_t *self) { return self->sock->connected; } -bool common_hal_ssl_sslsocket_listen(ssl_sslsocket_obj_t* self, int backlog) { +bool common_hal_ssl_sslsocket_listen(ssl_sslsocket_obj_t *self, int backlog) { return common_hal_socketpool_socket_listen(self->sock, backlog); } -mp_uint_t common_hal_ssl_sslsocket_recv_into(ssl_sslsocket_obj_t* self, const uint8_t* buf, uint32_t len) { +mp_uint_t common_hal_ssl_sslsocket_recv_into(ssl_sslsocket_obj_t *self, const uint8_t *buf, uint32_t len) { int received = 0; bool timed_out = false; int status = 0; @@ -129,7 +129,7 @@ mp_uint_t common_hal_ssl_sslsocket_recv_into(ssl_sslsocket_obj_t* self, const ui available = remaining; } if (available > 0) { - status = esp_tls_conn_read(self->tls, (void*) buf + received, available); + status = esp_tls_conn_read(self->tls, (void *)buf + received, available); if (status == 0) { // Reading zero when something is available indicates a closed // connection. (The available bytes could have been TLS internal.) @@ -140,7 +140,7 @@ mp_uint_t common_hal_ssl_sslsocket_recv_into(ssl_sslsocket_obj_t* self, const ui } } // In non-blocking mode, fail instead of timing out - if (received==0 && self->sock->timeout_ms == 0) { + if (received == 0 && self->sock->timeout_ms == 0) { mp_raise_OSError(MP_EAGAIN); } } @@ -151,7 +151,7 @@ mp_uint_t common_hal_ssl_sslsocket_recv_into(ssl_sslsocket_obj_t* self, const ui return received; } -mp_uint_t common_hal_ssl_sslsocket_send(ssl_sslsocket_obj_t* self, const uint8_t* buf, uint32_t len) { +mp_uint_t common_hal_ssl_sslsocket_send(ssl_sslsocket_obj_t *self, const uint8_t *buf, uint32_t len) { int sent = -1; sent = esp_tls_conn_write(self->tls, buf, len); @@ -171,6 +171,6 @@ mp_uint_t common_hal_ssl_sslsocket_send(ssl_sslsocket_obj_t* self, const uint8_t return sent; } -void common_hal_ssl_sslsocket_settimeout(ssl_sslsocket_obj_t* self, uint32_t timeout_ms) { +void common_hal_ssl_sslsocket_settimeout(ssl_sslsocket_obj_t *self, uint32_t timeout_ms) { self->sock->timeout_ms = timeout_ms; } diff --git a/ports/esp32s2/common-hal/ssl/SSLSocket.h b/ports/esp32s2/common-hal/ssl/SSLSocket.h index e9e5bff062..b485781259 100644 --- a/ports/esp32s2/common-hal/ssl/SSLSocket.h +++ b/ports/esp32s2/common-hal/ssl/SSLSocket.h @@ -36,9 +36,9 @@ typedef struct { mp_obj_base_t base; - socketpool_socket_obj_t * sock; - esp_tls_t* tls; - ssl_sslcontext_obj_t* ssl_context; + socketpool_socket_obj_t *sock; + esp_tls_t *tls; + ssl_sslcontext_obj_t *ssl_context; } ssl_sslsocket_obj_t; #endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_SSL_SSLSOCKET_H diff --git a/ports/esp32s2/common-hal/ssl/__init__.c b/ports/esp32s2/common-hal/ssl/__init__.c index 8d386d0c3a..a0886adda7 100644 --- a/ports/esp32s2/common-hal/ssl/__init__.c +++ b/ports/esp32s2/common-hal/ssl/__init__.c @@ -28,7 +28,7 @@ #include "components/mbedtls/esp_crt_bundle/include/esp_crt_bundle.h" -void common_hal_ssl_create_default_context(ssl_sslcontext_obj_t* self) { +void common_hal_ssl_create_default_context(ssl_sslcontext_obj_t *self) { memset(&self->ssl_config, 0, sizeof(esp_tls_cfg_t)); self->ssl_config.crt_bundle_attach = esp_crt_bundle_attach; } diff --git a/ports/esp32s2/common-hal/supervisor/Runtime.c b/ports/esp32s2/common-hal/supervisor/Runtime.c index 974f26cec1..f827651781 100644 --- a/ports/esp32s2/common-hal/supervisor/Runtime.c +++ b/ports/esp32s2/common-hal/supervisor/Runtime.c @@ -29,9 +29,9 @@ #include "supervisor/serial.h" bool common_hal_supervisor_runtime_get_serial_connected(void) { - return (bool) serial_connected(); + return (bool)serial_connected(); } bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); + return (bool)serial_bytes_available(); } diff --git a/ports/esp32s2/common-hal/touchio/TouchIn.c b/ports/esp32s2/common-hal/touchio/TouchIn.c index 401b84d5c2..53bc335d30 100644 --- a/ports/esp32s2/common-hal/touchio/TouchIn.c +++ b/ports/esp32s2/common-hal/touchio/TouchIn.c @@ -38,8 +38,8 @@ static uint16_t get_raw_reading(touchio_touchin_obj_t *self) { return touch_value; } -void common_hal_touchio_touchin_construct(touchio_touchin_obj_t* self, - const mcu_pin_obj_t *pin) { +void common_hal_touchio_touchin_construct(touchio_touchin_obj_t *self, + const mcu_pin_obj_t *pin) { if (pin->touch_channel == TOUCH_PAD_MAX) { mp_raise_ValueError(translate("Invalid pin")); } @@ -59,11 +59,11 @@ void common_hal_touchio_touchin_construct(touchio_touchin_obj_t* self, self->threshold = get_raw_reading(self) + 100; } -bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t* self) { +bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t *self) { return self->pin == NULL; } -void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t* self) { +void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t *self) { if (common_hal_touchio_touchin_deinited(self)) { return; } diff --git a/ports/esp32s2/common-hal/touchio/TouchIn.h b/ports/esp32s2/common-hal/touchio/TouchIn.h index 2f7c66d2b8..d4ce2d8a5f 100644 --- a/ports/esp32s2/common-hal/touchio/TouchIn.h +++ b/ports/esp32s2/common-hal/touchio/TouchIn.h @@ -32,7 +32,7 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t * pin; + const mcu_pin_obj_t *pin; uint16_t threshold; } touchio_touchin_obj_t; diff --git a/ports/esp32s2/common-hal/watchdog/WatchDogTimer.c b/ports/esp32s2/common-hal/watchdog/WatchDogTimer.c index 79a84ef594..f17a037ff4 100644 --- a/ports/esp32s2/common-hal/watchdog/WatchDogTimer.c +++ b/ports/esp32s2/common-hal/watchdog/WatchDogTimer.c @@ -35,11 +35,11 @@ void esp_task_wdt_isr_user_handler(void) { mp_obj_exception_clear_traceback(MP_OBJ_FROM_PTR(&mp_watchdog_timeout_exception)); MP_STATE_VM(mp_pending_exception) = &mp_watchdog_timeout_exception; -#if MICROPY_ENABLE_SCHEDULER + #if MICROPY_ENABLE_SCHEDULER if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) { MP_STATE_VM(sched_state) = MP_SCHED_PENDING; } -#endif + #endif } void common_hal_watchdog_feed(watchdog_watchdogtimer_obj_t *self) { @@ -55,7 +55,7 @@ void common_hal_watchdog_deinit(watchdog_watchdogtimer_obj_t *self) { } void watchdog_reset(void) { - common_hal_watchdog_deinit(&common_hal_mcu_watchdogtimer_obj); + common_hal_watchdog_deinit(&common_hal_mcu_watchdogtimer_obj); } static void wdt_config(watchdog_watchdogtimer_obj_t *self) { diff --git a/ports/esp32s2/common-hal/watchdog/WatchDogTimer.h b/ports/esp32s2/common-hal/watchdog/WatchDogTimer.h index 04d9aeee6c..c26d140139 100644 --- a/ports/esp32s2/common-hal/watchdog/WatchDogTimer.h +++ b/ports/esp32s2/common-hal/watchdog/WatchDogTimer.h @@ -32,9 +32,9 @@ #include "shared-bindings/watchdog/WatchDogTimer.h" struct _watchdog_watchdogtimer_obj_t { - mp_obj_base_t base; - mp_float_t timeout; - watchdog_watchdogmode_t mode; + mp_obj_base_t base; + mp_float_t timeout; + watchdog_watchdogmode_t mode; }; // This needs to be called in order to disable the watchdog diff --git a/ports/esp32s2/common-hal/wifi/Network.c b/ports/esp32s2/common-hal/wifi/Network.c index b6eb6bb433..49507df0d5 100644 --- a/ports/esp32s2/common-hal/wifi/Network.c +++ b/ports/esp32s2/common-hal/wifi/Network.c @@ -31,8 +31,8 @@ #include "py/obj.h" mp_obj_t common_hal_wifi_network_get_ssid(wifi_network_obj_t *self) { - const char* cstr = (const char*) self->record.ssid; - return mp_obj_new_str(cstr, strlen(cstr)); + const char *cstr = (const char *)self->record.ssid; + return mp_obj_new_str(cstr, strlen(cstr)); } #define MAC_ADDRESS_LENGTH 6 @@ -50,13 +50,13 @@ mp_obj_t common_hal_wifi_network_get_channel(wifi_network_obj_t *self) { } mp_obj_t common_hal_wifi_network_get_country(wifi_network_obj_t *self) { - const char* cstr = (const char*) self->record.country.cc; - // 2 instead of strlen(cstr) as this gives us only the country-code - return mp_obj_new_str(cstr, 2); + const char *cstr = (const char *)self->record.country.cc; + // 2 instead of strlen(cstr) as this gives us only the country-code + return mp_obj_new_str(cstr, 2); } mp_obj_t common_hal_wifi_network_get_authmode(wifi_network_obj_t *self) { - const char* authmode = ""; + const char *authmode = ""; switch (self->record.authmode) { case WIFI_AUTH_OPEN: authmode = "OPEN"; @@ -86,5 +86,5 @@ mp_obj_t common_hal_wifi_network_get_authmode(wifi_network_obj_t *self) { authmode = "UNKNOWN"; break; } - return mp_obj_new_str(authmode, strlen(authmode)); + return mp_obj_new_str(authmode, strlen(authmode)); } diff --git a/ports/esp32s2/common-hal/wifi/Radio.c b/ports/esp32s2/common-hal/wifi/Radio.c index 574bab0a19..9c8ccaf7f2 100644 --- a/ports/esp32s2/common-hal/wifi/Radio.c +++ b/ports/esp32s2/common-hal/wifi/Radio.c @@ -71,7 +71,7 @@ void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled) { return; } if (!self->started && enabled) { - // esp_wifi_start() would default to soft-AP, thus setting it to station + // esp_wifi_start() would default to soft-AP, thus setting it to station start_station(self); ESP_ERROR_CHECK(esp_wifi_start()); self->started = true; @@ -127,7 +127,7 @@ void common_hal_wifi_radio_set_hostname(wifi_radio_obj_t *self, const char *host esp_netif_set_hostname(self->netif, hostname); } -wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t* ssid, size_t ssid_len, uint8_t* password, size_t password_len, uint8_t channel, mp_float_t timeout, uint8_t* bssid, size_t bssid_len) { +wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t *ssid, size_t ssid_len, uint8_t *password, size_t password_len, uint8_t channel, mp_float_t timeout, uint8_t *bssid, size_t bssid_len) { if (!common_hal_wifi_radio_get_enabled(self)) { mp_raise_RuntimeError(translate("wifi is not enabled")); } @@ -149,7 +149,7 @@ wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t xEventGroupClearBits(self->event_group_handle, WIFI_DISCONNECTED_BIT); start_station(self); - wifi_config_t* config = &self->sta_config; + wifi_config_t *config = &self->sta_config; memcpy(&config->sta.ssid, ssid, ssid_len); config->sta.ssid[ssid_len] = 0; memcpy(&config->sta.password, password, password_len); @@ -158,7 +158,7 @@ wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t // From esp_wifi_types.h: // Generally, station_config.bssid_set needs to be 0; and it needs // to be 1 only when users need to check the MAC address of the AP - if (bssid_len > 0){ + if (bssid_len > 0) { memcpy(&config->sta.bssid, bssid, bssid_len); config->sta.bssid[bssid_len] = 0; config->sta.bssid_set = true; @@ -202,7 +202,7 @@ mp_obj_t common_hal_wifi_radio_get_ap_info(wifi_radio_obj_t *self) { } // Make sure the interface is in STA mode - if (!self->sta_mode){ + if (!self->sta_mode) { return mp_const_none; } @@ -212,7 +212,7 @@ mp_obj_t common_hal_wifi_radio_get_ap_info(wifi_radio_obj_t *self) { // ESP_OK: succeed // ESP_ERR_WIFI_CONN: The station interface don't initialized // ESP_ERR_WIFI_NOT_CONNECT: The station is in disconnect status - if (esp_wifi_sta_get_ap_info(&self->ap_info.record) != ESP_OK){ + if (esp_wifi_sta_get_ap_info(&self->ap_info.record) != ESP_OK) { return mp_const_none; } else { if (strlen(self->ap_info.record.country.cc) == 0) { diff --git a/ports/esp32s2/common-hal/wifi/ScannedNetworks.c b/ports/esp32s2/common-hal/wifi/ScannedNetworks.c index cc733308db..62ef62b7f5 100644 --- a/ports/esp32s2/common-hal/wifi/ScannedNetworks.c +++ b/ports/esp32s2/common-hal/wifi/ScannedNetworks.c @@ -52,10 +52,10 @@ static void wifi_scannednetworks_done(wifi_scannednetworks_obj_t *self) { static bool wifi_scannednetworks_wait_for_scan(wifi_scannednetworks_obj_t *self) { EventBits_t bits = xEventGroupWaitBits(self->radio_event_group, - WIFI_SCAN_DONE_BIT, - pdTRUE, - pdTRUE, - 0); + WIFI_SCAN_DONE_BIT, + pdTRUE, + pdTRUE, + 0); while ((bits & WIFI_SCAN_DONE_BIT) == 0 && !mp_hal_is_interrupted()) { RUN_BACKGROUND_TASKS; bits = xEventGroupWaitBits(self->radio_event_group, @@ -94,11 +94,11 @@ mp_obj_t common_hal_wifi_scannednetworks_next(wifi_scannednetworks_obj_t *self) } // If we need more space than we have, realloc. if (self->total_results > self->max_results) { - wifi_ap_record_t* results = m_renew_maybe(wifi_ap_record_t, - self->results, - self->max_results, - self->total_results, - true /* allow move */); + wifi_ap_record_t *results = m_renew_maybe(wifi_ap_record_t, + self->results, + self->max_results, + self->total_results, + true /* allow move */); if (results != NULL) { self->results = results; self->max_results = self->total_results; @@ -157,7 +157,7 @@ void wifi_scannednetworks_scan_next_channel(wifi_scannednetworks_obj_t *self) { } } -void wifi_scannednetworks_deinit(wifi_scannednetworks_obj_t* self) { +void wifi_scannednetworks_deinit(wifi_scannednetworks_obj_t *self) { // if a scan is active, make sure and clean up the idf's buffer of results. if (self->scanning) { esp_wifi_scan_stop(); diff --git a/ports/esp32s2/common-hal/wifi/ScannedNetworks.h b/ports/esp32s2/common-hal/wifi/ScannedNetworks.h index 36da387f21..9790c4ab33 100644 --- a/ports/esp32s2/common-hal/wifi/ScannedNetworks.h +++ b/ports/esp32s2/common-hal/wifi/ScannedNetworks.h @@ -43,7 +43,7 @@ typedef struct { EventGroupHandle_t radio_event_group; // Results from the last channel scan - wifi_ap_record_t* results; + wifi_ap_record_t *results; uint16_t current_result; uint16_t total_results; uint16_t max_results; diff --git a/ports/esp32s2/common-hal/wifi/__init__.c b/ports/esp32s2/common-hal/wifi/__init__.c index a3927b7c3e..3ec4ebc24d 100644 --- a/ports/esp32s2/common-hal/wifi/__init__.c +++ b/ports/esp32s2/common-hal/wifi/__init__.c @@ -39,11 +39,11 @@ wifi_radio_obj_t common_hal_wifi_radio_obj; #include "components/log/include/esp_log.h" -static const char* TAG = "wifi"; +static const char *TAG = "wifi"; -static void event_handler(void* arg, esp_event_base_t event_base, - int32_t event_id, void* event_data) { - wifi_radio_obj_t* radio = arg; +static void event_handler(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data) { + wifi_radio_obj_t *radio = arg; if (event_base == WIFI_EVENT) { switch (event_id) { case WIFI_EVENT_SCAN_DONE: @@ -61,13 +61,13 @@ static void event_handler(void* arg, esp_event_base_t event_base, break; case WIFI_EVENT_STA_DISCONNECTED: { ESP_LOGW(TAG, "disconnected"); - wifi_event_sta_disconnected_t* d = (wifi_event_sta_disconnected_t*) event_data; + wifi_event_sta_disconnected_t *d = (wifi_event_sta_disconnected_t *)event_data; uint8_t reason = d->reason; ESP_LOGW(TAG, "reason %d 0x%02x", reason, reason); if (radio->retries_left > 0 && - reason != WIFI_REASON_AUTH_FAIL && - reason != WIFI_REASON_NO_AP_FOUND && - reason != WIFI_REASON_ASSOC_LEAVE) { + reason != WIFI_REASON_AUTH_FAIL && + reason != WIFI_REASON_NO_AP_FOUND && + reason != WIFI_REASON_ASSOC_LEAVE) { radio->retries_left--; ESP_LOGI(TAG, "Retrying connect. %d retries remaining", radio->retries_left); esp_wifi_connect(); @@ -107,7 +107,7 @@ void common_hal_wifi_init(void) { } wifi_ever_inited = true; - wifi_radio_obj_t* self = &common_hal_wifi_radio_obj; + wifi_radio_obj_t *self = &common_hal_wifi_radio_obj; self->netif = esp_netif_create_default_wifi_sta(); self->started = false; @@ -120,15 +120,15 @@ void common_hal_wifi_init(void) { self->event_group_handle = xEventGroupCreateStatic(&self->event_group); ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT, - ESP_EVENT_ANY_ID, - &event_handler, - self, - &self->handler_instance_all_wifi)); + ESP_EVENT_ANY_ID, + &event_handler, + self, + &self->handler_instance_all_wifi)); ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, - IP_EVENT_STA_GOT_IP, - &event_handler, - self, - &self->handler_instance_got_ip)); + IP_EVENT_STA_GOT_IP, + &event_handler, + self, + &self->handler_instance_got_ip)); wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); esp_err_t result = esp_wifi_init(&config); @@ -144,26 +144,26 @@ void wifi_reset(void) { if (!wifi_inited) { return; } - wifi_radio_obj_t* radio = &common_hal_wifi_radio_obj; + wifi_radio_obj_t *radio = &common_hal_wifi_radio_obj; common_hal_wifi_radio_set_enabled(radio, false); ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, - ESP_EVENT_ANY_ID, - radio->handler_instance_all_wifi)); + ESP_EVENT_ANY_ID, + radio->handler_instance_all_wifi)); ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, - IP_EVENT_STA_GOT_IP, - radio->handler_instance_got_ip)); + IP_EVENT_STA_GOT_IP, + radio->handler_instance_got_ip)); ESP_ERROR_CHECK(esp_wifi_deinit()); esp_netif_destroy(radio->netif); radio->netif = NULL; } -void ipaddress_ipaddress_to_esp_idf(mp_obj_t ip_address, ip_addr_t* esp_ip_address) { +void ipaddress_ipaddress_to_esp_idf(mp_obj_t ip_address, ip_addr_t *esp_ip_address) { if (!MP_OBJ_IS_TYPE(ip_address, &ipaddress_ipv4address_type)) { mp_raise_ValueError(translate("Only IPv4 addresses supported")); } mp_obj_t packed = common_hal_ipaddress_ipv4address_get_packed(ip_address); size_t len; - const char* bytes = mp_obj_str_get_data(packed, &len); + const char *bytes = mp_obj_str_get_data(packed, &len); IP_ADDR4(esp_ip_address, bytes[0], bytes[1], bytes[2], bytes[3]); } diff --git a/ports/esp32s2/common-hal/wifi/__init__.h b/ports/esp32s2/common-hal/wifi/__init__.h index d2bd06c570..1dbe50a04b 100644 --- a/ports/esp32s2/common-hal/wifi/__init__.h +++ b/ports/esp32s2/common-hal/wifi/__init__.h @@ -33,6 +33,6 @@ void wifi_reset(void); -void ipaddress_ipaddress_to_esp_idf(mp_obj_t ip_address, ip_addr_t* esp_ip_address); +void ipaddress_ipaddress_to_esp_idf(mp_obj_t ip_address, ip_addr_t *esp_ip_address); #endif // MICROPY_INCLUDED_ESP32S2_COMMON_HAL_WIFI___INIT___H diff --git a/ports/esp32s2/esp_error.c b/ports/esp32s2/esp_error.c index 57bc51528d..4bc44674b7 100644 --- a/ports/esp32s2/esp_error.c +++ b/ports/esp32s2/esp_error.c @@ -31,8 +31,8 @@ void raise_esp_error(esp_err_t err) { const compressed_string_t *msg = NULL; - const mp_obj_type_t * exception_type = &mp_type_espidf_IDFError; - switch(err) { + const mp_obj_type_t *exception_type = &mp_type_espidf_IDFError; + switch (err) { case ESP_FAIL: msg = translate("Generic Failure"); break; @@ -78,9 +78,9 @@ void raise_esp_error(esp_err_t err) { const char *group = "ESP-IDF"; // tests must be in descending order - MP_STATIC_ASSERT( ESP_ERR_FLASH_BASE > ESP_ERR_MESH_BASE ); - MP_STATIC_ASSERT( ESP_ERR_MESH_BASE > ESP_ERR_WIFI_BASE ); - if(err >= ESP_ERR_FLASH_BASE) { + MP_STATIC_ASSERT(ESP_ERR_FLASH_BASE > ESP_ERR_MESH_BASE); + MP_STATIC_ASSERT(ESP_ERR_MESH_BASE > ESP_ERR_WIFI_BASE); + if (err >= ESP_ERR_FLASH_BASE) { group = "Flash"; } else if (err >= ESP_ERR_MESH_BASE) { group = "Mesh"; diff --git a/ports/esp32s2/fatfs_port.c b/ports/esp32s2/fatfs_port.c index 8bdc047c12..631f7f0982 100644 --- a/ports/esp32s2/fatfs_port.c +++ b/ports/esp32s2/fatfs_port.c @@ -28,6 +28,6 @@ #include "lib/oofatfs/ff.h" DWORD get_fattime(void) { - // TODO: Implement this function. For now, fake it. + // TODO: Implement this function. For now, fake it. return ((2016 - 1980) << 25) | ((12) << 21) | ((4) << 16) | ((00) << 11) | ((18) << 5) | (23 / 2); } diff --git a/ports/esp32s2/mpconfigport.h b/ports/esp32s2/mpconfigport.h index 0cf695bc98..a3db0ab3d5 100644 --- a/ports/esp32s2/mpconfigport.h +++ b/ports/esp32s2/mpconfigport.h @@ -36,7 +36,7 @@ #include "py/circuitpy_mpconfig.h" #define MICROPY_PORT_ROOT_POINTERS \ - CIRCUITPY_COMMON_ROOT_POINTERS + CIRCUITPY_COMMON_ROOT_POINTERS #define MICROPY_NLR_SETJMP (1) #define CIRCUITPY_DEFAULT_STACK_SIZE 0x6000 diff --git a/ports/esp32s2/mphalport.c b/ports/esp32s2/mphalport.c index 9b4c4bc5eb..aaf1f468ff 100644 --- a/ports/esp32s2/mphalport.c +++ b/ports/esp32s2/mphalport.c @@ -57,5 +57,5 @@ mp_uint_t cpu_get_regs_and_sp(mp_uint_t *regs, uint8_t reg_count) { // because the register value could change after it's been restored but that // is unlikely to happen with a heap pointer while we do a GC. xthal_window_spill(); - return (mp_uint_t) __builtin_frame_address(0); + return (mp_uint_t)__builtin_frame_address(0); } diff --git a/ports/esp32s2/mphalport.h b/ports/esp32s2/mphalport.h index 4feddbd9b0..8682baec45 100644 --- a/ports/esp32s2/mphalport.h +++ b/ports/esp32s2/mphalport.h @@ -34,7 +34,7 @@ #include "py/mpconfig.h" #include "supervisor/shared/tick.h" -#define mp_hal_ticks_ms() ((mp_uint_t) supervisor_ticks_ms32()) +#define mp_hal_ticks_ms() ((mp_uint_t)supervisor_ticks_ms32()) bool mp_hal_stdin_any(void); diff --git a/ports/esp32s2/peripherals/pcnt.c b/ports/esp32s2/peripherals/pcnt.c index dd24569bef..e4578a2791 100644 --- a/ports/esp32s2/peripherals/pcnt.c +++ b/ports/esp32s2/peripherals/pcnt.c @@ -32,14 +32,14 @@ static uint8_t pcnt_unit_state[4]; void peripherals_pcnt_reset(void) { - for (uint8_t i = 0; i<=3; i++) { + for (uint8_t i = 0; i <= 3; i++) { pcnt_unit_state[i] = PCNT_UNIT_INACTIVE; } } int peripherals_pcnt_init(pcnt_config_t pcnt_config) { // Look for available pcnt unit - for (uint8_t i = 0; i<=3; i++) { + for (uint8_t i = 0; i <= 3; i++) { if (pcnt_unit_state[i] == PCNT_UNIT_INACTIVE) { pcnt_config.unit = (pcnt_unit_t)i; pcnt_unit_state[i] = PCNT_UNIT_ACTIVE; @@ -62,7 +62,7 @@ int peripherals_pcnt_init(pcnt_config_t pcnt_config) { return pcnt_config.unit; } -void peripherals_pcnt_deinit(pcnt_unit_t* unit) { +void peripherals_pcnt_deinit(pcnt_unit_t *unit) { pcnt_unit_state[*unit] = PCNT_UNIT_INACTIVE; *unit = PCNT_UNIT_MAX; } diff --git a/ports/esp32s2/peripherals/pcnt.h b/ports/esp32s2/peripherals/pcnt.h index 4fce13f4d6..8bd8b0272b 100644 --- a/ports/esp32s2/peripherals/pcnt.h +++ b/ports/esp32s2/peripherals/pcnt.h @@ -30,7 +30,7 @@ #include "driver/pcnt.h" extern int peripherals_pcnt_init(pcnt_config_t pcnt_config); -extern void peripherals_pcnt_deinit(pcnt_unit_t* unit); +extern void peripherals_pcnt_deinit(pcnt_unit_t *unit); extern void peripherals_pcnt_reset(void); #endif // MICROPY_INCLUDED_ESP32S2_PERIPHERALS_PCNT_HANDLER_H diff --git a/ports/esp32s2/peripherals/pins.c b/ports/esp32s2/peripherals/pins.c old mode 100755 new mode 100644 index 0d3d89ad50..f882281405 --- a/ports/esp32s2/peripherals/pins.c +++ b/ports/esp32s2/peripherals/pins.c @@ -33,13 +33,13 @@ // This macro is used to simplify pin definition in boards//pins.c #define PIN(p_name, p_number, p_adc_index, p_adc_channel, p_touch_channel) \ -const mcu_pin_obj_t pin_## p_name = { \ - PIN_PREFIX_VALUES \ - .number = p_number, \ - .adc_index = p_adc_index, \ - .adc_channel = p_adc_channel, \ - .touch_channel = p_touch_channel, \ -} + const mcu_pin_obj_t pin_##p_name = { \ + PIN_PREFIX_VALUES \ + .number = p_number, \ + .adc_index = p_adc_index, \ + .adc_channel = p_adc_channel, \ + .touch_channel = p_touch_channel, \ + } PIN(GPIO0, 0, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); PIN(GPIO1, 1, ADC_UNIT_1, ADC_CHANNEL_0, TOUCH_PAD_NUM1); diff --git a/ports/esp32s2/peripherals/pins.h b/ports/esp32s2/peripherals/pins.h index e0f5e7ddfe..c92f4b4cce 100644 --- a/ports/esp32s2/peripherals/pins.h +++ b/ports/esp32s2/peripherals/pins.h @@ -42,8 +42,8 @@ typedef struct { PIN_PREFIX_FIELDS gpio_num_t number; - uint8_t adc_index:2; - uint8_t adc_channel:6; + uint8_t adc_index : 2; + uint8_t adc_channel : 6; touch_pad_t touch_channel; } mcu_pin_obj_t; diff --git a/ports/esp32s2/peripherals/timer.c b/ports/esp32s2/peripherals/timer.c index 0ae1403874..674d7fc5b2 100644 --- a/ports/esp32s2/peripherals/timer.c +++ b/ports/esp32s2/peripherals/timer.c @@ -45,7 +45,7 @@ void peripherals_timer_reset(void) { } } -void peripherals_timer_init(const timer_config_t * config, timer_index_t * timer) { +void peripherals_timer_init(const timer_config_t *config, timer_index_t *timer) { bool break_loop = false; // get free timer @@ -63,7 +63,9 @@ void peripherals_timer_init(const timer_config_t * config, timer_index_t * timer return; } } - if (break_loop) {break;} + if (break_loop) { + break; + } } // initialize timer module @@ -71,6 +73,6 @@ void peripherals_timer_init(const timer_config_t * config, timer_index_t * timer timer_set_counter_value(timer->group, timer->idx, 0); } -void peripherals_timer_deinit(timer_index_t * timer) { +void peripherals_timer_deinit(timer_index_t *timer) { timer_deinit(timer->group, timer->idx); } diff --git a/ports/esp32s2/peripherals/timer.h b/ports/esp32s2/peripherals/timer.h index 8c9ebd91c9..54150069c4 100644 --- a/ports/esp32s2/peripherals/timer.h +++ b/ports/esp32s2/peripherals/timer.h @@ -34,8 +34,8 @@ typedef struct { timer_group_t group; } timer_index_t; -extern void peripherals_timer_init(const timer_config_t * config, timer_index_t * timer); -extern void peripherals_timer_deinit(timer_index_t * timer); +extern void peripherals_timer_init(const timer_config_t *config, timer_index_t *timer); +extern void peripherals_timer_deinit(timer_index_t *timer); extern void peripherals_timer_reset(void); #endif // MICROPY_INCLUDED_ESP32S2_PERIPHERALS_TIMER_HANDLER_H diff --git a/ports/esp32s2/supervisor/internal_flash.c b/ports/esp32s2/supervisor/internal_flash.c index de69a49f94..8f3d917765 100644 --- a/ports/esp32s2/supervisor/internal_flash.c +++ b/ports/esp32s2/supervisor/internal_flash.c @@ -41,7 +41,7 @@ #include "supervisor/usb.h" -STATIC const esp_partition_t * _partition; +STATIC const esp_partition_t *_partition; // TODO: Split the caching out of supervisor/shared/external_flash so we can use it. #define SECTOR_SIZE 4096 @@ -50,8 +50,8 @@ STATIC uint32_t _cache_lba = 0xffffffff; void supervisor_flash_init(void) { _partition = esp_partition_find_first(ESP_PARTITION_TYPE_DATA, - ESP_PARTITION_SUBTYPE_DATA_FAT, - NULL); + ESP_PARTITION_SUBTYPE_DATA_FAT, + NULL); } uint32_t supervisor_flash_get_block_size(void) { @@ -68,9 +68,9 @@ void port_internal_flash_flush(void) { mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t num_blocks) { esp_partition_read(_partition, - block * FILESYSTEM_BLOCK_SIZE, - dest, - num_blocks * FILESYSTEM_BLOCK_SIZE); + block * FILESYSTEM_BLOCK_SIZE, + dest, + num_blocks * FILESYSTEM_BLOCK_SIZE); return 0; } @@ -84,26 +84,26 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 if (_cache_lba != block_address) { esp_partition_read(_partition, - sector_offset, - _cache, - SECTOR_SIZE); + sector_offset, + _cache, + SECTOR_SIZE); _cache_lba = sector_offset; } for (uint8_t b = block_offset; b < blocks_per_sector; b++) { // Stop copying after the last block. if (block >= num_blocks) { - break; + break; } memcpy(_cache + b * FILESYSTEM_BLOCK_SIZE, - src + block * FILESYSTEM_BLOCK_SIZE, - FILESYSTEM_BLOCK_SIZE); + src + block * FILESYSTEM_BLOCK_SIZE, + FILESYSTEM_BLOCK_SIZE); block++; } esp_partition_erase_range(_partition, sector_offset, SECTOR_SIZE); esp_partition_write(_partition, - sector_offset, - _cache, - SECTOR_SIZE); + sector_offset, + _cache, + SECTOR_SIZE); } return 0; // success diff --git a/ports/esp32s2/supervisor/port.c b/ports/esp32s2/supervisor/port.c index 534f7f71bf..d48b7ef892 100644 --- a/ports/esp32s2/supervisor/port.c +++ b/ports/esp32s2/supervisor/port.c @@ -68,7 +68,7 @@ #define HEAP_SIZE (48 * 1024) -uint32_t* heap; +uint32_t *heap; uint32_t heap_size; STATIC esp_timer_handle_t _tick_timer; @@ -78,7 +78,7 @@ TaskHandle_t circuitpython_task = NULL; extern void esp_restart(void) NORETURN; -void tick_timer_cb(void* arg) { +void tick_timer_cb(void *arg) { supervisor_tick(); // CircuitPython's VM is run in a separate FreeRTOS task from timer callbacks. So, we have to @@ -86,7 +86,7 @@ void tick_timer_cb(void* arg) { xTaskNotifyGive(circuitpython_task); } -void sleep_timer_cb(void* arg); +void sleep_timer_cb(void *arg); safe_mode_t port_init(void) { esp_timer_create_args_t args; @@ -127,8 +127,8 @@ safe_mode_t port_init(void) { #endif #ifdef CONFIG_SPIRAM - heap = (uint32_t*) (DRAM0_CACHE_ADDRESS_HIGH - CONFIG_SPIRAM_SIZE); - heap_size = CONFIG_SPIRAM_SIZE / sizeof(uint32_t); + heap = (uint32_t *)(DRAM0_CACHE_ADDRESS_HIGH - CONFIG_SPIRAM_SIZE); + heap_size = CONFIG_SPIRAM_SIZE / sizeof(uint32_t); #endif if (heap == NULL) { @@ -160,73 +160,73 @@ void reset_port(void) { // A larger delay so the idle task can run and do any IDF cleanup needed. vTaskDelay(4); -#if CIRCUITPY_ANALOGIO + #if CIRCUITPY_ANALOGIO analogout_reset(); -#endif + #endif -#if CIRCUITPY_DUALBANK + #if CIRCUITPY_DUALBANK dualbank_reset(); -#endif + #endif -#if CIRCUITPY_PS2IO + #if CIRCUITPY_PS2IO ps2_reset(); -#endif + #endif -#if CIRCUITPY_AUDIOBUSIO + #if CIRCUITPY_AUDIOBUSIO i2s_reset(); -#endif + #endif -#if CIRCUITPY_PULSEIO + #if CIRCUITPY_PULSEIO esp32s2_peripherals_rmt_reset(); pulsein_reset(); -#endif + #endif -#if CIRCUITPY_PWMIO + #if CIRCUITPY_PWMIO pwmout_reset(); -#endif + #endif -#if CIRCUITPY_BUSIO + #if CIRCUITPY_BUSIO i2c_reset(); spi_reset(); uart_reset(); -#endif + #endif -#if defined(CIRCUITPY_COUNTIO) || defined(CIRCUITPY_ROTARYIO) + #if defined(CIRCUITPY_COUNTIO) || defined(CIRCUITPY_ROTARYIO) peripherals_pcnt_reset(); -#endif + #endif -#if CIRCUITPY_FREQUENCYIO + #if CIRCUITPY_FREQUENCYIO peripherals_timer_reset(); -#endif + #endif -#if CIRCUITPY_PULSEIO + #if CIRCUITPY_PULSEIO esp32s2_peripherals_rmt_reset(); pulsein_reset(); -#endif + #endif -#if CIRCUITPY_PWMIO + #if CIRCUITPY_PWMIO pwmout_reset(); -#endif + #endif -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC rtc_reset(); -#endif + #endif -#if CIRCUITPY_TOUCHIO_USE_NATIVE + #if CIRCUITPY_TOUCHIO_USE_NATIVE peripherals_touch_reset(); -#endif + #endif -#if CIRCUITPY_WATCHDOG + #if CIRCUITPY_WATCHDOG watchdog_reset(); -#endif + #endif -#if CIRCUITPY_WIFI + #if CIRCUITPY_WIFI wifi_reset(); -#endif + #endif -#if CIRCUITPY_SOCKETPOOL + #if CIRCUITPY_SOCKETPOOL socket_reset(); -#endif + #endif } void reset_to_bootloader(void) { @@ -249,7 +249,7 @@ uint32_t *port_heap_get_top(void) { uint32_t *port_stack_get_limit(void) { #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" - return (uint32_t*) pxTaskGetStackStart(NULL); + return (uint32_t *)pxTaskGetStackStart(NULL); #pragma GCC diagnostic pop } @@ -281,7 +281,7 @@ uint32_t port_get_saved_word(void) { return REG_READ(RTC_CNTL_STORE0_REG); } -uint64_t port_get_raw_ticks(uint8_t* subticks) { +uint64_t port_get_raw_ticks(uint8_t *subticks) { // Convert microseconds to subticks of 1/32768 seconds // 32768/1000000 = 64/15625 in lowest terms // this arithmetic overflows after 570 years @@ -306,7 +306,7 @@ void port_wake_main_task() { xTaskNotifyGive(circuitpython_task); } -void sleep_timer_cb(void* arg) { +void sleep_timer_cb(void *arg) { port_wake_main_task(); } diff --git a/ports/esp32s2/supervisor/usb.c b/ports/esp32s2/supervisor/usb.c index 16657d4079..54ac88dc44 100644 --- a/ports/esp32s2/supervisor/usb.c +++ b/ports/esp32s2/supervisor/usb.c @@ -44,39 +44,36 @@ #include "tusb.h" #ifdef CFG_TUSB_DEBUG - #define USBD_STACK_SIZE (3*configMINIMAL_STACK_SIZE) + #define USBD_STACK_SIZE (3 * configMINIMAL_STACK_SIZE) #else - #define USBD_STACK_SIZE (3*configMINIMAL_STACK_SIZE/2) + #define USBD_STACK_SIZE (3 * configMINIMAL_STACK_SIZE / 2) #endif -StackType_t usb_device_stack[USBD_STACK_SIZE]; +StackType_t usb_device_stack[USBD_STACK_SIZE]; StaticTask_t usb_device_taskdef; // USB Device Driver task // This top level thread process all usb events and invoke callbacks -void usb_device_task(void* param) -{ - (void) param; +void usb_device_task(void *param) { + (void)param; - // RTOS forever loop - while (1) - { - // tinyusb device task - if (tusb_inited()) { - tud_task(); - tud_cdc_write_flush(); + // RTOS forever loop + while (1) { + // tinyusb device task + if (tusb_inited()) { + tud_task(); + tud_cdc_write_flush(); + } + vTaskDelay(1); } - vTaskDelay(1); - } } -static void configure_pins (usb_hal_context_t *usb) -{ +static void configure_pins(usb_hal_context_t *usb) { /* usb_periph_iopins currently configures USB_OTG as USB Device. * Introduce additional parameters in usb_hal_context_t when adding support * for USB Host. */ - for (const usb_iopin_dsc_t* iopin = usb_periph_iopins; iopin->pin != -1; ++iopin) { + for (const usb_iopin_dsc_t *iopin = usb_periph_iopins; iopin->pin != -1; ++iopin) { if ((usb->use_external_phy) || (iopin->ext_phy_only == 0)) { gpio_pad_select_gpio(iopin->pin); if (iopin->is_output) { @@ -103,22 +100,21 @@ void init_usb_hardware(void) { usb_hal_init(&hal); configure_pins(&hal); - (void) xTaskCreateStatic(usb_device_task, - "usbd", - USBD_STACK_SIZE, - NULL, - 5, - usb_device_stack, - &usb_device_taskdef); + (void)xTaskCreateStatic(usb_device_task, + "usbd", + USBD_STACK_SIZE, + NULL, + 5, + usb_device_stack, + &usb_device_taskdef); } /** * Callback invoked when received an "wanted" char. * @param itf Interface index (for multiple cdc interfaces) * @param wanted_char The wanted char (set previously) */ -void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char) -{ - (void) itf; // not used +void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char) { + (void)itf; // not used // Workaround for using lib/utils/interrupt_char.c // Compare mp_interrupt_char with wanted_char and ignore if not matched if (mp_interrupt_char == wanted_char) { diff --git a/ports/esp32s2/tools/decode_backtrace.py b/ports/esp32s2/tools/decode_backtrace.py index 3f078895af..523677baea 100644 --- a/ports/esp32s2/tools/decode_backtrace.py +++ b/ports/esp32s2/tools/decode_backtrace.py @@ -15,9 +15,10 @@ print(board) while True: addresses = input("? ") if addresses.startswith("Backtrace:"): - addresses = addresses[len("Backtrace:"):] + addresses = addresses[len("Backtrace:") :] addresses = addresses.strip().split() addresses = [address.split(":")[0] for address in addresses] - print('got', addresses) - subprocess.run(["xtensa-esp32s2-elf-addr2line", - "-e", "build-{}/firmware.elf".format(board)] + addresses) + print("got", addresses) + subprocess.run( + ["xtensa-esp32s2-elf-addr2line", "-e", "build-{}/firmware.elf".format(board)] + addresses + ) diff --git a/ports/litex/background.c b/ports/litex/background.c index 174d9588ac..da86919c0c 100644 --- a/ports/litex/background.c +++ b/ports/litex/background.c @@ -29,6 +29,9 @@ #include "supervisor/usb.h" #include "supervisor/shared/stack.h" -void port_background_task(void) {} -void port_start_background_task(void) {} -void port_finish_background_task(void) {} +void port_background_task(void) { +} +void port_start_background_task(void) { +} +void port_finish_background_task(void) { +} diff --git a/ports/litex/boards/fomu/csr.h b/ports/litex/boards/fomu/csr.h index bf66fe3a17..7405d43125 100644 --- a/ports/litex/boards/fomu/csr.h +++ b/ports/litex/boards/fomu/csr.h @@ -1,6 +1,6 @@ -//-------------------------------------------------------------------------------- +// -------------------------------------------------------------------------------- // Auto-generated by Migen (f4fcd10) & LiteX (de205d4a) on 2019-11-25 14:57:34 -//-------------------------------------------------------------------------------- +// -------------------------------------------------------------------------------- #include #ifndef __GENERATED_CSR_H #define __GENERATED_CSR_H @@ -21,41 +21,41 @@ extern uint32_t csr_readl(unsigned long addr); #define CSR_CTRL_RESET_ADDR 0xe0000000L #define CSR_CTRL_RESET_SIZE 1 static inline unsigned char ctrl_reset_read(void) { - unsigned char r = csr_readl(0xe0000000L); - return r; + unsigned char r = csr_readl(0xe0000000L); + return r; } static inline void ctrl_reset_write(unsigned char value) { - csr_writel(value, 0xe0000000L); + csr_writel(value, 0xe0000000L); } #define CSR_CTRL_SCRATCH_ADDR 0xe0000004L #define CSR_CTRL_SCRATCH_SIZE 4 static inline unsigned int ctrl_scratch_read(void) { - unsigned int r = csr_readl(0xe0000004L); - r <<= 8; - r |= csr_readl(0xe0000008L); - r <<= 8; - r |= csr_readl(0xe000000cL); - r <<= 8; - r |= csr_readl(0xe0000010L); - return r; + unsigned int r = csr_readl(0xe0000004L); + r <<= 8; + r |= csr_readl(0xe0000008L); + r <<= 8; + r |= csr_readl(0xe000000cL); + r <<= 8; + r |= csr_readl(0xe0000010L); + return r; } static inline void ctrl_scratch_write(unsigned int value) { - csr_writel(value >> 24, 0xe0000004L); - csr_writel(value >> 16, 0xe0000008L); - csr_writel(value >> 8, 0xe000000cL); - csr_writel(value, 0xe0000010L); + csr_writel(value >> 24, 0xe0000004L); + csr_writel(value >> 16, 0xe0000008L); + csr_writel(value >> 8, 0xe000000cL); + csr_writel(value, 0xe0000010L); } #define CSR_CTRL_BUS_ERRORS_ADDR 0xe0000014L #define CSR_CTRL_BUS_ERRORS_SIZE 4 static inline unsigned int ctrl_bus_errors_read(void) { - unsigned int r = csr_readl(0xe0000014L); - r <<= 8; - r |= csr_readl(0xe0000018L); - r <<= 8; - r |= csr_readl(0xe000001cL); - r <<= 8; - r |= csr_readl(0xe0000020L); - return r; + unsigned int r = csr_readl(0xe0000014L); + r <<= 8; + r |= csr_readl(0xe0000018L); + r <<= 8; + r |= csr_readl(0xe000001cL); + r <<= 8; + r |= csr_readl(0xe0000020L); + return r; } /* lxspi */ @@ -63,11 +63,11 @@ static inline unsigned int ctrl_bus_errors_read(void) { #define CSR_LXSPI_BITBANG_ADDR 0xe0007800L #define CSR_LXSPI_BITBANG_SIZE 1 static inline unsigned char lxspi_bitbang_read(void) { - unsigned char r = csr_readl(0xe0007800L); - return r; + unsigned char r = csr_readl(0xe0007800L); + return r; } static inline void lxspi_bitbang_write(unsigned char value) { - csr_writel(value, 0xe0007800L); + csr_writel(value, 0xe0007800L); } #define CSR_LXSPI_BITBANG_MOSI_OFFSET 0 #define CSR_LXSPI_BITBANG_MOSI_SIZE 1 @@ -80,17 +80,17 @@ static inline void lxspi_bitbang_write(unsigned char value) { #define CSR_LXSPI_MISO_ADDR 0xe0007804L #define CSR_LXSPI_MISO_SIZE 1 static inline unsigned char lxspi_miso_read(void) { - unsigned char r = csr_readl(0xe0007804L); - return r; + unsigned char r = csr_readl(0xe0007804L); + return r; } #define CSR_LXSPI_BITBANG_EN_ADDR 0xe0007808L #define CSR_LXSPI_BITBANG_EN_SIZE 1 static inline unsigned char lxspi_bitbang_en_read(void) { - unsigned char r = csr_readl(0xe0007808L); - return r; + unsigned char r = csr_readl(0xe0007808L); + return r; } static inline void lxspi_bitbang_en_write(unsigned char value) { - csr_writel(value, 0xe0007808L); + csr_writel(value, 0xe0007808L); } /* messible */ @@ -98,23 +98,23 @@ static inline void lxspi_bitbang_en_write(unsigned char value) { #define CSR_MESSIBLE_IN_ADDR 0xe0008000L #define CSR_MESSIBLE_IN_SIZE 1 static inline unsigned char messible_in_read(void) { - unsigned char r = csr_readl(0xe0008000L); - return r; + unsigned char r = csr_readl(0xe0008000L); + return r; } static inline void messible_in_write(unsigned char value) { - csr_writel(value, 0xe0008000L); + csr_writel(value, 0xe0008000L); } #define CSR_MESSIBLE_OUT_ADDR 0xe0008004L #define CSR_MESSIBLE_OUT_SIZE 1 static inline unsigned char messible_out_read(void) { - unsigned char r = csr_readl(0xe0008004L); - return r; + unsigned char r = csr_readl(0xe0008004L); + return r; } #define CSR_MESSIBLE_STATUS_ADDR 0xe0008008L #define CSR_MESSIBLE_STATUS_SIZE 1 static inline unsigned char messible_status_read(void) { - unsigned char r = csr_readl(0xe0008008L); - return r; + unsigned char r = csr_readl(0xe0008008L); + return r; } #define CSR_MESSIBLE_STATUS_FULL_OFFSET 0 #define CSR_MESSIBLE_STATUS_FULL_SIZE 1 @@ -126,11 +126,11 @@ static inline unsigned char messible_status_read(void) { #define CSR_REBOOT_CTRL_ADDR 0xe0006000L #define CSR_REBOOT_CTRL_SIZE 1 static inline unsigned char reboot_ctrl_read(void) { - unsigned char r = csr_readl(0xe0006000L); - return r; + unsigned char r = csr_readl(0xe0006000L); + return r; } static inline void reboot_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0006000L); + csr_writel(value, 0xe0006000L); } #define CSR_REBOOT_CTRL_IMAGE_OFFSET 0 #define CSR_REBOOT_CTRL_IMAGE_SIZE 2 @@ -139,20 +139,20 @@ static inline void reboot_ctrl_write(unsigned char value) { #define CSR_REBOOT_ADDR_ADDR 0xe0006004L #define CSR_REBOOT_ADDR_SIZE 4 static inline unsigned int reboot_addr_read(void) { - unsigned int r = csr_readl(0xe0006004L); - r <<= 8; - r |= csr_readl(0xe0006008L); - r <<= 8; - r |= csr_readl(0xe000600cL); - r <<= 8; - r |= csr_readl(0xe0006010L); - return r; + unsigned int r = csr_readl(0xe0006004L); + r <<= 8; + r |= csr_readl(0xe0006008L); + r <<= 8; + r |= csr_readl(0xe000600cL); + r <<= 8; + r |= csr_readl(0xe0006010L); + return r; } static inline void reboot_addr_write(unsigned int value) { - csr_writel(value >> 24, 0xe0006004L); - csr_writel(value >> 16, 0xe0006008L); - csr_writel(value >> 8, 0xe000600cL); - csr_writel(value, 0xe0006010L); + csr_writel(value >> 24, 0xe0006004L); + csr_writel(value >> 16, 0xe0006008L); + csr_writel(value >> 8, 0xe000600cL); + csr_writel(value, 0xe0006010L); } /* rgb */ @@ -160,29 +160,29 @@ static inline void reboot_addr_write(unsigned int value) { #define CSR_RGB_DAT_ADDR 0xe0006800L #define CSR_RGB_DAT_SIZE 1 static inline unsigned char rgb_dat_read(void) { - unsigned char r = csr_readl(0xe0006800L); - return r; + unsigned char r = csr_readl(0xe0006800L); + return r; } static inline void rgb_dat_write(unsigned char value) { - csr_writel(value, 0xe0006800L); + csr_writel(value, 0xe0006800L); } #define CSR_RGB_ADDR_ADDR 0xe0006804L #define CSR_RGB_ADDR_SIZE 1 static inline unsigned char rgb_addr_read(void) { - unsigned char r = csr_readl(0xe0006804L); - return r; + unsigned char r = csr_readl(0xe0006804L); + return r; } static inline void rgb_addr_write(unsigned char value) { - csr_writel(value, 0xe0006804L); + csr_writel(value, 0xe0006804L); } #define CSR_RGB_CTRL_ADDR 0xe0006808L #define CSR_RGB_CTRL_SIZE 1 static inline unsigned char rgb_ctrl_read(void) { - unsigned char r = csr_readl(0xe0006808L); - return r; + unsigned char r = csr_readl(0xe0006808L); + return r; } static inline void rgb_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0006808L); + csr_writel(value, 0xe0006808L); } #define CSR_RGB_CTRL_EXE_OFFSET 0 #define CSR_RGB_CTRL_EXE_SIZE 1 @@ -199,11 +199,11 @@ static inline void rgb_ctrl_write(unsigned char value) { #define CSR_RGB_RAW_ADDR 0xe000680cL #define CSR_RGB_RAW_SIZE 1 static inline unsigned char rgb_raw_read(void) { - unsigned char r = csr_readl(0xe000680cL); - return r; + unsigned char r = csr_readl(0xe000680cL); + return r; } static inline void rgb_raw_write(unsigned char value) { - csr_writel(value, 0xe000680cL); + csr_writel(value, 0xe000680cL); } #define CSR_RGB_RAW_R_OFFSET 0 #define CSR_RGB_RAW_R_SIZE 1 @@ -217,95 +217,95 @@ static inline void rgb_raw_write(unsigned char value) { #define CSR_TIMER0_LOAD_ADDR 0xe0002800L #define CSR_TIMER0_LOAD_SIZE 4 static inline unsigned int timer0_load_read(void) { - unsigned int r = csr_readl(0xe0002800L); - r <<= 8; - r |= csr_readl(0xe0002804L); - r <<= 8; - r |= csr_readl(0xe0002808L); - r <<= 8; - r |= csr_readl(0xe000280cL); - return r; + unsigned int r = csr_readl(0xe0002800L); + r <<= 8; + r |= csr_readl(0xe0002804L); + r <<= 8; + r |= csr_readl(0xe0002808L); + r <<= 8; + r |= csr_readl(0xe000280cL); + return r; } static inline void timer0_load_write(unsigned int value) { - csr_writel(value >> 24, 0xe0002800L); - csr_writel(value >> 16, 0xe0002804L); - csr_writel(value >> 8, 0xe0002808L); - csr_writel(value, 0xe000280cL); + csr_writel(value >> 24, 0xe0002800L); + csr_writel(value >> 16, 0xe0002804L); + csr_writel(value >> 8, 0xe0002808L); + csr_writel(value, 0xe000280cL); } #define CSR_TIMER0_RELOAD_ADDR 0xe0002810L #define CSR_TIMER0_RELOAD_SIZE 4 static inline unsigned int timer0_reload_read(void) { - unsigned int r = csr_readl(0xe0002810L); - r <<= 8; - r |= csr_readl(0xe0002814L); - r <<= 8; - r |= csr_readl(0xe0002818L); - r <<= 8; - r |= csr_readl(0xe000281cL); - return r; + unsigned int r = csr_readl(0xe0002810L); + r <<= 8; + r |= csr_readl(0xe0002814L); + r <<= 8; + r |= csr_readl(0xe0002818L); + r <<= 8; + r |= csr_readl(0xe000281cL); + return r; } static inline void timer0_reload_write(unsigned int value) { - csr_writel(value >> 24, 0xe0002810L); - csr_writel(value >> 16, 0xe0002814L); - csr_writel(value >> 8, 0xe0002818L); - csr_writel(value, 0xe000281cL); + csr_writel(value >> 24, 0xe0002810L); + csr_writel(value >> 16, 0xe0002814L); + csr_writel(value >> 8, 0xe0002818L); + csr_writel(value, 0xe000281cL); } #define CSR_TIMER0_EN_ADDR 0xe0002820L #define CSR_TIMER0_EN_SIZE 1 static inline unsigned char timer0_en_read(void) { - unsigned char r = csr_readl(0xe0002820L); - return r; + unsigned char r = csr_readl(0xe0002820L); + return r; } static inline void timer0_en_write(unsigned char value) { - csr_writel(value, 0xe0002820L); + csr_writel(value, 0xe0002820L); } #define CSR_TIMER0_UPDATE_VALUE_ADDR 0xe0002824L #define CSR_TIMER0_UPDATE_VALUE_SIZE 1 static inline unsigned char timer0_update_value_read(void) { - unsigned char r = csr_readl(0xe0002824L); - return r; + unsigned char r = csr_readl(0xe0002824L); + return r; } static inline void timer0_update_value_write(unsigned char value) { - csr_writel(value, 0xe0002824L); + csr_writel(value, 0xe0002824L); } #define CSR_TIMER0_VALUE_ADDR 0xe0002828L #define CSR_TIMER0_VALUE_SIZE 4 static inline unsigned int timer0_value_read(void) { - unsigned int r = csr_readl(0xe0002828L); - r <<= 8; - r |= csr_readl(0xe000282cL); - r <<= 8; - r |= csr_readl(0xe0002830L); - r <<= 8; - r |= csr_readl(0xe0002834L); - return r; + unsigned int r = csr_readl(0xe0002828L); + r <<= 8; + r |= csr_readl(0xe000282cL); + r <<= 8; + r |= csr_readl(0xe0002830L); + r <<= 8; + r |= csr_readl(0xe0002834L); + return r; } #define CSR_TIMER0_EV_STATUS_ADDR 0xe0002838L #define CSR_TIMER0_EV_STATUS_SIZE 1 static inline unsigned char timer0_ev_status_read(void) { - unsigned char r = csr_readl(0xe0002838L); - return r; + unsigned char r = csr_readl(0xe0002838L); + return r; } static inline void timer0_ev_status_write(unsigned char value) { - csr_writel(value, 0xe0002838L); + csr_writel(value, 0xe0002838L); } #define CSR_TIMER0_EV_PENDING_ADDR 0xe000283cL #define CSR_TIMER0_EV_PENDING_SIZE 1 static inline unsigned char timer0_ev_pending_read(void) { - unsigned char r = csr_readl(0xe000283cL); - return r; + unsigned char r = csr_readl(0xe000283cL); + return r; } static inline void timer0_ev_pending_write(unsigned char value) { - csr_writel(value, 0xe000283cL); + csr_writel(value, 0xe000283cL); } #define CSR_TIMER0_EV_ENABLE_ADDR 0xe0002840L #define CSR_TIMER0_EV_ENABLE_SIZE 1 static inline unsigned char timer0_ev_enable_read(void) { - unsigned char r = csr_readl(0xe0002840L); - return r; + unsigned char r = csr_readl(0xe0002840L); + return r; } static inline void timer0_ev_enable_write(unsigned char value) { - csr_writel(value, 0xe0002840L); + csr_writel(value, 0xe0002840L); } /* touch */ @@ -313,26 +313,26 @@ static inline void timer0_ev_enable_write(unsigned char value) { #define CSR_TOUCH_O_ADDR 0xe0005800L #define CSR_TOUCH_O_SIZE 1 static inline unsigned char touch_o_read(void) { - unsigned char r = csr_readl(0xe0005800L); - return r; + unsigned char r = csr_readl(0xe0005800L); + return r; } static inline void touch_o_write(unsigned char value) { - csr_writel(value, 0xe0005800L); + csr_writel(value, 0xe0005800L); } #define CSR_TOUCH_OE_ADDR 0xe0005804L #define CSR_TOUCH_OE_SIZE 1 static inline unsigned char touch_oe_read(void) { - unsigned char r = csr_readl(0xe0005804L); - return r; + unsigned char r = csr_readl(0xe0005804L); + return r; } static inline void touch_oe_write(unsigned char value) { - csr_writel(value, 0xe0005804L); + csr_writel(value, 0xe0005804L); } #define CSR_TOUCH_I_ADDR 0xe0005808L #define CSR_TOUCH_I_SIZE 1 static inline unsigned char touch_i_read(void) { - unsigned char r = csr_readl(0xe0005808L); - return r; + unsigned char r = csr_readl(0xe0005808L); + return r; } /* usb */ @@ -340,28 +340,28 @@ static inline unsigned char touch_i_read(void) { #define CSR_USB_PULLUP_OUT_ADDR 0xe0004800L #define CSR_USB_PULLUP_OUT_SIZE 1 static inline unsigned char usb_pullup_out_read(void) { - unsigned char r = csr_readl(0xe0004800L); - return r; + unsigned char r = csr_readl(0xe0004800L); + return r; } static inline void usb_pullup_out_write(unsigned char value) { - csr_writel(value, 0xe0004800L); + csr_writel(value, 0xe0004800L); } #define CSR_USB_ADDRESS_ADDR 0xe0004804L #define CSR_USB_ADDRESS_SIZE 1 static inline unsigned char usb_address_read(void) { - unsigned char r = csr_readl(0xe0004804L); - return r; + unsigned char r = csr_readl(0xe0004804L); + return r; } static inline void usb_address_write(unsigned char value) { - csr_writel(value, 0xe0004804L); + csr_writel(value, 0xe0004804L); } #define CSR_USB_ADDRESS_ADDR_OFFSET 0 #define CSR_USB_ADDRESS_ADDR_SIZE 7 #define CSR_USB_NEXT_EV_ADDR 0xe0004808L #define CSR_USB_NEXT_EV_SIZE 1 static inline unsigned char usb_next_ev_read(void) { - unsigned char r = csr_readl(0xe0004808L); - return r; + unsigned char r = csr_readl(0xe0004808L); + return r; } #define CSR_USB_NEXT_EV_IN_OFFSET 0 #define CSR_USB_NEXT_EV_IN_SIZE 1 @@ -374,27 +374,27 @@ static inline unsigned char usb_next_ev_read(void) { #define CSR_USB_SETUP_DATA_ADDR 0xe000480cL #define CSR_USB_SETUP_DATA_SIZE 1 static inline unsigned char usb_setup_data_read(void) { - unsigned char r = csr_readl(0xe000480cL); - return r; + unsigned char r = csr_readl(0xe000480cL); + return r; } #define CSR_USB_SETUP_DATA_DATA_OFFSET 0 #define CSR_USB_SETUP_DATA_DATA_SIZE 8 #define CSR_USB_SETUP_CTRL_ADDR 0xe0004810L #define CSR_USB_SETUP_CTRL_SIZE 1 static inline unsigned char usb_setup_ctrl_read(void) { - unsigned char r = csr_readl(0xe0004810L); - return r; + unsigned char r = csr_readl(0xe0004810L); + return r; } static inline void usb_setup_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0004810L); + csr_writel(value, 0xe0004810L); } #define CSR_USB_SETUP_CTRL_RESET_OFFSET 5 #define CSR_USB_SETUP_CTRL_RESET_SIZE 1 #define CSR_USB_SETUP_STATUS_ADDR 0xe0004814L #define CSR_USB_SETUP_STATUS_SIZE 1 static inline unsigned char usb_setup_status_read(void) { - unsigned char r = csr_readl(0xe0004814L); - return r; + unsigned char r = csr_readl(0xe0004814L); + return r; } #define CSR_USB_SETUP_STATUS_EPNO_OFFSET 0 #define CSR_USB_SETUP_STATUS_EPNO_SIZE 4 @@ -409,49 +409,49 @@ static inline unsigned char usb_setup_status_read(void) { #define CSR_USB_SETUP_EV_STATUS_ADDR 0xe0004818L #define CSR_USB_SETUP_EV_STATUS_SIZE 1 static inline unsigned char usb_setup_ev_status_read(void) { - unsigned char r = csr_readl(0xe0004818L); - return r; + unsigned char r = csr_readl(0xe0004818L); + return r; } static inline void usb_setup_ev_status_write(unsigned char value) { - csr_writel(value, 0xe0004818L); + csr_writel(value, 0xe0004818L); } #define CSR_USB_SETUP_EV_PENDING_ADDR 0xe000481cL #define CSR_USB_SETUP_EV_PENDING_SIZE 1 static inline unsigned char usb_setup_ev_pending_read(void) { - unsigned char r = csr_readl(0xe000481cL); - return r; + unsigned char r = csr_readl(0xe000481cL); + return r; } static inline void usb_setup_ev_pending_write(unsigned char value) { - csr_writel(value, 0xe000481cL); + csr_writel(value, 0xe000481cL); } #define CSR_USB_SETUP_EV_ENABLE_ADDR 0xe0004820L #define CSR_USB_SETUP_EV_ENABLE_SIZE 1 static inline unsigned char usb_setup_ev_enable_read(void) { - unsigned char r = csr_readl(0xe0004820L); - return r; + unsigned char r = csr_readl(0xe0004820L); + return r; } static inline void usb_setup_ev_enable_write(unsigned char value) { - csr_writel(value, 0xe0004820L); + csr_writel(value, 0xe0004820L); } #define CSR_USB_IN_DATA_ADDR 0xe0004824L #define CSR_USB_IN_DATA_SIZE 1 static inline unsigned char usb_in_data_read(void) { - unsigned char r = csr_readl(0xe0004824L); - return r; + unsigned char r = csr_readl(0xe0004824L); + return r; } static inline void usb_in_data_write(unsigned char value) { - csr_writel(value, 0xe0004824L); + csr_writel(value, 0xe0004824L); } #define CSR_USB_IN_DATA_DATA_OFFSET 0 #define CSR_USB_IN_DATA_DATA_SIZE 8 #define CSR_USB_IN_CTRL_ADDR 0xe0004828L #define CSR_USB_IN_CTRL_SIZE 1 static inline unsigned char usb_in_ctrl_read(void) { - unsigned char r = csr_readl(0xe0004828L); - return r; + unsigned char r = csr_readl(0xe0004828L); + return r; } static inline void usb_in_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0004828L); + csr_writel(value, 0xe0004828L); } #define CSR_USB_IN_CTRL_EPNO_OFFSET 0 #define CSR_USB_IN_CTRL_EPNO_SIZE 4 @@ -462,8 +462,8 @@ static inline void usb_in_ctrl_write(unsigned char value) { #define CSR_USB_IN_STATUS_ADDR 0xe000482cL #define CSR_USB_IN_STATUS_SIZE 1 static inline unsigned char usb_in_status_read(void) { - unsigned char r = csr_readl(0xe000482cL); - return r; + unsigned char r = csr_readl(0xe000482cL); + return r; } #define CSR_USB_IN_STATUS_IDLE_OFFSET 0 #define CSR_USB_IN_STATUS_IDLE_SIZE 1 @@ -474,46 +474,46 @@ static inline unsigned char usb_in_status_read(void) { #define CSR_USB_IN_EV_STATUS_ADDR 0xe0004830L #define CSR_USB_IN_EV_STATUS_SIZE 1 static inline unsigned char usb_in_ev_status_read(void) { - unsigned char r = csr_readl(0xe0004830L); - return r; + unsigned char r = csr_readl(0xe0004830L); + return r; } static inline void usb_in_ev_status_write(unsigned char value) { - csr_writel(value, 0xe0004830L); + csr_writel(value, 0xe0004830L); } #define CSR_USB_IN_EV_PENDING_ADDR 0xe0004834L #define CSR_USB_IN_EV_PENDING_SIZE 1 static inline unsigned char usb_in_ev_pending_read(void) { - unsigned char r = csr_readl(0xe0004834L); - return r; + unsigned char r = csr_readl(0xe0004834L); + return r; } static inline void usb_in_ev_pending_write(unsigned char value) { - csr_writel(value, 0xe0004834L); + csr_writel(value, 0xe0004834L); } #define CSR_USB_IN_EV_ENABLE_ADDR 0xe0004838L #define CSR_USB_IN_EV_ENABLE_SIZE 1 static inline unsigned char usb_in_ev_enable_read(void) { - unsigned char r = csr_readl(0xe0004838L); - return r; + unsigned char r = csr_readl(0xe0004838L); + return r; } static inline void usb_in_ev_enable_write(unsigned char value) { - csr_writel(value, 0xe0004838L); + csr_writel(value, 0xe0004838L); } #define CSR_USB_OUT_DATA_ADDR 0xe000483cL #define CSR_USB_OUT_DATA_SIZE 1 static inline unsigned char usb_out_data_read(void) { - unsigned char r = csr_readl(0xe000483cL); - return r; + unsigned char r = csr_readl(0xe000483cL); + return r; } #define CSR_USB_OUT_DATA_DATA_OFFSET 0 #define CSR_USB_OUT_DATA_DATA_SIZE 8 #define CSR_USB_OUT_CTRL_ADDR 0xe0004840L #define CSR_USB_OUT_CTRL_SIZE 1 static inline unsigned char usb_out_ctrl_read(void) { - unsigned char r = csr_readl(0xe0004840L); - return r; + unsigned char r = csr_readl(0xe0004840L); + return r; } static inline void usb_out_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0004840L); + csr_writel(value, 0xe0004840L); } #define CSR_USB_OUT_CTRL_EPNO_OFFSET 0 #define CSR_USB_OUT_CTRL_EPNO_SIZE 4 @@ -526,8 +526,8 @@ static inline void usb_out_ctrl_write(unsigned char value) { #define CSR_USB_OUT_STATUS_ADDR 0xe0004844L #define CSR_USB_OUT_STATUS_SIZE 1 static inline unsigned char usb_out_status_read(void) { - unsigned char r = csr_readl(0xe0004844L); - return r; + unsigned char r = csr_readl(0xe0004844L); + return r; } #define CSR_USB_OUT_STATUS_EPNO_OFFSET 0 #define CSR_USB_OUT_STATUS_EPNO_SIZE 4 @@ -538,41 +538,41 @@ static inline unsigned char usb_out_status_read(void) { #define CSR_USB_OUT_EV_STATUS_ADDR 0xe0004848L #define CSR_USB_OUT_EV_STATUS_SIZE 1 static inline unsigned char usb_out_ev_status_read(void) { - unsigned char r = csr_readl(0xe0004848L); - return r; + unsigned char r = csr_readl(0xe0004848L); + return r; } static inline void usb_out_ev_status_write(unsigned char value) { - csr_writel(value, 0xe0004848L); + csr_writel(value, 0xe0004848L); } #define CSR_USB_OUT_EV_PENDING_ADDR 0xe000484cL #define CSR_USB_OUT_EV_PENDING_SIZE 1 static inline unsigned char usb_out_ev_pending_read(void) { - unsigned char r = csr_readl(0xe000484cL); - return r; + unsigned char r = csr_readl(0xe000484cL); + return r; } static inline void usb_out_ev_pending_write(unsigned char value) { - csr_writel(value, 0xe000484cL); + csr_writel(value, 0xe000484cL); } #define CSR_USB_OUT_EV_ENABLE_ADDR 0xe0004850L #define CSR_USB_OUT_EV_ENABLE_SIZE 1 static inline unsigned char usb_out_ev_enable_read(void) { - unsigned char r = csr_readl(0xe0004850L); - return r; + unsigned char r = csr_readl(0xe0004850L); + return r; } static inline void usb_out_ev_enable_write(unsigned char value) { - csr_writel(value, 0xe0004850L); + csr_writel(value, 0xe0004850L); } #define CSR_USB_OUT_ENABLE_STATUS_ADDR 0xe0004854L #define CSR_USB_OUT_ENABLE_STATUS_SIZE 1 static inline unsigned char usb_out_enable_status_read(void) { - unsigned char r = csr_readl(0xe0004854L); - return r; + unsigned char r = csr_readl(0xe0004854L); + return r; } #define CSR_USB_OUT_STALL_STATUS_ADDR 0xe0004858L #define CSR_USB_OUT_STALL_STATUS_SIZE 1 static inline unsigned char usb_out_stall_status_read(void) { - unsigned char r = csr_readl(0xe0004858L); - return r; + unsigned char r = csr_readl(0xe0004858L); + return r; } /* version */ @@ -580,68 +580,68 @@ static inline unsigned char usb_out_stall_status_read(void) { #define CSR_VERSION_MAJOR_ADDR 0xe0007000L #define CSR_VERSION_MAJOR_SIZE 1 static inline unsigned char version_major_read(void) { - unsigned char r = csr_readl(0xe0007000L); - return r; + unsigned char r = csr_readl(0xe0007000L); + return r; } #define CSR_VERSION_MINOR_ADDR 0xe0007004L #define CSR_VERSION_MINOR_SIZE 1 static inline unsigned char version_minor_read(void) { - unsigned char r = csr_readl(0xe0007004L); - return r; + unsigned char r = csr_readl(0xe0007004L); + return r; } #define CSR_VERSION_REVISION_ADDR 0xe0007008L #define CSR_VERSION_REVISION_SIZE 1 static inline unsigned char version_revision_read(void) { - unsigned char r = csr_readl(0xe0007008L); - return r; + unsigned char r = csr_readl(0xe0007008L); + return r; } #define CSR_VERSION_GITREV_ADDR 0xe000700cL #define CSR_VERSION_GITREV_SIZE 4 static inline unsigned int version_gitrev_read(void) { - unsigned int r = csr_readl(0xe000700cL); - r <<= 8; - r |= csr_readl(0xe0007010L); - r <<= 8; - r |= csr_readl(0xe0007014L); - r <<= 8; - r |= csr_readl(0xe0007018L); - return r; + unsigned int r = csr_readl(0xe000700cL); + r <<= 8; + r |= csr_readl(0xe0007010L); + r <<= 8; + r |= csr_readl(0xe0007014L); + r <<= 8; + r |= csr_readl(0xe0007018L); + return r; } #define CSR_VERSION_GITEXTRA_ADDR 0xe000701cL #define CSR_VERSION_GITEXTRA_SIZE 2 static inline unsigned short int version_gitextra_read(void) { - unsigned short int r = csr_readl(0xe000701cL); - r <<= 8; - r |= csr_readl(0xe0007020L); - return r; + unsigned short int r = csr_readl(0xe000701cL); + r <<= 8; + r |= csr_readl(0xe0007020L); + return r; } #define CSR_VERSION_DIRTY_ADDR 0xe0007024L #define CSR_VERSION_DIRTY_SIZE 1 static inline unsigned char version_dirty_read(void) { - unsigned char r = csr_readl(0xe0007024L); - return r; + unsigned char r = csr_readl(0xe0007024L); + return r; } #define CSR_VERSION_DIRTY_DIRTY_OFFSET 0 #define CSR_VERSION_DIRTY_DIRTY_SIZE 1 #define CSR_VERSION_MODEL_ADDR 0xe0007028L #define CSR_VERSION_MODEL_SIZE 1 static inline unsigned char version_model_read(void) { - unsigned char r = csr_readl(0xe0007028L); - return r; + unsigned char r = csr_readl(0xe0007028L); + return r; } #define CSR_VERSION_MODEL_MODEL_OFFSET 0 #define CSR_VERSION_MODEL_MODEL_SIZE 8 #define CSR_VERSION_SEED_ADDR 0xe000702cL #define CSR_VERSION_SEED_SIZE 4 static inline unsigned int version_seed_read(void) { - unsigned int r = csr_readl(0xe000702cL); - r <<= 8; - r |= csr_readl(0xe0007030L); - r <<= 8; - r |= csr_readl(0xe0007034L); - r <<= 8; - r |= csr_readl(0xe0007038L); - return r; + unsigned int r = csr_readl(0xe000702cL); + r <<= 8; + r |= csr_readl(0xe0007030L); + r <<= 8; + r |= csr_readl(0xe0007034L); + r <<= 8; + r |= csr_readl(0xe0007038L); + return r; } #endif diff --git a/ports/litex/boards/fomu/generated/soc.h b/ports/litex/boards/fomu/generated/soc.h index 91b2f1a310..1d73bbf0ff 100644 --- a/ports/litex/boards/fomu/generated/soc.h +++ b/ports/litex/boards/fomu/generated/soc.h @@ -1,58 +1,58 @@ -//-------------------------------------------------------------------------------- +// -------------------------------------------------------------------------------- // Auto-generated by Migen (f4fcd10) & LiteX (de205d4a) on 2019-11-25 15:17:59 -//-------------------------------------------------------------------------------- +// -------------------------------------------------------------------------------- #ifndef __GENERATED_SOC_H #define __GENERATED_SOC_H #define CONFIG_BITSTREAM_SYNC_HEADER1 2123999870 static inline int config_bitstream_sync_header1_read(void) { - return 2123999870; + return 2123999870; } #define CONFIG_BITSTREAM_SYNC_HEADER2 2125109630 static inline int config_bitstream_sync_header2_read(void) { - return 2125109630; + return 2125109630; } #define CONFIG_CLOCK_FREQUENCY 12000000 static inline int config_clock_frequency_read(void) { - return 12000000; + return 12000000; } #define CONFIG_CPU_RESET_ADDR 0 static inline int config_cpu_reset_addr_read(void) { - return 0; + return 0; } #define CONFIG_CPU_TYPE "VEXRISCV" -static inline const char * config_cpu_type_read(void) { - return "VEXRISCV"; +static inline const char *config_cpu_type_read(void) { + return "VEXRISCV"; } #define CONFIG_CPU_TYPE_VEXRISCV #define CONFIG_CPU_VARIANT "MIN" -static inline const char * config_cpu_variant_read(void) { - return "MIN"; +static inline const char *config_cpu_variant_read(void) { + return "MIN"; } #define CONFIG_CPU_VARIANT_MIN #define CONFIG_CSR_ALIGNMENT 32 static inline int config_csr_alignment_read(void) { - return 32; + return 32; } #define CONFIG_CSR_DATA_WIDTH 8 static inline int config_csr_data_width_read(void) { - return 8; + return 8; } #define CONFIG_FOMU_REV "HACKER" -static inline const char * config_fomu_rev_read(void) { - return "HACKER"; +static inline const char *config_fomu_rev_read(void) { + return "HACKER"; } #define CONFIG_FOMU_REV_HACKER #define CONFIG_SHADOW_BASE 2147483648 static inline int config_shadow_base_read(void) { - return 2147483648; + return 2147483648; } #define TIMER0_INTERRUPT 2 static inline int timer0_interrupt_read(void) { - return 2; + return 2; } #define USB_INTERRUPT 3 static inline int usb_interrupt_read(void) { - return 3; + return 3; } #endif diff --git a/ports/litex/boards/fomu/mpconfigboard.h b/ports/litex/boards/fomu/mpconfigboard.h index 127301eee2..fd627c0b05 100644 --- a/ports/litex/boards/fomu/mpconfigboard.h +++ b/ports/litex/boards/fomu/mpconfigboard.h @@ -24,14 +24,14 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Fomu" #define MICROPY_HW_MCU_NAME "VexRiscv" #define FLASH_SIZE (0x100000) #define FLASH_PAGE_SIZE (0x1000) -#define FLASH_PARTITION_OFFSET_BYTES (1024*1024) +#define FLASH_PARTITION_OFFSET_BYTES (1024 * 1024) #define AUTORESET_DELAY_MS 500 #define BOARD_FLASH_SIZE (FLASH_SIZE) diff --git a/ports/litex/boards/fomu/pins.c b/ports/litex/boards/fomu/pins.c index 6be495c331..804a8b37f9 100644 --- a/ports/litex/boards/fomu/pins.c +++ b/ports/litex/boards/fomu/pins.c @@ -1,9 +1,9 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_global_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_TOUCH1), MP_ROM_PTR(&pin_TOUCH1) }, - { MP_ROM_QSTR(MP_QSTR_TOUCH2), MP_ROM_PTR(&pin_TOUCH2) }, - { MP_ROM_QSTR(MP_QSTR_TOUCH3), MP_ROM_PTR(&pin_TOUCH3) }, - { MP_ROM_QSTR(MP_QSTR_TOUCH4), MP_ROM_PTR(&pin_TOUCH4) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH1), MP_ROM_PTR(&pin_TOUCH1) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH2), MP_ROM_PTR(&pin_TOUCH2) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH3), MP_ROM_PTR(&pin_TOUCH3) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH4), MP_ROM_PTR(&pin_TOUCH4) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_global_dict_table); diff --git a/ports/litex/common-hal/digitalio/DigitalInOut.c b/ports/litex/common-hal/digitalio/DigitalInOut.c index 53df637c43..96cc95dfa6 100644 --- a/ports/litex/common-hal/digitalio/DigitalInOut.c +++ b/ports/litex/common-hal/digitalio/DigitalInOut.c @@ -32,12 +32,12 @@ #include "csr.h" void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { (void)self; } digitalinout_result_t common_hal_digitalio_digitalinout_construct( - digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { + digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { // claim_pin(pin); self->pin = pin; @@ -59,14 +59,14 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self } void common_hal_digitalio_digitalinout_switch_to_input( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { (void)pull; touch_oe_write(touch_oe_read() & ~(1 << self->pin->number)); } digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( - digitalio_digitalinout_obj_t *self, bool value, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, bool value, + digitalio_drive_mode_t drive_mode) { (void)drive_mode; common_hal_digitalio_digitalinout_set_value(self, value); touch_oe_write(touch_oe_read() | (1 << self->pin->number)); @@ -74,48 +74,50 @@ digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( } digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { return (touch_oe_read() & (1 << self->pin->number)) ? DIRECTION_OUTPUT : DIRECTION_INPUT; } void common_hal_digitalio_digitalinout_set_value( - digitalio_digitalinout_obj_t *self, bool value) { - if (value) + digitalio_digitalinout_obj_t *self, bool value) { + if (value) { touch_o_write(touch_o_read() | (1 << self->pin->number)); - else + } else { touch_o_write(touch_o_read() & ~(1 << self->pin->number)); + } } bool common_hal_digitalio_digitalinout_get_value( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { return !!(touch_i_read() & (1 << self->pin->number)); } digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( - digitalio_digitalinout_obj_t *self, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, + digitalio_drive_mode_t drive_mode) { (void)self; (void)drive_mode; return DIGITALINOUT_OK; } digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( - digitalio_digitalinout_obj_t *self) { - if (common_hal_digitalio_digitalinout_get_direction(self) == DIRECTION_OUTPUT) + digitalio_digitalinout_obj_t *self) { + if (common_hal_digitalio_digitalinout_get_direction(self) == DIRECTION_OUTPUT) { return DRIVE_MODE_PUSH_PULL; - else + } else { return DRIVE_MODE_OPEN_DRAIN; + } } void common_hal_digitalio_digitalinout_set_pull( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { (void)self; (void)pull; } digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { return PULL_NONE; } diff --git a/ports/litex/common-hal/microcontroller/Pin.c b/ports/litex/common-hal/microcontroller/Pin.c index 4d088a0763..1cc4c41d58 100644 --- a/ports/litex/common-hal/microcontroller/Pin.c +++ b/ports/litex/common-hal/microcontroller/Pin.c @@ -38,27 +38,27 @@ void reset_pin_number(uint8_t pin_port, uint8_t pin_number) { } // Clear claimed bit. - claimed_pins[pin_port] &= ~(1<number); } -void claim_pin(const mcu_pin_obj_t* pin) { +void claim_pin(const mcu_pin_obj_t *pin) { // Set bit in claimed_pins bitmask. - claimed_pins[0] |= 1<number; + claimed_pins[0] |= 1 << pin->number; } -void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) { +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { claim_pin(pin); } bool pin_number_is_free(uint8_t pin_port, uint8_t pin_number) { - return !(claimed_pins[pin_port] & 1< 0) { @@ -82,14 +82,17 @@ void common_hal_mcu_enable_interrupts(void) { } void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { - if(runmode == RUNMODE_SAFE_MODE) + if (runmode == RUNMODE_SAFE_MODE) { safe_mode_on_next_reset(PROGRAMMATIC_SAFE_MODE); + } } void common_hal_mcu_reset(void) { - filesystem_flush(); //TODO: implement as part of flash improvements + filesystem_flush(); // TODO: implement as part of flash improvements // NVIC_SystemReset(); - while(1); + while (1) { + ; + } } // The singleton microcontroller.Processor object, bound to microcontroller.cpu @@ -106,9 +109,9 @@ const mcu_pin_obj_t pin_TOUCH3 = PIN(2); const mcu_pin_obj_t pin_TOUCH4 = PIN(3); STATIC const mp_rom_map_elem_t mcu_pin_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR_TOUCH1), MP_ROM_PTR(&pin_TOUCH1) }, - { MP_ROM_QSTR(MP_QSTR_TOUCH2), MP_ROM_PTR(&pin_TOUCH2) }, - { MP_ROM_QSTR(MP_QSTR_TOUCH3), MP_ROM_PTR(&pin_TOUCH3) }, - { MP_ROM_QSTR(MP_QSTR_TOUCH4), MP_ROM_PTR(&pin_TOUCH4) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH1), MP_ROM_PTR(&pin_TOUCH1) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH2), MP_ROM_PTR(&pin_TOUCH2) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH3), MP_ROM_PTR(&pin_TOUCH3) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH4), MP_ROM_PTR(&pin_TOUCH4) }, }; MP_DEFINE_CONST_DICT(mcu_pin_globals, mcu_pin_globals_table); diff --git a/ports/litex/common-hal/neopixel_write/__init__.c b/ports/litex/common-hal/neopixel_write/__init__.c index 29fd318d40..e7e5600fb1 100644 --- a/ports/litex/common-hal/neopixel_write/__init__.c +++ b/ports/litex/common-hal/neopixel_write/__init__.c @@ -60,8 +60,9 @@ static void ledda_write(uint8_t value, uint8_t addr) { static int ledda_init_done; static void ledda_init(void) { - if (ledda_init_done) + if (ledda_init_done) { return; + } // Enable the driver rgb_ctrl_write((1 << CSR_RGB_CTRL_EXE_OFFSET) | (1 << CSR_RGB_CTRL_CURREN_OFFSET) | (1 << CSR_RGB_CTRL_RGBLEDEN_OFFSET)); @@ -69,7 +70,7 @@ static void ledda_init(void) { ledda_write(LEDDCR0_LEDDEN | LEDDCR0_FR250 | LEDDCR0_QUICKSTOP, LEDDCR0); // Set clock register to 12 MHz / 64 kHz - 1 - ledda_write((12000000/64000)-1, LEDDBR); + ledda_write((12000000 / 64000) - 1, LEDDBR); // Ensure LED "breathe" effect is diabled ledda_write(0, LEDDBCRR); @@ -82,7 +83,7 @@ static void ledda_init(void) { ledda_init_done = 1; } -void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout, uint8_t *pixels, uint32_t numBytes) { +void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, uint8_t *pixels, uint32_t numBytes) { (void)digitalinout; (void)numBytes; ledda_init(); diff --git a/ports/litex/common-hal/os/__init__.c b/ports/litex/common-hal/os/__init__.c index 578f3e8c63..c070c2777e 100644 --- a/ports/litex/common-hal/os/__init__.c +++ b/ports/litex/common-hal/os/__init__.c @@ -50,12 +50,12 @@ STATIC MP_DEFINE_ATTRTUPLE( (mp_obj_t)&os_uname_info_release_obj, (mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj -); + ); mp_obj_t common_hal_os_uname(void) { return (mp_obj_t)&os_uname_info_obj; } -bool common_hal_os_urandom(uint8_t* buffer, uint32_t length) { +bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { return false; } diff --git a/ports/litex/common-hal/supervisor/Runtime.c b/ports/litex/common-hal/supervisor/Runtime.c index 974f26cec1..f827651781 100644 --- a/ports/litex/common-hal/supervisor/Runtime.c +++ b/ports/litex/common-hal/supervisor/Runtime.c @@ -29,9 +29,9 @@ #include "supervisor/serial.h" bool common_hal_supervisor_runtime_get_serial_connected(void) { - return (bool) serial_connected(); + return (bool)serial_connected(); } bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); + return (bool)serial_bytes_available(); } diff --git a/ports/litex/fatfs_port.c b/ports/litex/fatfs_port.c index 8bdc047c12..631f7f0982 100644 --- a/ports/litex/fatfs_port.c +++ b/ports/litex/fatfs_port.c @@ -28,6 +28,6 @@ #include "lib/oofatfs/ff.h" DWORD get_fattime(void) { - // TODO: Implement this function. For now, fake it. + // TODO: Implement this function. For now, fake it. return ((2016 - 1980) << 25) | ((12) << 21) | ((4) << 16) | ((00) << 11) | ((18) << 5) | (23 / 2); } diff --git a/ports/litex/hw/common.h b/ports/litex/hw/common.h index b902bc4f27..8b3a0304ee 100644 --- a/ports/litex/hw/common.h +++ b/ports/litex/hw/common.h @@ -1,33 +1,27 @@ #ifndef _HW_COMMON_H_ #define _HW_COMMON_H_ #include -static inline void csr_writeb(uint8_t value, uint32_t addr) -{ - *((volatile uint8_t *)addr) = value; +static inline void csr_writeb(uint8_t value, uint32_t addr) { + *((volatile uint8_t *)addr) = value; } -static inline uint8_t csr_readb(uint32_t addr) -{ - return *(volatile uint8_t *)addr; +static inline uint8_t csr_readb(uint32_t addr) { + return *(volatile uint8_t *)addr; } -static inline void csr_writew(uint16_t value, uint32_t addr) -{ - *((volatile uint16_t *)addr) = value; +static inline void csr_writew(uint16_t value, uint32_t addr) { + *((volatile uint16_t *)addr) = value; } -static inline uint16_t csr_readw(uint32_t addr) -{ - return *(volatile uint16_t *)addr; +static inline uint16_t csr_readw(uint32_t addr) { + return *(volatile uint16_t *)addr; } -static inline void csr_writel(uint32_t value, uint32_t addr) -{ - *((volatile uint32_t *)addr) = value; +static inline void csr_writel(uint32_t value, uint32_t addr) { + *((volatile uint32_t *)addr) = value; } -static inline uint32_t csr_readl(uint32_t addr) -{ - return *(volatile uint32_t *)addr; +static inline uint32_t csr_readl(uint32_t addr) { + return *(volatile uint32_t *)addr; } #endif /* _HW_COMMON_H_ */ diff --git a/ports/litex/irq.h b/ports/litex/irq.h index dc96c228d8..34c8b0a10a 100644 --- a/ports/litex/irq.h +++ b/ports/litex/irq.h @@ -14,54 +14,53 @@ extern "C" { #define CSR_DCACHE_INFO 0xCC0 #define csrr(reg) ({ unsigned long __tmp; \ - asm volatile ("csrr %0, " #reg : "=r"(__tmp)); \ - __tmp; }) + asm volatile ("csrr %0, " #reg : "=r" (__tmp)); \ + __tmp; }) #define csrw(reg, val) ({ \ - if (__builtin_constant_p(val) && (unsigned long)(val) < 32) \ - asm volatile ("csrw " #reg ", %0" :: "i"(val)); \ - else \ - asm volatile ("csrw " #reg ", %0" :: "r"(val)); }) + if (__builtin_constant_p(val) && (unsigned long)(val) < 32) \ + asm volatile ("csrw " #reg ", %0" : : "i" (val)); \ + else \ + asm volatile ("csrw " #reg ", %0" : : "r" (val)); }) #define csrs(reg, bit) ({ \ - if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ - asm volatile ("csrrs x0, " #reg ", %0" :: "i"(bit)); \ - else \ - asm volatile ("csrrs x0, " #reg ", %0" :: "r"(bit)); }) + if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ + asm volatile ("csrrs x0, " #reg ", %0" : : "i" (bit)); \ + else \ + asm volatile ("csrrs x0, " #reg ", %0" : : "r" (bit)); }) #define csrc(reg, bit) ({ \ - if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ - asm volatile ("csrrc x0, " #reg ", %0" :: "i"(bit)); \ - else \ - asm volatile ("csrrc x0, " #reg ", %0" :: "r"(bit)); }) + if (__builtin_constant_p(bit) && (unsigned long)(bit) < 32) \ + asm volatile ("csrrc x0, " #reg ", %0" : : "i" (bit)); \ + else \ + asm volatile ("csrrc x0, " #reg ", %0" : : "r" (bit)); }) -static inline unsigned int irq_getie(void) -{ - return (csrr(mstatus) & CSR_MSTATUS_MIE) != 0; +static inline unsigned int irq_getie(void) { + return (csrr(mstatus) & CSR_MSTATUS_MIE) != 0; } -static inline void irq_setie(unsigned int ie) -{ - if(ie) csrs(mstatus,CSR_MSTATUS_MIE); else csrc(mstatus,CSR_MSTATUS_MIE); +static inline void irq_setie(unsigned int ie) { + if (ie) { + csrs(mstatus,CSR_MSTATUS_MIE); + } else { + csrc(mstatus,CSR_MSTATUS_MIE); + } } -static inline unsigned int irq_getmask(void) -{ - unsigned int mask; - asm volatile ("csrr %0, %1" : "=r"(mask) : "i"(CSR_IRQ_MASK)); - return mask; +static inline unsigned int irq_getmask(void) { + unsigned int mask; + asm volatile ("csrr %0, %1" : "=r" (mask) : "i" (CSR_IRQ_MASK)); + return mask; } -static inline void irq_setmask(unsigned int mask) -{ - asm volatile ("csrw %0, %1" :: "i"(CSR_IRQ_MASK), "r"(mask)); +static inline void irq_setmask(unsigned int mask) { + asm volatile ("csrw %0, %1" : : "i" (CSR_IRQ_MASK), "r" (mask)); } -static inline unsigned int irq_pending(void) -{ - unsigned int pending; - asm volatile ("csrr %0, %1" : "=r"(pending) : "i"(CSR_IRQ_PENDING)); - return pending; +static inline unsigned int irq_pending(void) { + unsigned int pending; + asm volatile ("csrr %0, %1" : "=r" (pending) : "i" (CSR_IRQ_PENDING)); + return pending; } #ifdef __cplusplus diff --git a/ports/litex/mpconfigport.h b/ports/litex/mpconfigport.h index 5f739e49ea..cedc3badc3 100644 --- a/ports/litex/mpconfigport.h +++ b/ports/litex/mpconfigport.h @@ -35,7 +35,7 @@ #include "py/circuitpy_mpconfig.h" #define MICROPY_PORT_ROOT_POINTERS \ - CIRCUITPY_COMMON_ROOT_POINTERS + CIRCUITPY_COMMON_ROOT_POINTERS #define MICROPY_NLR_SETJMP (1) #define CIRCUITPY_DEFAULT_STACK_SIZE 0x6000 diff --git a/ports/litex/mphalport.c b/ports/litex/mphalport.c index c7369dc050..5eedc73f3c 100644 --- a/ports/litex/mphalport.c +++ b/ports/litex/mphalport.c @@ -60,12 +60,14 @@ void isr(void) { // Increase the "nesting count". Note: This should be going from 0 -> 1. nesting_count += 1; -#ifdef CFG_TUSB_MCU - if (irqs & (1 << USB_INTERRUPT)) + #ifdef CFG_TUSB_MCU + if (irqs & (1 << USB_INTERRUPT)) { usb_irq_handler(); -#endif - if (irqs & (1 << TIMER0_INTERRUPT)) + } + #endif + if (irqs & (1 << TIMER0_INTERRUPT)) { SysTick_Handler(); + } // Decrease the "nesting count". Note: This should be going from 1 -> 0. nesting_count -= 1; @@ -73,6 +75,6 @@ void isr(void) { mp_uint_t cpu_get_regs_and_sp(mp_uint_t *regs) { unsigned long __tmp; - asm volatile ("mv %0, x2" :"=r"(__tmp)); + asm volatile ("mv %0, x2" : "=r" (__tmp)); return __tmp; } diff --git a/ports/litex/mphalport.h b/ports/litex/mphalport.h index 540575c587..62c8e0bab3 100644 --- a/ports/litex/mphalport.h +++ b/ports/litex/mphalport.h @@ -34,8 +34,8 @@ #include "py/mpconfig.h" #include "supervisor/shared/tick.h" -#define mp_hal_ticks_ms() ((mp_uint_t) supervisor_ticks_ms32()) -//#define mp_hal_delay_us(us) NRFX_DELAY_US((uint32_t) (us)) +#define mp_hal_ticks_ms() ((mp_uint_t)supervisor_ticks_ms32()) +// #define mp_hal_delay_us(us) NRFX_DELAY_US((uint32_t) (us)) bool mp_hal_stdin_any(void); diff --git a/ports/litex/supervisor/internal_flash.c b/ports/litex/supervisor/internal_flash.c index 9b1dea6852..989fffcc47 100644 --- a/ports/litex/supervisor/internal_flash.c +++ b/ports/litex/supervisor/internal_flash.c @@ -53,9 +53,9 @@ enum pin { #define NO_CACHE 0xffffffff -static uint8_t _flash_cache[FLASH_PAGE_SIZE] __attribute__((aligned(4))); +static uint8_t _flash_cache[FLASH_PAGE_SIZE] __attribute__((aligned(4))); static uint32_t _flash_page_addr = NO_CACHE; -static bool _flash_cache_dirty; +static bool _flash_cache_dirty; // ------------------------------------------------------------------------- // When performing SPI operations, the flash cannot be accessed. Since we // normally execute directly from SPI, this can cause problems. @@ -65,14 +65,12 @@ static bool _flash_cache_dirty; // Therefore, we must re-implement these functions here and explicitly mark // them as being in `.ramtext`, even though they really ought to be inlined. __attribute__((section(".ramtext"))) -static inline void spi_writel(uint32_t value, uint32_t addr) -{ +static inline void spi_writel(uint32_t value, uint32_t addr) { *((volatile uint32_t *)addr) = value; } __attribute__((section(".ramtext"))) -static inline uint32_t spi_readl(uint32_t addr) -{ +static inline uint32_t spi_readl(uint32_t addr) { return *(volatile uint32_t *)addr; } @@ -92,9 +90,12 @@ static inline void bb_spi_en(unsigned int en) { } __attribute__((section(".ramtext"))) -static inline void bb_spi_irq_setie(unsigned int ie) -{ - if(ie) csrs(mstatus,CSR_MSTATUS_MIE); else csrc(mstatus,CSR_MSTATUS_MIE); +static inline void bb_spi_irq_setie(unsigned int ie) { + if (ie) { + csrs(mstatus,CSR_MSTATUS_MIE); + } else { + csrc(mstatus,CSR_MSTATUS_MIE); + } } __attribute__((section(".ramtext"))) @@ -162,14 +163,14 @@ static int bb_spi_beginWrite(uint32_t addr, const void *v_data, unsigned int cou const uint8_t *data = v_data; unsigned int i; -#ifdef NDEBUG + #ifdef NDEBUG if (v_data < (const void *)_flash_cache) { - asm("ebreak"); + asm ("ebreak"); } - if ((v_data+count) > (const void *)&_flash_cache[4096]) { - asm("ebreak"); + if ((v_data + count) > (const void *)&_flash_cache[4096]) { + asm ("ebreak"); } -#endif + #endif // Enable Write-Enable Latch (WEL) bb_spi_begin(); @@ -181,8 +182,9 @@ static int bb_spi_beginWrite(uint32_t addr, const void *v_data, unsigned int cou spi_single_tx(addr >> 16); spi_single_tx(addr >> 8); spi_single_tx(addr >> 0); - for (i = 0; (i < count) && (i < 256); i++) + for (i = 0; (i < count) && (i < 256); i++) { spi_single_tx(*data++); + } bb_spi_end(); return 0; @@ -215,41 +217,46 @@ static void bb_spi_write_page(uint32_t flash_address, const uint8_t *data) { // Ensure we're within the target flash address range. if ((flash_address - FLASH_PARTITION_OFFSET_BYTES) > FLASH_SIZE) { - asm("ebreak"); + asm ("ebreak"); return; } if (flash_address < FLASH_PARTITION_OFFSET_BYTES) { - asm("ebreak"); + asm ("ebreak"); return; } if ((flash_address_end - FLASH_PARTITION_OFFSET_BYTES) > FLASH_SIZE) { - asm("ebreak"); + asm ("ebreak"); return; } if (flash_address_end < FLASH_PARTITION_OFFSET_BYTES) { - asm("ebreak"); + asm ("ebreak"); return; } // Ensure we're not erasing the middle of a flash bank if ((flash_address & 0xfff) != 0) { - asm("ebreak"); + asm ("ebreak"); return; } page_write_log[page_write_log_offset++] = flash_address; - if (page_write_log_offset > sizeof(page_write_log)/sizeof(*page_write_log)) page_write_log_offset=0; + if (page_write_log_offset > sizeof(page_write_log) / sizeof(*page_write_log)) { + page_write_log_offset = 0; + } - while (bb_spi_is_busy()) + while (bb_spi_is_busy()) { ; // relax + } bb_spi_beginErase4(flash_address); - while (bb_spi_is_busy()) + while (bb_spi_is_busy()) { ; // relax + } while (flash_address < flash_address_end) { bb_spi_beginWrite(flash_address, data, 256); - while (bb_spi_is_busy()) + while (bb_spi_is_busy()) { ; // relax + } flash_address += 256; data += 256; } @@ -267,16 +274,18 @@ uint32_t supervisor_flash_get_block_size(void) { } uint32_t supervisor_flash_get_block_count(void) { - return FLASH_SIZE/FILESYSTEM_BLOCK_SIZE; + return FLASH_SIZE / FILESYSTEM_BLOCK_SIZE; } __attribute__((section(".ramtext"))) void port_internal_flash_flush(void) { // Skip if data is the same, or if there is no data in the cache - if (_flash_page_addr == NO_CACHE) + if (_flash_page_addr == NO_CACHE) { return; - if (!_flash_cache_dirty) + } + if (!_flash_cache_dirty) { return; + } // Disable interrupts and enable bit-bang mode on the SPI flash. // This function is running from RAM -- otherwise enabling bitbang mode @@ -291,7 +300,7 @@ void port_internal_flash_flush(void) { bb_spi_en(0); bb_spi_irq_setie(1); - _flash_cache_dirty = false; + _flash_cache_dirty = false; } mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t num_blocks) { @@ -299,7 +308,7 @@ mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t n supervisor_flash_flush(); uint32_t src = lba2addr(block); - memcpy(dest, (uint8_t*) src, FILESYSTEM_BLOCK_SIZE*num_blocks); + memcpy(dest, (uint8_t *)src, FILESYSTEM_BLOCK_SIZE * num_blocks); #if USB_AVAILABLE usb_background(); @@ -310,7 +319,7 @@ mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t n mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32_t num_blocks) { while (num_blocks) { - uint32_t const addr = lba2addr(lba); + uint32_t const addr = lba2addr(lba); uint32_t const page_addr = addr & ~(FLASH_PAGE_SIZE - 1); uint32_t count = 8 - (lba % 8); // up to page boundary @@ -334,8 +343,8 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 } // adjust for next run - lba += count; - src += count * FILESYSTEM_BLOCK_SIZE; + lba += count; + src += count * FILESYSTEM_BLOCK_SIZE; num_blocks -= count; #if USB_AVAILABLE diff --git a/ports/litex/supervisor/port.c b/ports/litex/supervisor/port.c index 04ff1c09bf..6f108ee051 100644 --- a/ports/litex/supervisor/port.c +++ b/ports/litex/supervisor/port.c @@ -87,7 +87,7 @@ void reset_port(void) { void reset_to_bootloader(void) { reboot_ctrl_write(0xac); - for(;;) {} + for (;;) {} } void reset_cpu(void) { @@ -97,7 +97,7 @@ void reset_cpu(void) { // simply writing this value" -- // https://workshop.fomu.im/en/latest/riscv.html reboot_ctrl_write(0xac); - for(;;) {} + for (;;) {} } bool port_has_fixed_stack(void) { @@ -129,7 +129,7 @@ uint32_t port_get_saved_word(void) { return _ebss; } -uint64_t port_get_raw_ticks(uint8_t* subticks) { +uint64_t port_get_raw_ticks(uint8_t *subticks) { // Reading 64 bits may take two loads, so turn of interrupts while we do it. common_hal_mcu_disable_interrupts(); uint64_t raw_tick_snapshot = raw_ticks; diff --git a/ports/mimxrt10xx/background.c b/ports/mimxrt10xx/background.c index a8a613d41a..9e531cea23 100644 --- a/ports/mimxrt10xx/background.c +++ b/ports/mimxrt10xx/background.c @@ -32,5 +32,7 @@ void port_background_task(void) { audio_dma_background(); #endif } -void port_start_background_task(void) {} -void port_finish_background_task(void) {} +void port_start_background_task(void) { +} +void port_finish_background_task(void) { +} diff --git a/ports/mimxrt10xx/boards/feather_m7_1011/board.c b/ports/mimxrt10xx/boards/feather_m7_1011/board.c index 1db1dd6861..5e20e5e3c2 100644 --- a/ports/mimxrt10xx/boards/feather_m7_1011/board.c +++ b/ports/mimxrt10xx/boards/feather_m7_1011/board.c @@ -32,8 +32,8 @@ void board_init(void) { // SWD Pins - common_hal_never_reset_pin(&pin_GPIO_AD_13);//SWDIO - common_hal_never_reset_pin(&pin_GPIO_AD_12);//SWCLK + common_hal_never_reset_pin(&pin_GPIO_AD_13);// SWDIO + common_hal_never_reset_pin(&pin_GPIO_AD_12);// SWCLK // FLEX flash common_hal_never_reset_pin(&pin_GPIO_SD_12); diff --git a/ports/mimxrt10xx/boards/feather_m7_1011/flash_config.c b/ports/mimxrt10xx/boards/feather_m7_1011/flash_config.c index 9ba3e168f5..5871dda963 100644 --- a/ports/mimxrt10xx/boards/feather_m7_1011/flash_config.c +++ b/ports/mimxrt10xx/boards/feather_m7_1011/flash_config.c @@ -14,14 +14,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -29,141 +29,141 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for W25Q32JV with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x02, // Bit pattern for setting Quad Enable. - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_133MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - // READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x02), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - EMPTY_SEQUENCE, - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status -2 - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x01 /* number of bytes to write */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x02, // Bit pattern for setting Quad Enable. + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_133MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + // READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x02), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + EMPTY_SEQUENCE, + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status -2 + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x01 /* number of bytes to write */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/boards/feather_mimxrt1011/board.c b/ports/mimxrt10xx/boards/feather_mimxrt1011/board.c index 1db1dd6861..5e20e5e3c2 100644 --- a/ports/mimxrt10xx/boards/feather_mimxrt1011/board.c +++ b/ports/mimxrt10xx/boards/feather_mimxrt1011/board.c @@ -32,8 +32,8 @@ void board_init(void) { // SWD Pins - common_hal_never_reset_pin(&pin_GPIO_AD_13);//SWDIO - common_hal_never_reset_pin(&pin_GPIO_AD_12);//SWCLK + common_hal_never_reset_pin(&pin_GPIO_AD_13);// SWDIO + common_hal_never_reset_pin(&pin_GPIO_AD_12);// SWCLK // FLEX flash common_hal_never_reset_pin(&pin_GPIO_SD_12); diff --git a/ports/mimxrt10xx/boards/feather_mimxrt1011/flash_config.c b/ports/mimxrt10xx/boards/feather_mimxrt1011/flash_config.c index eafc9ac3af..7460615c4c 100644 --- a/ports/mimxrt10xx/boards/feather_mimxrt1011/flash_config.c +++ b/ports/mimxrt10xx/boards/feather_mimxrt1011/flash_config.c @@ -14,14 +14,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -29,141 +29,141 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for W25Q64JV with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x02, - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_133MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - // READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - EMPTY_SEQUENCE, - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x02, + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_133MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + // READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + EMPTY_SEQUENCE, + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/boards/feather_mimxrt1011/pins.c b/ports/mimxrt10xx/boards/feather_mimxrt1011/pins.c index 4e5de8de27..b752b8ed30 100644 --- a/ports/mimxrt10xx/boards/feather_mimxrt1011/pins.c +++ b/ports/mimxrt10xx/boards/feather_mimxrt1011/pins.c @@ -41,7 +41,7 @@ STATIC const mp_rom_map_elem_t board_global_dict_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_ESP_RESET), MP_ROM_PTR(&pin_GPIO_AD_00) }, { MP_OBJ_NEW_QSTR(MP_QSTR_ESP_TX), MP_ROM_PTR(&pin_GPIO_12) }, { MP_OBJ_NEW_QSTR(MP_QSTR_ESP_RX), MP_ROM_PTR(&pin_GPIO_11) }, - //{ MP_OBJ_NEW_QSTR(MP_QSTR_ESP_RTS), MP_ROM_PTR(&pin_) }, + // { MP_OBJ_NEW_QSTR(MP_QSTR_ESP_RTS), MP_ROM_PTR(&pin_) }, { MP_OBJ_NEW_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO_SD_05) }, diff --git a/ports/mimxrt10xx/boards/feather_mimxrt1062/board.c b/ports/mimxrt10xx/boards/feather_mimxrt1062/board.c index 26f55f96e1..3782d3f2d2 100644 --- a/ports/mimxrt10xx/boards/feather_mimxrt1062/board.c +++ b/ports/mimxrt10xx/boards/feather_mimxrt1062/board.c @@ -32,8 +32,8 @@ void board_init(void) { // SWD Pins - common_hal_never_reset_pin(&pin_GPIO_AD_B0_06);//SWDIO - common_hal_never_reset_pin(&pin_GPIO_AD_B0_07);//SWCLK + common_hal_never_reset_pin(&pin_GPIO_AD_B0_06);// SWDIO + common_hal_never_reset_pin(&pin_GPIO_AD_B0_07);// SWCLK // FLEX flash common_hal_never_reset_pin(&pin_GPIO_SD_B1_06); diff --git a/ports/mimxrt10xx/boards/feather_mimxrt1062/flash_config.c b/ports/mimxrt10xx/boards/feather_mimxrt1062/flash_config.c index fef1c11e3e..d6cfc07e62 100644 --- a/ports/mimxrt10xx/boards/feather_mimxrt1062/flash_config.c +++ b/ports/mimxrt10xx/boards/feather_mimxrt1062/flash_config.c @@ -15,14 +15,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -30,141 +30,141 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for W25Q64JV with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x02, - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_133MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - // READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - EMPTY_SEQUENCE, - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x02, + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_133MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + // READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + EMPTY_SEQUENCE, + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/boards/feather_mimxrt1062/mpconfigboard.h b/ports/mimxrt10xx/boards/feather_mimxrt1062/mpconfigboard.h index 4c3953187e..7b335d896c 100644 --- a/ports/mimxrt10xx/boards/feather_mimxrt1062/mpconfigboard.h +++ b/ports/mimxrt10xx/boards/feather_mimxrt1062/mpconfigboard.h @@ -1,10 +1,10 @@ #define MICROPY_HW_BOARD_NAME "Feather MIMXRT1062" #define MICROPY_HW_MCU_NAME "IMXRT1062DVJ6A" -//TODO -//#define MICROPY_HW_LED_STATUS (&pin_PA27) +// TODO +// #define MICROPY_HW_LED_STATUS (&pin_PA27) -//#define MICROPY_HW_NEOPIXEL (&pin_PB22) +// #define MICROPY_HW_NEOPIXEL (&pin_PB22) // If you change this, then make sure to update the linker scripts as well to // make sure you don't overwrite code diff --git a/ports/mimxrt10xx/boards/imxrt1010_evk/board.c b/ports/mimxrt10xx/boards/imxrt1010_evk/board.c index 8519893a5f..9f7a22a86f 100644 --- a/ports/mimxrt10xx/boards/imxrt1010_evk/board.c +++ b/ports/mimxrt10xx/boards/imxrt1010_evk/board.c @@ -32,8 +32,8 @@ void board_init(void) { // SWD Pins - common_hal_never_reset_pin(&pin_GPIO_AD_13); //SWDIO - common_hal_never_reset_pin(&pin_GPIO_AD_12); //SWCLK + common_hal_never_reset_pin(&pin_GPIO_AD_13); // SWDIO + common_hal_never_reset_pin(&pin_GPIO_AD_12); // SWCLK // FLEX flash common_hal_never_reset_pin(&pin_GPIO_SD_12); common_hal_never_reset_pin(&pin_GPIO_SD_11); diff --git a/ports/mimxrt10xx/boards/imxrt1010_evk/flash_config.c b/ports/mimxrt10xx/boards/imxrt1010_evk/flash_config.c index 00ee47c985..9c88f689d8 100644 --- a/ports/mimxrt10xx/boards/imxrt1010_evk/flash_config.c +++ b/ports/mimxrt10xx/boards/imxrt1010_evk/flash_config.c @@ -15,14 +15,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -30,141 +30,141 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for AT25SF128A with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x02, - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_60MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - // READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x02), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - EMPTY_SEQUENCE, - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x02, + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_60MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + // READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x02), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + EMPTY_SEQUENCE, + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/boards/imxrt1020_evk/board.c b/ports/mimxrt10xx/boards/imxrt1020_evk/board.c index 531c0c6f62..4ae1e19b0d 100644 --- a/ports/mimxrt10xx/boards/imxrt1020_evk/board.c +++ b/ports/mimxrt10xx/boards/imxrt1020_evk/board.c @@ -32,8 +32,8 @@ void board_init(void) { // SWD Pins - common_hal_never_reset_pin(&pin_GPIO_AD_B0_00);//SWDIO - common_hal_never_reset_pin(&pin_GPIO_AD_B0_01);//SWCLK + common_hal_never_reset_pin(&pin_GPIO_AD_B0_00);// SWDIO + common_hal_never_reset_pin(&pin_GPIO_AD_B0_01);// SWCLK // FLEX flash common_hal_never_reset_pin(&pin_GPIO_SD_B1_06); diff --git a/ports/mimxrt10xx/boards/imxrt1020_evk/flash_config.c b/ports/mimxrt10xx/boards/imxrt1020_evk/flash_config.c index 4c3ba47179..6589ad9c48 100644 --- a/ports/mimxrt10xx/boards/imxrt1020_evk/flash_config.c +++ b/ports/mimxrt10xx/boards/imxrt1020_evk/flash_config.c @@ -15,14 +15,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -30,141 +30,141 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for IS25LP064A with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x40, - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_30MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - // SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - // RADDR_SDR, FLEXSPI_4PAD, 24 bits to transmit ), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - // READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - EMPTY_SEQUENCE, - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x01 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x40, + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_30MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + // SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + // RADDR_SDR, FLEXSPI_4PAD, 24 bits to transmit ), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + // READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + EMPTY_SEQUENCE, + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x01 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/boards/imxrt1060_evk/board.c b/ports/mimxrt10xx/boards/imxrt1060_evk/board.c index e7d74ab49f..c4a2867ab1 100644 --- a/ports/mimxrt10xx/boards/imxrt1060_evk/board.c +++ b/ports/mimxrt10xx/boards/imxrt1060_evk/board.c @@ -32,8 +32,8 @@ void board_init(void) { // SWD Pins - common_hal_never_reset_pin(&pin_GPIO_AD_B0_06);//SWDIO - common_hal_never_reset_pin(&pin_GPIO_AD_B0_07);//SWCLK + common_hal_never_reset_pin(&pin_GPIO_AD_B0_06);// SWDIO + common_hal_never_reset_pin(&pin_GPIO_AD_B0_07);// SWCLK // FLEX flash common_hal_never_reset_pin(&pin_GPIO_SD_B1_00); diff --git a/ports/mimxrt10xx/boards/imxrt1060_evk/flash_config.c b/ports/mimxrt10xx/boards/imxrt1060_evk/flash_config.c index 502e21a3b0..40db33444f 100644 --- a/ports/mimxrt10xx/boards/imxrt1060_evk/flash_config.c +++ b/ports/mimxrt10xx/boards/imxrt1060_evk/flash_config.c @@ -15,14 +15,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -30,141 +30,141 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for IS25WP064A with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x40, - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_60MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - // READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x02), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - EMPTY_SEQUENCE, - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x01 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x40, + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_60MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + // READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x02), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + EMPTY_SEQUENCE, + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x01 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/boards/metro_m7_1011/board.c b/ports/mimxrt10xx/boards/metro_m7_1011/board.c index 1db1dd6861..5e20e5e3c2 100644 --- a/ports/mimxrt10xx/boards/metro_m7_1011/board.c +++ b/ports/mimxrt10xx/boards/metro_m7_1011/board.c @@ -32,8 +32,8 @@ void board_init(void) { // SWD Pins - common_hal_never_reset_pin(&pin_GPIO_AD_13);//SWDIO - common_hal_never_reset_pin(&pin_GPIO_AD_12);//SWCLK + common_hal_never_reset_pin(&pin_GPIO_AD_13);// SWDIO + common_hal_never_reset_pin(&pin_GPIO_AD_12);// SWCLK // FLEX flash common_hal_never_reset_pin(&pin_GPIO_SD_12); diff --git a/ports/mimxrt10xx/boards/metro_m7_1011/flash_config.c b/ports/mimxrt10xx/boards/metro_m7_1011/flash_config.c index 991bc43e45..3f4ab0271d 100644 --- a/ports/mimxrt10xx/boards/metro_m7_1011/flash_config.c +++ b/ports/mimxrt10xx/boards/metro_m7_1011/flash_config.c @@ -15,14 +15,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -30,151 +30,151 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for W25Q16JV with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x0200, - .configCmdEnable = 1u, - .configModeType[0] = kDeviceConfigCmdType_Generic, - .configCmdSeqs[0] = { - .seqId = 2u, - .seqNum = 1u, - }, - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_60MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - // READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x02), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x35 /* the command to send */, - DUMMY_SDR, FLEXSPI_1PAD, 8), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x01 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x02), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x0200, + .configCmdEnable = 1u, + .configModeType[0] = kDeviceConfigCmdType_Generic, + .configCmdSeqs[0] = { + .seqId = 2u, + .seqNum = 1u, + }, + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_60MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + // READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x02), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x35 /* the command to send */, + DUMMY_SDR, FLEXSPI_1PAD, 8), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x01 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x02), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/boards/teensy40/flash_config.c b/ports/mimxrt10xx/boards/teensy40/flash_config.c index 991bc43e45..3f4ab0271d 100644 --- a/ports/mimxrt10xx/boards/teensy40/flash_config.c +++ b/ports/mimxrt10xx/boards/teensy40/flash_config.c @@ -15,14 +15,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -30,151 +30,151 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for W25Q16JV with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x0200, - .configCmdEnable = 1u, - .configModeType[0] = kDeviceConfigCmdType_Generic, - .configCmdSeqs[0] = { - .seqId = 2u, - .seqNum = 1u, - }, - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_60MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - // READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x02), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x35 /* the command to send */, - DUMMY_SDR, FLEXSPI_1PAD, 8), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x01 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x02), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x0200, + .configCmdEnable = 1u, + .configModeType[0] = kDeviceConfigCmdType_Generic, + .configCmdSeqs[0] = { + .seqId = 2u, + .seqNum = 1u, + }, + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_60MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + // READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x02), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x35 /* the command to send */, + DUMMY_SDR, FLEXSPI_1PAD, 8), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x01 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x02), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/boards/teensy41/flash_config.c b/ports/mimxrt10xx/boards/teensy41/flash_config.c index c0e0c86f98..09886dece6 100644 --- a/ports/mimxrt10xx/boards/teensy41/flash_config.c +++ b/ports/mimxrt10xx/boards/teensy41/flash_config.c @@ -15,14 +15,14 @@ __attribute__((section(".boot_hdr.ivt"))) * IVT Data *************************************/ const ivt image_vector_table = { - IVT_HEADER, /* IVT Header */ - IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ - IVT_RSVD, /* Reserved = 0 */ - (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ - (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ - (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ - (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ - IVT_RSVD /* Reserved = 0 */ + IVT_HEADER, /* IVT Header */ + IMAGE_ENTRY_ADDRESS, /* Image Entry Function */ + IVT_RSVD, /* Reserved = 0 */ + (uint32_t)DCD_ADDRESS, /* Address where DCD information is stored */ + (uint32_t)BOOT_DATA_ADDRESS, /* Address where BOOT Data Structure is stored */ + (uint32_t)&image_vector_table, /* Pointer to IVT Self (absolute address */ + (uint32_t)CSF_ADDRESS, /* Address where CSF file is stored */ + IVT_RSVD /* Reserved = 0 */ }; __attribute__((section(".boot_hdr.boot_data"))) @@ -30,141 +30,141 @@ __attribute__((section(".boot_hdr.boot_data"))) * Boot Data *************************************/ const BOOT_DATA_T boot_data = { - FLASH_BASE, /* boot start location */ - FLASH_SIZE, /* size */ - PLUGIN_FLAG, /* Plugin flag*/ - 0xFFFFFFFF /* empty - extra data word */ + FLASH_BASE, /* boot start location */ + FLASH_SIZE, /* size */ + PLUGIN_FLAG, /* Plugin flag*/ + 0xFFFFFFFF /* empty - extra data word */ }; // Config for W25Q64JV with QSPI routed. __attribute__((section(".boot_hdr.conf"))) const flexspi_nor_config_t qspiflash_config = { - .pageSize = 256u, - .sectorSize = 4u * 1024u, + .pageSize = 256u, + .sectorSize = 4u * 1024u, .ipcmdSerialClkFreq = kFlexSpiSerialClk_30MHz, - .blockSize = 0x00010000, + .blockSize = 0x00010000, .isUniformBlockSize = false, .memConfig = - { - .tag = FLEXSPI_CFG_BLK_TAG, - .version = FLEXSPI_CFG_BLK_VERSION, - .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, - .csHoldTime = 3u, - .csSetupTime = 3u, + { + .tag = FLEXSPI_CFG_BLK_TAG, + .version = FLEXSPI_CFG_BLK_VERSION, + .readSampleClkSrc = kFlexSPIReadSampleClk_LoopbackFromDqsPad, + .csHoldTime = 3u, + .csSetupTime = 3u, - .busyOffset = 0u, // Status bit 0 indicates busy. - .busyBitPolarity = 0u, // Busy when the bit is 1. + .busyOffset = 0u, // Status bit 0 indicates busy. + .busyBitPolarity = 0u, // Busy when the bit is 1. - .deviceModeCfgEnable = 1u, - .deviceModeType = kDeviceConfigCmdType_QuadEnable, - .deviceModeSeq = { - .seqId = 4u, - .seqNum = 1u, - }, - .deviceModeArg = 0x02, - .deviceType = kFlexSpiDeviceType_SerialNOR, - .sflashPadType = kSerialFlash_4Pads, - .serialClkFreq = kFlexSpiSerialClk_60MHz, - .sflashA1Size = FLASH_SIZE, - .lookupTable = - { - // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) - // The high 16 bits is command 1 and the low are command 0. - // Within a command, the top 6 bits are the opcode, the next two are the number - // of pads and then last byte is the operand. The operand's meaning changes - // per opcode. - - // Indices with ROM should always have the same function because the ROM - // bootloader uses it. - - // 0: ROM: Read LUTs - // Quad version - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, - RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), - FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, - READ_SDR, FLEXSPI_4PAD, 0x04), - // Single fast read version, good for debugging. - // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, - // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, - // READ_SDR, FLEXSPI_1PAD, 0x04), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 1: ROM: Read status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, - READ_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 2: Empty - EMPTY_SEQUENCE, - - // 3: ROM: Write Enable - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, - STOP, FLEXSPI_1PAD, 0x00), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 4: Config: Write Status - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, - WRITE_SDR, FLEXSPI_1PAD, 0x01), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 5: ROM: Erase Sector - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 6: Empty - EMPTY_SEQUENCE, - - // 7: Empty - EMPTY_SEQUENCE, - - // 8: Block Erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 9: ROM: Page program - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, - RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), - - FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 10: Empty - EMPTY_SEQUENCE, - - // 11: ROM: Chip erase - SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, - STOP, FLEXSPI_1PAD, 0), - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS, - TWO_EMPTY_STEPS), - - // 12: Empty - EMPTY_SEQUENCE, - - // 13: ROM: Read SFDP - EMPTY_SEQUENCE, - - // 14: ROM: Restore no cmd - EMPTY_SEQUENCE, - - // 15: ROM: Dummy - EMPTY_SEQUENCE - }, + .deviceModeCfgEnable = 1u, + .deviceModeType = kDeviceConfigCmdType_QuadEnable, + .deviceModeSeq = { + .seqId = 4u, + .seqNum = 1u, }, + .deviceModeArg = 0x02, + .deviceType = kFlexSpiDeviceType_SerialNOR, + .sflashPadType = kSerialFlash_4Pads, + .serialClkFreq = kFlexSpiSerialClk_60MHz, + .sflashA1Size = FLASH_SIZE, + .lookupTable = + { + // FLEXSPI_LUT_SEQ(cmd0, pad0, op0, cmd1, pad1, op1) + // The high 16 bits is command 1 and the low are command 0. + // Within a command, the top 6 bits are the opcode, the next two are the number + // of pads and then last byte is the operand. The operand's meaning changes + // per opcode. + + // Indices with ROM should always have the same function because the ROM + // bootloader uses it. + + // 0: ROM: Read LUTs + // Quad version + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xEB /* the command to send */, + RADDR_SDR, FLEXSPI_4PAD, 24 /* bits to transmit */), + FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_4PAD, 6 /* 6 dummy cycles, 2 for M7-0 and 4 dummy */, + READ_SDR, FLEXSPI_4PAD, 0x04), + // Single fast read version, good for debugging. + // FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x0B /* the command to send */, + // RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + // FLEXSPI_LUT_SEQ(DUMMY_SDR, FLEXSPI_1PAD, 8 /* 8 dummy clocks */, + // READ_SDR, FLEXSPI_1PAD, 0x04), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 1: ROM: Read status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x05 /* the command to send */, + READ_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 2: Empty + EMPTY_SEQUENCE, + + // 3: ROM: Write Enable + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x06 /* the command to send */, + STOP, FLEXSPI_1PAD, 0x00), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 4: Config: Write Status + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x31 /* the command to send */, + WRITE_SDR, FLEXSPI_1PAD, 0x01), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 5: ROM: Erase Sector + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x20 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 6: Empty + EMPTY_SEQUENCE, + + // 7: Empty + EMPTY_SEQUENCE, + + // 8: Block Erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0xD8 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 9: ROM: Page program + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x02 /* the command to send */, + RADDR_SDR, FLEXSPI_1PAD, 24 /* bits to transmit */), + + FLEXSPI_LUT_SEQ(WRITE_SDR, FLEXSPI_1PAD, 0x04 /* data out */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 10: Empty + EMPTY_SEQUENCE, + + // 11: ROM: Chip erase + SEQUENCE(FLEXSPI_LUT_SEQ(CMD_SDR, FLEXSPI_1PAD, 0x60 /* the command to send */, + STOP, FLEXSPI_1PAD, 0), + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS, + TWO_EMPTY_STEPS), + + // 12: Empty + EMPTY_SEQUENCE, + + // 13: ROM: Read SFDP + EMPTY_SEQUENCE, + + // 14: ROM: Restore no cmd + EMPTY_SEQUENCE, + + // 15: ROM: Dummy + EMPTY_SEQUENCE + }, + }, }; diff --git a/ports/mimxrt10xx/common-hal/analogio/AnalogIn.c b/ports/mimxrt10xx/common-hal/analogio/AnalogIn.c index 9587eba633..5e7bb82c77 100644 --- a/ports/mimxrt10xx/common-hal/analogio/AnalogIn.c +++ b/ports/mimxrt10xx/common-hal/analogio/AnalogIn.c @@ -36,8 +36,8 @@ #define ADC_CHANNEL_GROUP 0 -void common_hal_analogio_analogin_construct(analogio_analogin_obj_t* self, - const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, + const mcu_pin_obj_t *pin) { adc_config_t config = {0}; if (pin->adc == NULL) { diff --git a/ports/mimxrt10xx/common-hal/analogio/AnalogOut.c b/ports/mimxrt10xx/common-hal/analogio/AnalogOut.c index 6bdbeff7c2..bf21e30df3 100644 --- a/ports/mimxrt10xx/common-hal/analogio/AnalogOut.c +++ b/ports/mimxrt10xx/common-hal/analogio/AnalogOut.c @@ -31,7 +31,7 @@ #include "shared-bindings/microcontroller/Pin.h" #include "supervisor/shared/translate.h" -void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, const mcu_pin_obj_t *pin) { mp_raise_NotImplementedError(translate("AnalogOut functionality not supported")); } diff --git a/ports/mimxrt10xx/common-hal/busio/I2C.c b/ports/mimxrt10xx/common-hal/busio/I2C.c index c8daddc4bb..74639d0ef1 100644 --- a/ports/mimxrt10xx/common-hal/busio/I2C.c +++ b/ports/mimxrt10xx/common-hal/busio/I2C.c @@ -37,16 +37,16 @@ #include "fsl_lpi2c.h" #include "fsl_gpio.h" -#define I2C_CLOCK_FREQ (CLOCK_GetFreq(kCLOCK_Usb1PllClk) / 8 / (1+CLOCK_GetDiv(kCLOCK_Lpi2cDiv))) +#define I2C_CLOCK_FREQ (CLOCK_GetFreq(kCLOCK_Usb1PllClk) / 8 / (1 + CLOCK_GetDiv(kCLOCK_Lpi2cDiv))) #define IOMUXC_SW_MUX_CTL_PAD_MUX_MODE_ALT5 5U -//arrays use 0 based numbering: I2C1 is stored at index 0 +// arrays use 0 based numbering: I2C1 is stored at index 0 #define MAX_I2C 4 STATIC bool reserved_i2c[MAX_I2C]; STATIC bool never_reset_i2c[MAX_I2C]; void i2c_reset(void) { - for(uint i = 0; i < MP_ARRAY_SIZE(mcu_i2c_banks); i++) { + for (uint i = 0; i < MP_ARRAY_SIZE(mcu_i2c_banks); i++) { if (!never_reset_i2c[i]) { reserved_i2c[i] = false; LPI2C_MasterDeinit(mcu_i2c_banks[i]); @@ -64,30 +64,29 @@ static void config_periph_pin(const mcu_periph_obj_t *periph) { IOMUXC_SetPinConfig(0, 0, 0, 0, periph->pin->cfg_reg, IOMUXC_SW_PAD_CTL_PAD_HYS(0) - | IOMUXC_SW_PAD_CTL_PAD_PUS(3) - | IOMUXC_SW_PAD_CTL_PAD_PUE(0) - | IOMUXC_SW_PAD_CTL_PAD_PKE(1) - | IOMUXC_SW_PAD_CTL_PAD_ODE(1) - | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) - | IOMUXC_SW_PAD_CTL_PAD_DSE(4) - | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); + | IOMUXC_SW_PAD_CTL_PAD_PUS(3) + | IOMUXC_SW_PAD_CTL_PAD_PUE(0) + | IOMUXC_SW_PAD_CTL_PAD_PKE(1) + | IOMUXC_SW_PAD_CTL_PAD_ODE(1) + | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) + | IOMUXC_SW_PAD_CTL_PAD_DSE(4) + | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); } -static void i2c_check_pin_config(const mcu_pin_obj_t *pin, uint32_t pull) -{ +static void i2c_check_pin_config(const mcu_pin_obj_t *pin, uint32_t pull) { IOMUXC_SetPinConfig(0, 0, 0, 0, pin->cfg_reg, IOMUXC_SW_PAD_CTL_PAD_HYS(1) - | IOMUXC_SW_PAD_CTL_PAD_PUS(0) // Pulldown - | IOMUXC_SW_PAD_CTL_PAD_PUE(pull) // 0=nopull (keeper), 1=pull - | IOMUXC_SW_PAD_CTL_PAD_PKE(1) - | IOMUXC_SW_PAD_CTL_PAD_ODE(0) - | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) - | IOMUXC_SW_PAD_CTL_PAD_DSE(1) - | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); + | IOMUXC_SW_PAD_CTL_PAD_PUS(0) // Pulldown + | IOMUXC_SW_PAD_CTL_PAD_PUE(pull) // 0=nopull (keeper), 1=pull + | IOMUXC_SW_PAD_CTL_PAD_PKE(1) + | IOMUXC_SW_PAD_CTL_PAD_ODE(0) + | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) + | IOMUXC_SW_PAD_CTL_PAD_DSE(1) + | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); } void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, - const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint32_t frequency, uint32_t timeout) { + const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint32_t frequency, uint32_t timeout) { #if CIRCUITPY_REQUIRE_I2C_PULLUPS // Test that the pins are in a high state. (Hopefully indicating they are pulled up.) @@ -107,7 +106,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, // We must pull up within 3us to achieve 400khz. common_hal_mcu_delay_us(3); - if( !GPIO_PinRead(sda->gpio, sda->number) || !GPIO_PinRead(scl->gpio, scl->number)) { + if (!GPIO_PinRead(sda->gpio, sda->number) || !GPIO_PinRead(scl->gpio, scl->number)) { common_hal_reset_pin(sda); common_hal_reset_pin(scl); mp_raise_RuntimeError(translate("No pull up found on SDA or SCL; check your wiring")); @@ -118,15 +117,18 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, const uint32_t scl_count = MP_ARRAY_SIZE(mcu_i2c_scl_list); for (uint32_t i = 0; i < sda_count; ++i) { - if (mcu_i2c_sda_list[i].pin != sda) + if (mcu_i2c_sda_list[i].pin != sda) { continue; + } for (uint32_t j = 0; j < scl_count; ++j) { - if (mcu_i2c_scl_list[j].pin != scl) + if (mcu_i2c_scl_list[j].pin != scl) { continue; + } - if (mcu_i2c_scl_list[j].bank_idx != mcu_i2c_sda_list[i].bank_idx) + if (mcu_i2c_scl_list[j].bank_idx != mcu_i2c_sda_list[i].bank_idx) { continue; + } self->sda = &mcu_i2c_sda_list[i]; self->scl = &mcu_i2c_scl_list[j]; @@ -135,7 +137,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, } } - if(self->sda == NULL || self->scl == NULL) { + if (self->sda == NULL || self->scl == NULL) { mp_raise_ValueError(translate("Invalid pins")); } else { self->i2c = mcu_i2c_banks[self->sda->bank_idx - 1]; @@ -209,23 +211,24 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { } uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, - const uint8_t *data, size_t len, bool transmit_stop_bit) { + const uint8_t *data, size_t len, bool transmit_stop_bit) { lpi2c_master_transfer_t xfer = { 0 }; xfer.flags = transmit_stop_bit ? kLPI2C_TransferDefaultFlag : kLPI2C_TransferNoStopFlag; xfer.slaveAddress = addr; - xfer.data = (uint8_t*)data; + xfer.data = (uint8_t *)data; xfer.dataSize = len; const status_t status = LPI2C_MasterTransferBlocking(self->i2c, &xfer); - if (status == kStatus_Success) + if (status == kStatus_Success) { return 0; + } return MP_EIO; } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *data, size_t len) { + uint8_t *data, size_t len) { lpi2c_master_transfer_t xfer = { 0 }; xfer.direction = kLPI2C_Read; @@ -234,8 +237,9 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, xfer.dataSize = len; const status_t status = LPI2C_MasterTransferBlocking(self->i2c, &xfer); - if (status == kStatus_Success) + if (status == kStatus_Success) { return 0; + } return MP_EIO; } diff --git a/ports/mimxrt10xx/common-hal/busio/SPI.c b/ports/mimxrt10xx/common-hal/busio/SPI.c index 00d8d9867f..3488ac0fbe 100644 --- a/ports/mimxrt10xx/common-hal/busio/SPI.c +++ b/ports/mimxrt10xx/common-hal/busio/SPI.c @@ -40,7 +40,7 @@ #define MAX_SPI_BUSY_RETRIES 100 -//arrays use 0 based numbering: SPI1 is stored at index 0 +// arrays use 0 based numbering: SPI1 is stored at index 0 #define MAX_SPI 4 STATIC bool reserved_spi[MAX_SPI]; STATIC bool never_reset_spi[MAX_SPI]; @@ -55,13 +55,13 @@ STATIC void config_periph_pin(const mcu_periph_obj_t *periph) { IOMUXC_SetPinConfig(0, 0, 0, 0, periph->pin->cfg_reg, IOMUXC_SW_PAD_CTL_PAD_HYS(0) - | IOMUXC_SW_PAD_CTL_PAD_PUS(0) - | IOMUXC_SW_PAD_CTL_PAD_PUE(0) - | IOMUXC_SW_PAD_CTL_PAD_PKE(1) - | IOMUXC_SW_PAD_CTL_PAD_ODE(0) - | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) - | IOMUXC_SW_PAD_CTL_PAD_DSE(4) - | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); + | IOMUXC_SW_PAD_CTL_PAD_PUS(0) + | IOMUXC_SW_PAD_CTL_PAD_PUE(0) + | IOMUXC_SW_PAD_CTL_PAD_PKE(1) + | IOMUXC_SW_PAD_CTL_PAD_ODE(0) + | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) + | IOMUXC_SW_PAD_CTL_PAD_DSE(4) + | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); } void spi_reset(void) { @@ -74,8 +74,8 @@ void spi_reset(void) { } void common_hal_busio_spi_construct(busio_spi_obj_t *self, - const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, - const mcu_pin_obj_t *miso) { + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso) { const uint32_t sck_count = MP_ARRAY_SIZE(mcu_spi_sck_list); const uint32_t miso_count = MP_ARRAY_SIZE(mcu_spi_miso_list); @@ -86,15 +86,15 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, if (mcu_spi_sck_list[i].pin != clock) { continue; } - //if both MOSI and MISO exist, loop search normally + // if both MOSI and MISO exist, loop search normally if ((mosi != NULL) && (miso != NULL)) { for (uint j = 0; j < mosi_count; j++) { if ((mcu_spi_mosi_list[i].pin != mosi) - || (mcu_spi_sck_list[i].bank_idx != mcu_spi_mosi_list[j].bank_idx)){ + || (mcu_spi_sck_list[i].bank_idx != mcu_spi_mosi_list[j].bank_idx)) { continue; } for (uint k = 0; k < miso_count; k++) { - if ((mcu_spi_miso_list[k].pin != miso) //everything needs the same index + if ((mcu_spi_miso_list[k].pin != miso) // everything needs the same index || (mcu_spi_sck_list[i].bank_idx != mcu_spi_miso_list[k].bank_idx)) { continue; } @@ -103,7 +103,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, spi_taken = true; break; } - //store pins if not + // store pins if not self->clock = &mcu_spi_sck_list[i]; self->mosi = &mcu_spi_mosi_list[j]; self->miso = &mcu_spi_miso_list[k]; @@ -116,10 +116,10 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, if (self->clock != NULL || spi_taken) { break; } - // if just MISO, reduce search + // if just MISO, reduce search } else if (miso != NULL) { for (uint j = 0; j < miso_count; j++) { - if ((mcu_spi_miso_list[j].pin != miso) //only SCK and MISO need the same index + if ((mcu_spi_miso_list[j].pin != miso) // only SCK and MISO need the same index || (mcu_spi_sck_list[i].bank_idx != mcu_spi_miso_list[j].bank_idx)) { continue; } @@ -134,10 +134,10 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, if (self->clock != NULL || spi_taken) { break; } - // if just MOSI, reduce search + // if just MOSI, reduce search } else if (mosi != NULL) { for (uint j = 0; j < mosi_count; j++) { - if ((mcu_spi_mosi_list[j].pin != mosi) //only SCK and MOSI need the same index + if ((mcu_spi_mosi_list[j].pin != mosi) // only SCK and MOSI need the same index || (mcu_spi_sck_list[i].bank_idx != mcu_spi_mosi_list[j].bank_idx)) { continue; } @@ -153,7 +153,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, break; } } else { - //throw an error immediately + // throw an error immediately mp_raise_ValueError(translate("Must provide MISO or MOSI pin")); } } @@ -231,7 +231,7 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, - uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { + uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { LPSPI_Enable(self->spi, false); uint32_t tcrPrescaleValue; @@ -278,7 +278,7 @@ void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { } bool common_hal_busio_spi_write(busio_spi_obj_t *self, - const uint8_t *data, size_t len) { + const uint8_t *data, size_t len) { if (len == 0) { return true; } @@ -287,7 +287,7 @@ bool common_hal_busio_spi_write(busio_spi_obj_t *self, } lpspi_transfer_t xfer = { 0 }; - xfer.txData = (uint8_t*)data; + xfer.txData = (uint8_t *)data; xfer.dataSize = len; xfer.configFlags = kLPSPI_MasterPcs0; @@ -297,14 +297,15 @@ bool common_hal_busio_spi_write(busio_spi_obj_t *self, status = LPSPI_MasterTransferBlocking(self->spi, &xfer); } while (status == kStatus_LPSPI_Busy && --retries > 0); - if (status != kStatus_Success) + if (status != kStatus_Success) { printf("%s: status %ld\r\n", __func__, status); + } - return (status == kStatus_Success); + return status == kStatus_Success; } bool common_hal_busio_spi_read(busio_spi_obj_t *self, - uint8_t *data, size_t len, uint8_t write_value) { + uint8_t *data, size_t len, uint8_t write_value) { if (len == 0) { return true; } @@ -324,10 +325,11 @@ bool common_hal_busio_spi_read(busio_spi_obj_t *self, status = LPSPI_MasterTransferBlocking(self->spi, &xfer); } while (status == kStatus_LPSPI_Busy && --retries > 0); - if (status != kStatus_Success) + if (status != kStatus_Success) { printf("%s: status %ld\r\n", __func__, status); + } - return (status == kStatus_Success); + return status == kStatus_Success; } bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { @@ -351,20 +353,21 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou status = LPSPI_MasterTransferBlocking(self->spi, &xfer); } while (status == kStatus_LPSPI_Busy && --retries > 0); - if (status != kStatus_Success) + if (status != kStatus_Success) { printf("%s: status %ld\r\n", __func__, status); + } - return (status == kStatus_Success); + return status == kStatus_Success; } -uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self) { +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { return self->baudrate; } -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self) { - return ((self->spi->TCR & LPSPI_TCR_CPHA_MASK) == LPSPI_TCR_CPHA_MASK); +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { + return (self->spi->TCR & LPSPI_TCR_CPHA_MASK) == LPSPI_TCR_CPHA_MASK; } -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t* self) { - return ((self->spi->TCR & LPSPI_TCR_CPOL_MASK) == LPSPI_TCR_CPOL_MASK); +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { + return (self->spi->TCR & LPSPI_TCR_CPOL_MASK) == LPSPI_TCR_CPOL_MASK; } diff --git a/ports/mimxrt10xx/common-hal/busio/UART.c b/ports/mimxrt10xx/common-hal/busio/UART.c index 503da14c26..29f9ea0b27 100644 --- a/ports/mimxrt10xx/common-hal/busio/UART.c +++ b/ports/mimxrt10xx/common-hal/busio/UART.c @@ -40,7 +40,7 @@ #include "fsl_lpuart.h" -//arrays use 0 based numbering: UART1 is stored at index 0 +// arrays use 0 based numbering: UART1 is stored at index 0 #define MAX_UART 8 STATIC bool reserved_uart[MAX_UART]; @@ -56,18 +56,17 @@ static void config_periph_pin(const mcu_periph_obj_t *periph) { IOMUXC_SetPinConfig(0, 0, 0, 0, periph->pin->cfg_reg, IOMUXC_SW_PAD_CTL_PAD_HYS(0) - | IOMUXC_SW_PAD_CTL_PAD_PUS(1) - | IOMUXC_SW_PAD_CTL_PAD_PUE(1) - | IOMUXC_SW_PAD_CTL_PAD_PKE(1) - | IOMUXC_SW_PAD_CTL_PAD_ODE(0) - | IOMUXC_SW_PAD_CTL_PAD_SPEED(1) - | IOMUXC_SW_PAD_CTL_PAD_DSE(6) - | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); + | IOMUXC_SW_PAD_CTL_PAD_PUS(1) + | IOMUXC_SW_PAD_CTL_PAD_PUE(1) + | IOMUXC_SW_PAD_CTL_PAD_PKE(1) + | IOMUXC_SW_PAD_CTL_PAD_ODE(0) + | IOMUXC_SW_PAD_CTL_PAD_SPEED(1) + | IOMUXC_SW_PAD_CTL_PAD_DSE(6) + | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); } -void LPUART_UserCallback(LPUART_Type *base, lpuart_handle_t *handle, status_t status, void *user_data) -{ - busio_uart_obj_t *self = (busio_uart_obj_t*)user_data; +void LPUART_UserCallback(LPUART_Type *base, lpuart_handle_t *handle, status_t status, void *user_data) { + busio_uart_obj_t *self = (busio_uart_obj_t *)user_data; if (status == kStatus_LPUART_RxIdle) { self->rx_ongoing = false; @@ -75,19 +74,19 @@ void LPUART_UserCallback(LPUART_Type *base, lpuart_handle_t *handle, status_t st } void uart_reset(void) { - for(uint i = 0; i < MP_ARRAY_SIZE(mcu_uart_banks); i++) { + for (uint i = 0; i < MP_ARRAY_SIZE(mcu_uart_banks); i++) { reserved_uart[i] = false; LPUART_Deinit(mcu_uart_banks[i]); } } void common_hal_busio_uart_construct(busio_uart_obj_t *self, - const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, - const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, - const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, - mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, - bool sigint_enabled) { + const mcu_pin_obj_t *tx, const mcu_pin_obj_t *rx, + const mcu_pin_obj_t *rts, const mcu_pin_obj_t *cts, + const mcu_pin_obj_t *rs485_dir, bool rs485_invert, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, + mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, + bool sigint_enabled) { self->baudrate = baudrate; self->character_bits = bits; @@ -169,8 +168,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } // For IMXRT the RTS pin is used for RS485 direction rts = rs485_dir; - } - else { + } else { if (rs485_invert) { mp_raise_ValueError(translate("RS485 inversion specified when not in RS485 mode")); } @@ -181,7 +179,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, const uint32_t cts_count = MP_ARRAY_SIZE(mcu_uart_cts_list); if (rts != NULL) { - for (uint32_t i=0; i < rts_count; ++i) { + for (uint32_t i = 0; i < rts_count; ++i) { if (mcu_uart_rts_list[i].bank_idx == self->rx->bank_idx) { if (mcu_uart_rts_list[i].pin == rts) { self->rts = &mcu_uart_rts_list[i]; @@ -189,13 +187,13 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } } } - if (self->rts == NULL){ + if (self->rts == NULL) { mp_raise_ValueError(translate("Selected RTS pin not valid")); } } if (cts != NULL) { - for (uint32_t i=0; i < cts_count; ++i) { + for (uint32_t i = 0; i < cts_count; ++i) { if (mcu_uart_cts_list[i].bank_idx == self->rx->bank_idx) { if (mcu_uart_cts_list[i].pin == cts) { self->cts = &mcu_uart_cts_list[i]; @@ -203,7 +201,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } } } - if (self->cts == NULL){ + if (self->cts == NULL) { mp_raise_ValueError(translate("Selected CTS pin not valid")); } } @@ -326,7 +324,7 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t uint64_t start_ticks = supervisor_ticks_ms64(); // Wait for all bytes received or timeout - while (self->rx_ongoing && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms) ) { + while (self->rx_ongoing && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms)) { RUN_BACKGROUND_TASKS; // Allow user to break out of a timeout with a KeyboardInterrupt. @@ -372,7 +370,7 @@ void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrat } mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { - return (mp_float_t) (self->timeout_ms / 1000.0f); + return (mp_float_t)(self->timeout_ms / 1000.0f); } void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { diff --git a/ports/mimxrt10xx/common-hal/busio/UART.h b/ports/mimxrt10xx/common-hal/busio/UART.h index 94a5fb02c0..604fef2cf3 100644 --- a/ports/mimxrt10xx/common-hal/busio/UART.h +++ b/ports/mimxrt10xx/common-hal/busio/UART.h @@ -40,7 +40,7 @@ typedef struct { mp_obj_base_t base; LPUART_Type *uart; lpuart_handle_t handle; - uint8_t* ringbuf; + uint8_t *ringbuf; bool rx_ongoing; uint32_t baudrate; uint8_t character_bits; diff --git a/ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c b/ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c index e4eda9f4ff..445ffa91c5 100644 --- a/ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +++ b/ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c @@ -40,21 +40,20 @@ #define IOMUXC_SW_MUX_CTL_PAD_MUX_MODE_ALT5 5U -void pin_config(const mcu_pin_obj_t *pin, bool open_drain, digitalio_pull_t pull) -{ +void pin_config(const mcu_pin_obj_t *pin, bool open_drain, digitalio_pull_t pull) { IOMUXC_SetPinConfig(0, 0, 0, 0, pin->cfg_reg, IOMUXC_SW_PAD_CTL_PAD_HYS(1) - | IOMUXC_SW_PAD_CTL_PAD_PUS((pull == PULL_UP) ? 2 : 0) - | IOMUXC_SW_PAD_CTL_PAD_PUE(pull != PULL_NONE) - | IOMUXC_SW_PAD_CTL_PAD_PKE(1) - | IOMUXC_SW_PAD_CTL_PAD_ODE(open_drain) - | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) - | IOMUXC_SW_PAD_CTL_PAD_DSE(1) - | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); + | IOMUXC_SW_PAD_CTL_PAD_PUS((pull == PULL_UP) ? 2 : 0) + | IOMUXC_SW_PAD_CTL_PAD_PUE(pull != PULL_NONE) + | IOMUXC_SW_PAD_CTL_PAD_PKE(1) + | IOMUXC_SW_PAD_CTL_PAD_ODE(open_drain) + | IOMUXC_SW_PAD_CTL_PAD_SPEED(2) + | IOMUXC_SW_PAD_CTL_PAD_DSE(1) + | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); } digitalinout_result_t common_hal_digitalio_digitalinout_construct( - digitalio_digitalinout_obj_t* self, const mcu_pin_obj_t* pin) { + digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { claim_pin(pin); self->pin = pin; self->output = false; @@ -73,15 +72,15 @@ digitalinout_result_t common_hal_digitalio_digitalinout_construct( } void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { common_hal_never_reset_pin(self->pin); } -bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t* self) { +bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { return self->pin == NULL; } -void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t* self) { +void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self) { if (common_hal_digitalio_digitalinout_deinited(self)) { return; } @@ -90,7 +89,7 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t* self } void common_hal_digitalio_digitalinout_switch_to_input( - digitalio_digitalinout_obj_t* self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { self->output = false; // This also sets direction to input. @@ -98,8 +97,8 @@ void common_hal_digitalio_digitalinout_switch_to_input( } digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( - digitalio_digitalinout_obj_t* self, bool value, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, bool value, + digitalio_drive_mode_t drive_mode) { self->output = true; self->open_drain = drive_mode == DRIVE_MODE_OPEN_DRAIN; self->pull = PULL_NONE; @@ -112,23 +111,23 @@ digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( } digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( - digitalio_digitalinout_obj_t* self) { + digitalio_digitalinout_obj_t *self) { return self->output ? DIRECTION_OUTPUT : DIRECTION_INPUT; } void common_hal_digitalio_digitalinout_set_value( - digitalio_digitalinout_obj_t* self, bool value) { + digitalio_digitalinout_obj_t *self, bool value) { GPIO_PinWrite(self->pin->gpio, self->pin->number, value); } bool common_hal_digitalio_digitalinout_get_value( - digitalio_digitalinout_obj_t* self) { + digitalio_digitalinout_obj_t *self) { return GPIO_PinRead(self->pin->gpio, self->pin->number); } digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( - digitalio_digitalinout_obj_t* self, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, + digitalio_drive_mode_t drive_mode) { bool value = common_hal_digitalio_digitalinout_get_value(self); self->open_drain = drive_mode == DRIVE_MODE_OPEN_DRAIN; @@ -143,7 +142,7 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( } digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( - digitalio_digitalinout_obj_t* self) { + digitalio_digitalinout_obj_t *self) { if (self->open_drain) { return DRIVE_MODE_OPEN_DRAIN; } else { @@ -152,7 +151,7 @@ digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( } void common_hal_digitalio_digitalinout_set_pull( - digitalio_digitalinout_obj_t* self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { self->pull = pull; pin_config(self->pin, self->open_drain, self->pull); @@ -162,7 +161,7 @@ void common_hal_digitalio_digitalinout_set_pull( } digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( - digitalio_digitalinout_obj_t* self) { + digitalio_digitalinout_obj_t *self) { if (self->output) { mp_raise_AttributeError(translate("Cannot get pull while in output mode")); return PULL_NONE; diff --git a/ports/mimxrt10xx/common-hal/displayio/ParallelBus.c b/ports/mimxrt10xx/common-hal/displayio/ParallelBus.c index 0fdf4413b6..6a5a978cf4 100644 --- a/ports/mimxrt10xx/common-hal/displayio/ParallelBus.c +++ b/ports/mimxrt10xx/common-hal/displayio/ParallelBus.c @@ -33,19 +33,19 @@ #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/microcontroller/__init__.h" -void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* self, - const mcu_pin_obj_t* data0, const mcu_pin_obj_t* command, const mcu_pin_obj_t* chip_select, - const mcu_pin_obj_t* write, const mcu_pin_obj_t* read, const mcu_pin_obj_t* reset) { +void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t *self, + const mcu_pin_obj_t *data0, const mcu_pin_obj_t *command, const mcu_pin_obj_t *chip_select, + const mcu_pin_obj_t *write, const mcu_pin_obj_t *read, const mcu_pin_obj_t *reset) { mp_raise_NotImplementedError(translate("ParallelBus not yet supported")); } -void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) { +void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t *self) { } bool common_hal_displayio_parallelbus_reset(mp_obj_t obj) { - return false; + return false; } bool common_hal_displayio_parallelbus_bus_free(mp_obj_t obj) { diff --git a/ports/mimxrt10xx/common-hal/microcontroller/Pin.c b/ports/mimxrt10xx/common-hal/microcontroller/Pin.c index 50970f8e22..b55ab6e862 100644 --- a/ports/mimxrt10xx/common-hal/microcontroller/Pin.c +++ b/ports/mimxrt10xx/common-hal/microcontroller/Pin.c @@ -49,9 +49,9 @@ void reset_all_pins(void) { claimed_pins[i] = never_reset_pins[i]; } for (uint8_t i = 0; i < IOMUXC_SW_PAD_CTL_PAD_COUNT; i++) { - if(!never_reset_pins[i]) { - IOMUXC->SW_MUX_CTL_PAD[i] = ((mcu_pin_obj_t*)(mcu_pin_globals.map.table[i].value))->mux_reset; - IOMUXC->SW_PAD_CTL_PAD[i] = ((mcu_pin_obj_t*)(mcu_pin_globals.map.table[i].value))->pad_reset; + if (!never_reset_pins[i]) { + IOMUXC->SW_MUX_CTL_PAD[i] = ((mcu_pin_obj_t *)(mcu_pin_globals.map.table[i].value))->mux_reset; + IOMUXC->SW_PAD_CTL_PAD[i] = ((mcu_pin_obj_t *)(mcu_pin_globals.map.table[i].value))->pad_reset; } } @@ -66,14 +66,14 @@ void reset_all_pins(void) { // Since i.MX pins need extra register and reset information to reset properly, // resetting pins by number alone has been removed. -void common_hal_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_reset_pin(const mcu_pin_obj_t *pin) { if (pin == NULL) { return; } never_reset_pins[pin->mux_idx] = false; claimed_pins[pin->mux_idx] = false; - *(uint32_t*)pin->mux_reg = pin->mux_reset; - *(uint32_t*)pin->cfg_reg = pin->pad_reset; + *(uint32_t *)pin->mux_reg = pin->mux_reset; + *(uint32_t *)pin->cfg_reg = pin->pad_reset; #ifdef MICROPY_HW_NEOPIXEL if (pin == MICROPY_HW_NEOPIXEL) { @@ -95,11 +95,11 @@ void common_hal_reset_pin(const mcu_pin_obj_t* pin) { #endif } -void common_hal_never_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { never_reset_pins[pin->mux_idx] = true; } -bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t* pin) { +bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { #ifdef MICROPY_HW_NEOPIXEL if (pin == MICROPY_HW_NEOPIXEL) { return !neopixel_in_use; @@ -117,11 +117,11 @@ bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t* pin) { return !claimed_pins[pin->mux_idx]; } -uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t* pin) { +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin) { return pin->mux_idx; // returns IOMUXC to align with pin table } -void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) { +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { claimed_pins[pin->mux_idx] = true; #ifdef MICROPY_HW_NEOPIXEL @@ -139,10 +139,10 @@ void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) { #endif } -void claim_pin(const mcu_pin_obj_t* pin) { +void claim_pin(const mcu_pin_obj_t *pin) { common_hal_mcu_pin_claim(pin); } void common_hal_mcu_pin_reset_number(uint8_t pin_no) { - common_hal_reset_pin((mcu_pin_obj_t*)(mcu_pin_globals.map.table[pin_no].value)); + common_hal_reset_pin((mcu_pin_obj_t *)(mcu_pin_globals.map.table[pin_no].value)); } diff --git a/ports/mimxrt10xx/common-hal/microcontroller/Pin.h b/ports/mimxrt10xx/common-hal/microcontroller/Pin.h index 2f1aaa8955..fde7fc8b8f 100644 --- a/ports/mimxrt10xx/common-hal/microcontroller/Pin.h +++ b/ports/mimxrt10xx/common-hal/microcontroller/Pin.h @@ -41,6 +41,6 @@ extern bool apa102_mosi_in_use; #endif void reset_all_pins(void); -void claim_pin(const mcu_pin_obj_t* pin); +void claim_pin(const mcu_pin_obj_t *pin); #endif // MICROPY_INCLUDED_MIMXRT10XX_COMMON_HAL_MICROCONTROLLER_PIN_H diff --git a/ports/mimxrt10xx/common-hal/microcontroller/Processor.c b/ports/mimxrt10xx/common-hal/microcontroller/Processor.c index efbde35d28..b097133d57 100644 --- a/ports/mimxrt10xx/common-hal/microcontroller/Processor.c +++ b/ports/mimxrt10xx/common-hal/microcontroller/Processor.c @@ -65,7 +65,7 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { for (int i = 0; i < 4; ++i) { uint32_t wr = OCOTP_ReadFuseShadowRegister(OCOTP, i + 1); for (int j = 0; j < 4; j++) { - raw_id[i*4+j] = wr & 0xff; + raw_id[i * 4 + j] = wr & 0xff; wr >>= 8; } } diff --git a/ports/mimxrt10xx/common-hal/microcontroller/__init__.c b/ports/mimxrt10xx/common-hal/microcontroller/__init__.c index 6a8537e2da..2daf108af3 100644 --- a/ports/mimxrt10xx/common-hal/microcontroller/__init__.c +++ b/ports/mimxrt10xx/common-hal/microcontroller/__init__.c @@ -24,7 +24,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -//TODO +// TODO #include "py/mphal.h" #include "py/obj.h" #include "py/runtime.h" @@ -102,14 +102,14 @@ const nvm_bytearray_obj_t common_hal_mcu_nvm_obj = { .type = &nvm_bytearray_type, }, .len = CIRCUITPY_INTERNAL_NVM_SIZE, - .start_address = (uint8_t*) (FLASH_SIZE - CIRCUITPY_INTERNAL_NVM_SIZE) + .start_address = (uint8_t *)(FLASH_SIZE - CIRCUITPY_INTERNAL_NVM_SIZE) }; #endif // This maps MCU pin names to pin objects. // NOTE: for all i.MX chips, order MUST match _iomuxc_sw_mux_ctl_pad enum STATIC const mp_rom_map_elem_t mcu_pin_global_dict_table[] = { -#ifdef MIMXRT1011_SERIES + #ifdef MIMXRT1011_SERIES { MP_ROM_QSTR(MP_QSTR_GPIO_AD_14), MP_ROM_PTR(&pin_GPIO_AD_14) }, { MP_ROM_QSTR(MP_QSTR_GPIO_AD_13), MP_ROM_PTR(&pin_GPIO_AD_13) }, { MP_ROM_QSTR(MP_QSTR_GPIO_AD_12), MP_ROM_PTR(&pin_GPIO_AD_12) }, @@ -125,7 +125,7 @@ STATIC const mp_rom_map_elem_t mcu_pin_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_GPIO_AD_02), MP_ROM_PTR(&pin_GPIO_AD_02) }, { MP_ROM_QSTR(MP_QSTR_GPIO_AD_01), MP_ROM_PTR(&pin_GPIO_AD_01) }, { MP_ROM_QSTR(MP_QSTR_GPIO_AD_00), MP_ROM_PTR(&pin_GPIO_AD_00) }, - { MP_ROM_QSTR(MP_QSTR_GPIO_SD_14), MP_ROM_PTR(&pin_GPIO_SD_14) }, //spooky ghost pin + { MP_ROM_QSTR(MP_QSTR_GPIO_SD_14), MP_ROM_PTR(&pin_GPIO_SD_14) }, // spooky ghost pin { MP_ROM_QSTR(MP_QSTR_GPIO_SD_13), MP_ROM_PTR(&pin_GPIO_SD_13) }, { MP_ROM_QSTR(MP_QSTR_GPIO_SD_12), MP_ROM_PTR(&pin_GPIO_SD_12) }, { MP_ROM_QSTR(MP_QSTR_GPIO_SD_11), MP_ROM_PTR(&pin_GPIO_SD_11) }, @@ -154,7 +154,7 @@ STATIC const mp_rom_map_elem_t mcu_pin_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_GPIO_02), MP_ROM_PTR(&pin_GPIO_02) }, { MP_ROM_QSTR(MP_QSTR_GPIO_01), MP_ROM_PTR(&pin_GPIO_01) }, { MP_ROM_QSTR(MP_QSTR_GPIO_00), MP_ROM_PTR(&pin_GPIO_00) }, -#else + #else { MP_ROM_QSTR(MP_QSTR_GPIO_EMC_00), MP_ROM_PTR(&pin_GPIO_EMC_00) }, { MP_ROM_QSTR(MP_QSTR_GPIO_EMC_01), MP_ROM_PTR(&pin_GPIO_EMC_01) }, { MP_ROM_QSTR(MP_QSTR_GPIO_EMC_02), MP_ROM_PTR(&pin_GPIO_EMC_02) }, @@ -284,6 +284,6 @@ STATIC const mp_rom_map_elem_t mcu_pin_global_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_GPIO_SD_B1_09), MP_ROM_PTR(&pin_GPIO_SD_B1_09) }, { MP_ROM_QSTR(MP_QSTR_GPIO_SD_B1_10), MP_ROM_PTR(&pin_GPIO_SD_B1_10) }, { MP_ROM_QSTR(MP_QSTR_GPIO_SD_B1_11), MP_ROM_PTR(&pin_GPIO_SD_B1_11) }, -#endif + #endif }; MP_DEFINE_CONST_DICT(mcu_pin_globals, mcu_pin_global_dict_table); diff --git a/ports/mimxrt10xx/common-hal/neopixel_write/__init__.c b/ports/mimxrt10xx/common-hal/neopixel_write/__init__.c index b86077015c..88d0453065 100644 --- a/ports/mimxrt10xx/common-hal/neopixel_write/__init__.c +++ b/ports/mimxrt10xx/common-hal/neopixel_write/__init__.c @@ -33,7 +33,7 @@ uint64_t next_start_raw_ticks = 0; -//sysclock divisors +// sysclock divisors #define MAGIC_800_INT 900000 // ~1.11 us -> 1.2 field #define MAGIC_800_T0H 2800000 // ~0.36 us -> 0.44 field #define MAGIC_800_T1H 1350000 // ~0.74 us -> 0.84 field @@ -41,15 +41,15 @@ uint64_t next_start_raw_ticks = 0; #pragma GCC push_options #pragma GCC optimize ("Os") -void PLACE_IN_ITCM(common_hal_neopixel_write)(const digitalio_digitalinout_obj_t* digitalinout, uint8_t *pixels, - uint32_t numBytes) { +void PLACE_IN_ITCM(common_hal_neopixel_write)(const digitalio_digitalinout_obj_t * digitalinout, uint8_t *pixels, + uint32_t numBytes) { uint8_t *p = pixels, *end = p + numBytes, pix = *p++, mask = 0x80; uint32_t start = 0; uint32_t cyc = 0; - //assumes 800_000Hz frequency - //Theoretical values here are 800_000 -> 1.25us, 2500000->0.4us, 1250000->0.8us - //TODO: try to get dynamic weighting working again + // assumes 800_000Hz frequency + // Theoretical values here are 800_000 -> 1.25us, 2500000->0.4us, 1250000->0.8us + // TODO: try to get dynamic weighting working again const uint32_t sys_freq = SystemCoreClock; const uint32_t interval = (sys_freq / MAGIC_800_INT); const uint32_t t0 = (sys_freq / MAGIC_800_T0H); @@ -57,7 +57,8 @@ void PLACE_IN_ITCM(common_hal_neopixel_write)(const digitalio_digitalinout_obj_t // Wait to make sure we don't append onto the last transmission. This should only be a tick or // two. - while (port_get_raw_ticks(NULL) < next_start_raw_ticks) {} + while (port_get_raw_ticks(NULL) < next_start_raw_ticks) { + } GPIO_Type *gpio = digitalinout->pin->gpio; const uint32_t pin = digitalinout->pin->number; @@ -68,16 +69,22 @@ void PLACE_IN_ITCM(common_hal_neopixel_write)(const digitalio_digitalinout_obj_t DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; DWT->CYCCNT = 0; - for(;;) { + for (;;) { cyc = (pix & mask) ? t1 : t0; start = DWT->CYCCNT; gpio->DR |= (1U << pin); - while((DWT->CYCCNT - start) < cyc); + while ((DWT->CYCCNT - start) < cyc) { + ; + } gpio->DR &= ~(1U << pin); - while((DWT->CYCCNT - start) < interval); - if(!(mask >>= 1)) { - if(p >= end) break; - pix = *p++; + while ((DWT->CYCCNT - start) < interval) { + ; + } + if (!(mask >>= 1)) { + if (p >= end) { + break; + } + pix = *p++; mask = 0x80; } } diff --git a/ports/mimxrt10xx/common-hal/os/__init__.c b/ports/mimxrt10xx/common-hal/os/__init__.c index e84beb526c..dd1d186f1c 100644 --- a/ports/mimxrt10xx/common-hal/os/__init__.c +++ b/ports/mimxrt10xx/common-hal/os/__init__.c @@ -52,13 +52,13 @@ STATIC MP_DEFINE_ATTRTUPLE( (mp_obj_t)&os_uname_info_release_obj, (mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj -); + ); mp_obj_t common_hal_os_uname(void) { return (mp_obj_t)&os_uname_info_obj; } -bool common_hal_os_urandom(uint8_t* buffer, uint32_t length) { +bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { trng_config_t trngConfig; TRNG_GetDefaultConfig(&trngConfig); diff --git a/ports/mimxrt10xx/common-hal/pulseio/PulseIn.c b/ports/mimxrt10xx/common-hal/pulseio/PulseIn.c index cea11a4b9a..c1f7ce20b6 100644 --- a/ports/mimxrt10xx/common-hal/pulseio/PulseIn.c +++ b/ports/mimxrt10xx/common-hal/pulseio/PulseIn.c @@ -39,7 +39,7 @@ #include "supervisor/shared/translate.h" // TODO -//static void pulsein_set_config(pulseio_pulsein_obj_t* self, bool first_edge) { +// static void pulsein_set_config(pulseio_pulsein_obj_t* self, bool first_edge) { // uint32_t sense_setting; // if (!first_edge) { // sense_setting = EIC_CONFIG_SENSE0_BOTH_Val; @@ -52,9 +52,9 @@ // } // set_eic_handler(self->channel, EIC_HANDLER_PULSEIN); // turn_on_eic_channel(self->channel, sense_setting); -//} +// } -//void pulsein_interrupt_handler(uint8_t channel) { +// void pulsein_interrupt_handler(uint8_t channel) { // // Grab the current time first. // uint32_t current_us; // uint64_t current_ms; @@ -99,10 +99,10 @@ // } // self->last_ms = current_ms; // self->last_us = current_us; -//} +// } -void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, - const mcu_pin_obj_t* pin, uint16_t maxlen, bool idle_state) { +void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, + const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state) { // if (!pin->has_extint) { // mp_raise_RuntimeError(translate("No hardware support on pin")); // } @@ -142,12 +142,12 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, // pulsein_set_config(self, true); } -bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t* self) { +bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self) { // return self->pin == NO_PIN; return true; } -void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { // if (common_hal_pulseio_pulsein_deinited(self)) { // return; // } @@ -157,13 +157,13 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { // self->pin = NO_PIN; } -void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self) { // uint32_t mask = 1 << self->channel; // EIC->INTENCLR.reg = mask << EIC_INTENSET_EXTINT_Pos; } -void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, - uint16_t trigger_duration) { +void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t *self, + uint16_t trigger_duration) { // // Make sure we're paused. // common_hal_pulseio_pulsein_pause(self); // @@ -192,14 +192,14 @@ void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, // pulsein_set_config(self, true); } -void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t *self) { // common_hal_mcu_disable_interrupts(); // self->start = 0; // self->len = 0; // common_hal_mcu_enable_interrupts(); } -uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t *self) { // if (self->len == 0) { // mp_raise_IndexError_varg(translate("pop from empty %q"), MP_QSTR_PulseIn); // } @@ -213,24 +213,24 @@ uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { return 0; } -uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t *self) { // return self->maxlen; return 0; } -uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t *self) { // return self->len; return 0; } -bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t* self) { +bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t *self) { // uint32_t mask = 1 << self->channel; // return (EIC->INTENSET.reg & (mask << EIC_INTENSET_EXTINT_Pos)) == 0; return true; } -uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, - int16_t index) { +uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t *self, + int16_t index) { // common_hal_mcu_disable_interrupts(); // if (index < 0) { // index += self->len; diff --git a/ports/mimxrt10xx/common-hal/pulseio/PulseIn.h b/ports/mimxrt10xx/common-hal/pulseio/PulseIn.h index af742f319f..cce4f58ca7 100644 --- a/ports/mimxrt10xx/common-hal/pulseio/PulseIn.h +++ b/ports/mimxrt10xx/common-hal/pulseio/PulseIn.h @@ -48,8 +48,8 @@ typedef struct { // volatile bool errored_too_fast; } pulseio_pulsein_obj_t; -//void pulsein_reset(void); +// void pulsein_reset(void); // -//void pulsein_interrupt_handler(uint8_t channel); +// void pulsein_interrupt_handler(uint8_t channel); #endif // MICROPY_INCLUDED_MIMXRT10XX_COMMON_HAL_PULSEIO_PULSEIN_H diff --git a/ports/mimxrt10xx/common-hal/pulseio/PulseOut.c b/ports/mimxrt10xx/common-hal/pulseio/PulseOut.c index d3a1a897ff..b38f6f093f 100644 --- a/ports/mimxrt10xx/common-hal/pulseio/PulseOut.c +++ b/ports/mimxrt10xx/common-hal/pulseio/PulseOut.c @@ -39,25 +39,25 @@ // This timer is shared amongst all PulseOut objects under the assumption that // the code is single threaded. -//static uint8_t refcount = 0; +// static uint8_t refcount = 0; // -//static uint8_t pulseout_tc_index = 0xff; +// static uint8_t pulseout_tc_index = 0xff; // -//static __IO PORT_PINCFG_Type *active_pincfg = NULL; -//static uint16_t *pulse_buffer = NULL; -//static volatile uint16_t pulse_index = 0; -//static uint16_t pulse_length; -//static volatile uint32_t current_compare = 0; +// static __IO PORT_PINCFG_Type *active_pincfg = NULL; +// static uint16_t *pulse_buffer = NULL; +// static volatile uint16_t pulse_index = 0; +// static uint16_t pulse_length; +// static volatile uint32_t current_compare = 0; // -//static void turn_on(__IO PORT_PINCFG_Type * pincfg) { +// static void turn_on(__IO PORT_PINCFG_Type * pincfg) { // pincfg->reg = PORT_PINCFG_PMUXEN; -//} +// } // -//static void turn_off(__IO PORT_PINCFG_Type * pincfg) { +// static void turn_off(__IO PORT_PINCFG_Type * pincfg) { // pincfg->reg = PORT_PINCFG_RESETVALUE; -//} +// } // -//void pulse_finish(void) { +// void pulse_finish(void) { // pulse_index++; // // if (active_pincfg == NULL) { @@ -74,7 +74,7 @@ // if (pulse_index % 2 == 0) { // turn_on(active_pincfg); // } -//} +// } void pulseout_interrupt_handler(uint8_t index) { // if (index != pulseout_tc_index) return; @@ -93,11 +93,11 @@ void pulseout_reset() { // active_pincfg = NULL; } -void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, - const pwmio_pwmout_obj_t* carrier, - const mcu_pin_obj_t* pin, - uint32_t frequency, - uint16_t duty_cycle) { +void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, + const pwmio_pwmout_obj_t *carrier, + const mcu_pin_obj_t *pin, + uint32_t frequency, + uint16_t duty_cycle) { // if (refcount == 0) { // // Find a spare timer. // Tc *tc = NULL; @@ -155,12 +155,12 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, // turn_off(self->pincfg); } -bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t* self) { +bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t *self) { // return self->pin == NO_PIN; return false; } -void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { +void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { // if (common_hal_pulseio_pulseout_deinited(self)) { // return; // } @@ -177,7 +177,7 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { // self->pin = NO_PIN; } -void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pulses, uint16_t length) { +void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pulses, uint16_t length) { // if (active_pincfg != NULL) { // mp_raise_RuntimeError(translate("Another send is already active")); // } diff --git a/ports/mimxrt10xx/common-hal/pulseio/PulseOut.h b/ports/mimxrt10xx/common-hal/pulseio/PulseOut.h index ee70ac17ec..da022b738d 100644 --- a/ports/mimxrt10xx/common-hal/pulseio/PulseOut.h +++ b/ports/mimxrt10xx/common-hal/pulseio/PulseOut.h @@ -40,6 +40,6 @@ typedef struct { } pulseio_pulseout_obj_t; void pulseout_reset(void); -//void pulseout_interrupt_handler(uint8_t index); +// void pulseout_interrupt_handler(uint8_t index); #endif // MICROPY_INCLUDED_MIMXRT10XX_COMMON_HAL_PULSEIO_PULSEOUT_H diff --git a/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c b/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c index dd464ef846..28ea81fa22 100644 --- a/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +++ b/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -41,28 +41,28 @@ #include // TODO -//#include "samd/pins.h" +// #include "samd/pins.h" -//#undef ENABLE +// #undef ENABLE // -//# define _TCC_SIZE(unused, n) TCC ## n ## _SIZE, -//# define TCC_SIZES { REPEAT_MACRO(_TCC_SIZE, 0, TCC_INST_NUM) } +// # define _TCC_SIZE(unused, n) TCC ## n ## _SIZE, +// # define TCC_SIZES { REPEAT_MACRO(_TCC_SIZE, 0, TCC_INST_NUM) } // -//static uint32_t tcc_periods[TCC_INST_NUM]; -//static uint32_t tc_periods[TC_INST_NUM]; +// static uint32_t tcc_periods[TCC_INST_NUM]; +// static uint32_t tc_periods[TC_INST_NUM]; // -//uint32_t target_tcc_frequencies[TCC_INST_NUM]; -//uint8_t tcc_refcount[TCC_INST_NUM]; +// uint32_t target_tcc_frequencies[TCC_INST_NUM]; +// uint8_t tcc_refcount[TCC_INST_NUM]; // //// This bitmask keeps track of which channels of a TCC are currently claimed. -//#ifdef SAMD21 -//uint8_t tcc_channels[3]; // Set by pwmout_reset() to {0xf0, 0xfc, 0xfc} initially. -//#endif -//#ifdef SAMD51 -//uint8_t tcc_channels[5]; // Set by pwmout_reset() to {0xc0, 0xf0, 0xf8, 0xfc, 0xfc} initially. -//#endif +// #ifdef SAMD21 +// uint8_t tcc_channels[3]; // Set by pwmout_reset() to {0xf0, 0xfc, 0xfc} initially. +// #endif +// #ifdef SAMD51 +// uint8_t tcc_channels[5]; // Set by pwmout_reset() to {0xc0, 0xf0, 0xf8, 0xfc, 0xfc} initially. +// #endif // -//static uint8_t never_reset_tc_or_tcc[TC_INST_NUM + TCC_INST_NUM]; +// static uint8_t never_reset_tc_or_tcc[TC_INST_NUM + TCC_INST_NUM]; void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { // if (self->timer->is_tc) { @@ -119,33 +119,34 @@ void pwmout_reset(void) { // } } -//static uint8_t tcc_channel(const pin_timer_t* t) { +// static uint8_t tcc_channel(const pin_timer_t* t) { // // For the SAMD51 this hardcodes the use of OTMX == 0x0, the output matrix mapping, which uses // // SAMD21-style modulo mapping. // return t->wave_output % tcc_cc_num[t->index]; -//} +// } -//bool channel_ok(const pin_timer_t* t) { +// bool channel_ok(const pin_timer_t* t) { // uint8_t channel_bit = 1 << tcc_channel(t); // return (!t->is_tc && ((tcc_channels[t->index] & channel_bit) == 0)) || // t->is_tc; -//} +// } #define PWM_SRC_CLK_FREQ CLOCK_GetFreq(kCLOCK_IpgClk) pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, - const mcu_pin_obj_t *pin, - uint16_t duty, - uint32_t frequency, - bool variable_frequency) { + const mcu_pin_obj_t *pin, + uint16_t duty, + uint32_t frequency, + bool variable_frequency) { self->pin = pin; self->variable_frequency = variable_frequency; const uint32_t pwm_count = sizeof(mcu_pwm_list) / sizeof(mcu_pwm_obj_t); for (uint32_t i = 0; i < pwm_count; ++i) { - if (mcu_pwm_list[i].pin != pin) + if (mcu_pwm_list[i].pin != pin) { continue; + } printf("pwm: 0x%p, sum %d, chan %d, mux %d\r\n", mcu_pwm_list[i].pwm, mcu_pwm_list[i].submodule, mcu_pwm_list[i].channel, mcu_pwm_list[i].mux_mode); @@ -161,7 +162,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, CLOCK_SetDiv(kCLOCK_AhbDiv, 0x2); /* Set AHB PODF to 2, divide by 3 */ CLOCK_SetDiv(kCLOCK_IpgDiv, 0x3); /* Set IPG PODF to 3, divede by 4 */ -//TODO re-enable +// TODO re-enable // IOMUXC_SetPinMux( // IOMUXC_GPIO_SD_02_FLEXPWM1_PWM0_A, /* GPIO_02 is configured as FLEXPWM1_PWM0_A */ // 0U); /* Software Input On Field: Input Path is determined by functionality */ @@ -195,7 +196,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, */ PWM_GetDefaultConfig(&pwmConfig); - //pwmConfig.reloadLogic = kPWM_ReloadPwmFullCycle; + // pwmConfig.reloadLogic = kPWM_ReloadPwmFullCycle; pwmConfig.enableDebugMode = true; if (PWM_Init(PWM1, self->pwm->submodule, &pwmConfig) == kStatus_Fail) { @@ -208,10 +209,10 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, /* Set deadtime count, we set this to about 650ns */ uint16_t deadTimeVal = ((uint64_t)PWM_SRC_CLK_FREQ * 650) / 1000000000; - pwmSignal.pwmChannel = self->pwm->channel; - pwmSignal.level = kPWM_HighTrue; + pwmSignal.pwmChannel = self->pwm->channel; + pwmSignal.level = kPWM_HighTrue; pwmSignal.dutyCyclePercent = frequency / 2; /* 1 percent dutycycle */ - pwmSignal.deadtimeValue = deadTimeVal; + pwmSignal.deadtimeValue = deadTimeVal; PWM_SetupPwm(PWM1, self->pwm->submodule, &pwmSignal, 1, kPWM_SignedCenterAligned, frequency, PWM_SRC_CLK_FREQ); @@ -364,11 +365,11 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, return PWMOUT_OK; } -bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { return self->pin == NULL; } -void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { +void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { if (common_hal_pwmio_pwmout_deinited(self)) { return; } @@ -433,7 +434,7 @@ void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t d // } } -uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t* self) { +uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t *self) { return 0; // const pin_timer_t* t = self->timer; // if (t->is_tc) { @@ -471,8 +472,8 @@ uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t* self) { // } } -void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, - uint32_t frequency) { +void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, + uint32_t frequency) { // if (frequency == 0 || frequency > 6000000) { // mp_raise_ValueError(translate("Invalid PWM frequency")); // } @@ -530,7 +531,7 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, // common_hal_pwmio_pwmout_set_duty_cycle(self, old_duty); } -uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t* self) { +uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t *self) { // uint32_t system_clock = common_hal_mcu_processor_get_frequency(); // const pin_timer_t* t = self->timer; // uint8_t divisor; @@ -546,6 +547,6 @@ uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t* self) { return 0; } -bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *self) { return self->variable_frequency; } diff --git a/ports/mimxrt10xx/common-hal/rtc/RTC.c b/ports/mimxrt10xx/common-hal/rtc/RTC.c index 6940a1817d..aabe2b09f2 100644 --- a/ports/mimxrt10xx/common-hal/rtc/RTC.c +++ b/ports/mimxrt10xx/common-hal/rtc/RTC.c @@ -48,19 +48,19 @@ void common_hal_rtc_get_time(timeutils_struct_time_t *tm) { SNVS_HP_RTC_GetDatetime(SNVS, &rtcDate); tm->tm_year = rtcDate.year; - tm->tm_mon = rtcDate.month; + tm->tm_mon = rtcDate.month; tm->tm_mday = rtcDate.day; tm->tm_hour = rtcDate.hour; - tm->tm_min = rtcDate.minute; - tm->tm_sec = rtcDate.second; + tm->tm_min = rtcDate.minute; + tm->tm_sec = rtcDate.second; } void common_hal_rtc_set_time(timeutils_struct_time_t *tm) { snvs_hp_rtc_datetime_t rtcDate; - rtcDate.year = tm->tm_year; - rtcDate.month = tm->tm_mon; - rtcDate.day = tm->tm_mday; - rtcDate.hour = tm->tm_hour; + rtcDate.year = tm->tm_year; + rtcDate.month = tm->tm_mon; + rtcDate.day = tm->tm_mday; + rtcDate.hour = tm->tm_hour; rtcDate.minute = tm->tm_min; rtcDate.second = tm->tm_sec; diff --git a/ports/mimxrt10xx/common-hal/supervisor/Runtime.c b/ports/mimxrt10xx/common-hal/supervisor/Runtime.c old mode 100755 new mode 100644 index 974f26cec1..f827651781 --- a/ports/mimxrt10xx/common-hal/supervisor/Runtime.c +++ b/ports/mimxrt10xx/common-hal/supervisor/Runtime.c @@ -29,9 +29,9 @@ #include "supervisor/serial.h" bool common_hal_supervisor_runtime_get_serial_connected(void) { - return (bool) serial_connected(); + return (bool)serial_connected(); } bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); + return (bool)serial_bytes_available(); } diff --git a/ports/mimxrt10xx/fatfs_port.c b/ports/mimxrt10xx/fatfs_port.c index c65a73a428..e6eee20495 100644 --- a/ports/mimxrt10xx/fatfs_port.c +++ b/ports/mimxrt10xx/fatfs_port.c @@ -35,14 +35,14 @@ #endif DWORD get_fattime(void) { -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC timeutils_struct_time_t tm; common_hal_rtc_get_time(&tm); return ((tm.tm_year - 1980) << 25) | (tm.tm_mon << 21) | (tm.tm_mday << 16) | - (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1); -#else + (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1); + #else return ((2016 - 1980) << 25) | ((9) << 21) | ((1) << 16) | ((16) << 11) | ((43) << 5) | (35 / 2); -#endif + #endif } diff --git a/ports/mimxrt10xx/mpconfigport.h b/ports/mimxrt10xx/mpconfigport.h index 51e0ef9ff5..16cc63bc2d 100644 --- a/ports/mimxrt10xx/mpconfigport.h +++ b/ports/mimxrt10xx/mpconfigport.h @@ -38,14 +38,14 @@ extern uint8_t _ld_filesystem_end; extern uint8_t _ld_default_stack_size; // 20kiB stack -#define CIRCUITPY_DEFAULT_STACK_SIZE ((uint32_t) &_ld_default_stack_size) +#define CIRCUITPY_DEFAULT_STACK_SIZE ((uint32_t)&_ld_default_stack_size) #define MICROPY_PY_BUILTINS_NOTIMPLEMENTED (0) #define MICROPY_PY_FUNCTION_ATTRS (0) #define MICROPY_PY_REVERSE_SPECIAL_METHODS (1) -#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_START_ADDR ((uint32_t) &_ld_filesystem_start) -#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE ((uint32_t) (&_ld_filesystem_end - &_ld_filesystem_start)) +#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_START_ADDR ((uint32_t)&_ld_filesystem_start) +#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE ((uint32_t)(&_ld_filesystem_end - &_ld_filesystem_start)) #include "py/circuitpy_mpconfig.h" diff --git a/ports/mimxrt10xx/mphalport.c b/ports/mimxrt10xx/mphalport.c index 111e97011e..ff7a880ab7 100644 --- a/ports/mimxrt10xx/mphalport.c +++ b/ports/mimxrt10xx/mphalport.c @@ -34,11 +34,11 @@ #include "fsl_common.h" void mp_hal_delay_us(mp_uint_t delay) { -#if defined(MIMXRT1011_SERIES) || defined(MIMXRT1021_SERIES) + #if defined(MIMXRT1011_SERIES) || defined(MIMXRT1021_SERIES) SDK_DelayAtLeastUs(delay, SystemCoreClock); -#else + #else SDK_DelayAtLeastUs(delay); -#endif + #endif } void mp_hal_disable_all_interrupts(void) { diff --git a/ports/mimxrt10xx/mphalport.h b/ports/mimxrt10xx/mphalport.h index 4ba3a24764..a67e58e336 100644 --- a/ports/mimxrt10xx/mphalport.h +++ b/ports/mimxrt10xx/mphalport.h @@ -36,7 +36,7 @@ // Global millisecond tick count (driven by SysTick interrupt). static inline mp_uint_t mp_hal_ticks_ms(void) { - return supervisor_ticks_ms32(); + return supervisor_ticks_ms32(); } // Number of bytes in receive buffer extern volatile uint8_t usb_rx_count; diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/clocks.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/clocks.c index 61888fcaa7..e6354386a9 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/clocks.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/clocks.c @@ -74,17 +74,17 @@ const clock_sys_pll_config_t sysPllConfig_BOARD_BootClockRUN = { .loopDivider = 1, /* PLL loop divider, Fout = Fin * ( 20 + loopDivider*2 + numerator / denominator ) */ - .numerator = 0, /* 30 bit numerator of fractional loop divider */ + .numerator = 0, /* 30 bit numerator of fractional loop divider */ .denominator = 1, /* 30 bit denominator of fractional loop divider */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ }; const clock_usb_pll_config_t usb1PllConfig_BOARD_BootClockRUN = { .loopDivider = 0, /* PLL loop divider, Fout = Fin * 20 */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ }; const clock_enet_pll_config_t enetPllConfig_BOARD_BootClockRUN = { .enableClkOutput500M = true, /* Enable the PLL providing the ENET 500MHz reference clock */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ }; // Based on the hello_world example in the SDK @@ -111,8 +111,7 @@ void clocks_init(void) { /* Setting the VDD_SOC to 1.5V. It is necessary to config CORE to 500Mhz. */ DCDC->REG3 = (DCDC->REG3 & (~DCDC_REG3_TRG_MASK)) | DCDC_REG3_TRG(0x12); /* Waiting for DCDC_STS_DC_OK bit is asserted */ - while (DCDC_REG0_STS_DC_OK_MASK != (DCDC_REG0_STS_DC_OK_MASK & DCDC->REG0)) - { + while (DCDC_REG0_STS_DC_OK_MASK != (DCDC_REG0_STS_DC_OK_MASK & DCDC->REG0)) { } /* Set AHB_PODF. */ CLOCK_SetDiv(kCLOCK_AhbDiv, 0); diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/periph.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/periph.c index a994e154de..66dc56e4e0 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/periph.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/periph.c @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pins.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pins.c index cfab35cea8..492d1c6f08 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pins.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pins.c @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/clocks.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/clocks.c index cb9dd34c90..fb4d04b992 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/clocks.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/clocks.c @@ -87,20 +87,20 @@ const clock_sys_pll_config_t sysPllConfig_BOARD_BootClockRUN = { .loopDivider = 1, /* PLL loop divider, Fout = Fin * ( 20 + loopDivider*2 + numerator / denominator ) */ - .numerator = 0, /* 30 bit numerator of fractional loop divider */ + .numerator = 0, /* 30 bit numerator of fractional loop divider */ .denominator = 1, /* 30 bit denominator of fractional loop divider */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ }; const clock_usb_pll_config_t usb1PllConfig_BOARD_BootClockRUN = { .loopDivider = 0, /* PLL loop divider, Fout = Fin * 20 */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ }; const clock_enet_pll_config_t enetPllConfig_BOARD_BootClockRUN = { - .enableClkOutput = false, /* Disable the PLL providing the ENET 125MHz reference clock */ + .enableClkOutput = false, /* Disable the PLL providing the ENET 125MHz reference clock */ .enableClkOutput500M = true, /* Enable the PLL providing the ENET 500MHz reference clock */ - .enableClkOutput25M = false, /* Disable the PLL providing the ENET 25MHz reference clock */ - .loopDivider = 1, /* Set frequency of ethernet reference clock to 50 MHz */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ + .enableClkOutput25M = false, /* Disable the PLL providing the ENET 25MHz reference clock */ + .loopDivider = 1, /* Set frequency of ethernet reference clock to 50 MHz */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ }; // Based on the hello_world example in the SDK @@ -127,8 +127,7 @@ void clocks_init(void) { /* Setting the VDD_SOC to 1.5V. It is necessary to config AHB to 500Mhz. */ DCDC->REG3 = (DCDC->REG3 & (~DCDC_REG3_TRG_MASK)) | DCDC_REG3_TRG(0x12); /* Waiting for DCDC_STS_DC_OK bit is asserted */ - while (DCDC_REG0_STS_DC_OK_MASK != (DCDC_REG0_STS_DC_OK_MASK & DCDC->REG0)) - { + while (DCDC_REG0_STS_DC_OK_MASK != (DCDC_REG0_STS_DC_OK_MASK & DCDC->REG0)) { } /* Set AHB_PODF. */ CLOCK_SetDiv(kCLOCK_AhbDiv, 0); @@ -167,7 +166,7 @@ void clocks_init(void) { * With this macro SKIP_SYSCLK_INIT, system pll (selected to be SEMC source clock in SDK projects) will be left * unchanged. Note: If another clock source is selected for SEMC, user may want to avoid changing that clock as * well.*/ -#ifndef SKIP_SYSCLK_INIT + #ifndef SKIP_SYSCLK_INIT /* Disable Semc clock gate. */ CLOCK_DisableClock(kCLOCK_Semc); /* Set SEMC_PODF. */ @@ -176,7 +175,7 @@ void clocks_init(void) { CLOCK_SetMux(kCLOCK_SemcAltMux, 0); /* Set Semc clock source. */ CLOCK_SetMux(kCLOCK_SemcMux, 0); -#endif + #endif /* Disable LPSPI clock gate. */ CLOCK_DisableClock(kCLOCK_Lpspi1); CLOCK_DisableClock(kCLOCK_Lpspi2); @@ -268,10 +267,10 @@ void clocks_init(void) { * With this macro SKIP_SYSCLK_INIT, system pll (selected to be SEMC source clock in SDK projects) will be left * unchanged. Note: If another clock source is selected for SEMC, user may want to avoid changing that clock as * well.*/ -#ifndef SKIP_SYSCLK_INIT -#if defined(XIP_BOOT_HEADER_DCD_ENABLE) && (XIP_BOOT_HEADER_DCD_ENABLE == 1) + #ifndef SKIP_SYSCLK_INIT + #if defined(XIP_BOOT_HEADER_DCD_ENABLE) && (XIP_BOOT_HEADER_DCD_ENABLE == 1) #warning "SKIP_SYSCLK_INIT should be defined to keep system pll (selected to be SEMC source clock in SDK projects) unchanged." -#endif + #endif /* Init System PLL. */ CLOCK_InitSysPll(&sysPllConfig_BOARD_BootClockRUN); /* Init System pfd0. */ @@ -282,7 +281,7 @@ void clocks_init(void) { CLOCK_InitSysPfd(kCLOCK_Pfd2, 18); /* Init System pfd3. */ CLOCK_InitSysPfd(kCLOCK_Pfd3, 18); -#endif + #endif /* DeInit Audio PLL. */ CLOCK_DeinitAudioPll(); /* Bypass Audio PLL. */ diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/periph.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/periph.c index 3d043a14ec..754ef01c39 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/periph.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/periph.c @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pins.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pins.c index a25937cab7..fe39f7e19d 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pins.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pins.c @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/clocks.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/clocks.c index 7b9af3a6a5..1d67956f84 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/clocks.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/clocks.c @@ -40,22 +40,22 @@ #define BOARD_BOOTCLOCKRUN_CORE_CLOCK 600000000U /*!< Core clock frequency: 600000000Hz */ const clock_arm_pll_config_t armPllConfig_BOARD_BootClockRUN = - { - .loopDivider = 100, /* PLL loop divider, Fout = Fin * 50 */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ - }; +{ + .loopDivider = 100, /* PLL loop divider, Fout = Fin * 50 */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ +}; const clock_sys_pll_config_t sysPllConfig_BOARD_BootClockRUN = - { - .loopDivider = 1, /* PLL loop divider, Fout = Fin * ( 20 + loopDivider*2 + numerator / denominator ) */ - .numerator = 0, /* 30 bit numerator of fractional loop divider */ - .denominator = 1, /* 30 bit denominator of fractional loop divider */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ - }; +{ + .loopDivider = 1, /* PLL loop divider, Fout = Fin * ( 20 + loopDivider*2 + numerator / denominator ) */ + .numerator = 0, /* 30 bit numerator of fractional loop divider */ + .denominator = 1, /* 30 bit denominator of fractional loop divider */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ +}; const clock_usb_pll_config_t usb1PllConfig_BOARD_BootClockRUN = - { - .loopDivider = 0, /* PLL loop divider, Fout = Fin * 20 */ - .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ - }; +{ + .loopDivider = 0, /* PLL loop divider, Fout = Fin * 20 */ + .src = 0, /* Bypass clock source, 0 - OSC 24M, 1 - CLK1_P and CLK1_N */ +}; // Based on the hello_world example in the SDK void clocks_init(void) { @@ -81,8 +81,7 @@ void clocks_init(void) { /* Setting the VDD_SOC to 1.275V. It is necessary to config AHB to 600Mhz. */ DCDC->REG3 = (DCDC->REG3 & (~DCDC_REG3_TRG_MASK)) | DCDC_REG3_TRG(0x13); /* Waiting for DCDC_STS_DC_OK bit is asserted */ - while (DCDC_REG0_STS_DC_OK_MASK != (DCDC_REG0_STS_DC_OK_MASK & DCDC->REG0)) - { + while (DCDC_REG0_STS_DC_OK_MASK != (DCDC_REG0_STS_DC_OK_MASK & DCDC->REG0)) { } /* Set AHB_PODF. */ CLOCK_SetDiv(kCLOCK_AhbDiv, 0); @@ -120,7 +119,7 @@ void clocks_init(void) { /* In SDK projects, SDRAM (configured by SEMC) will be initialized in either debug script or dcd. * With this macro SKIP_SYSCLK_INIT, system pll (selected to be SEMC source clock in SDK projects) will be left unchanged. * Note: If another clock source is selected for SEMC, user may want to avoid changing that clock as well.*/ -#ifndef SKIP_SYSCLK_INIT + #ifndef SKIP_SYSCLK_INIT /* Disable Semc clock gate. */ CLOCK_DisableClock(kCLOCK_Semc); /* Set SEMC_PODF. */ @@ -129,7 +128,7 @@ void clocks_init(void) { CLOCK_SetMux(kCLOCK_SemcAltMux, 0); /* Set Semc clock source. */ CLOCK_SetMux(kCLOCK_SemcMux, 0); -#endif + #endif /* Disable LPSPI clock gate. */ CLOCK_DisableClock(kCLOCK_Lpspi1); CLOCK_DisableClock(kCLOCK_Lpspi2); @@ -232,7 +231,7 @@ void clocks_init(void) { /* In SDK projects, SDRAM (configured by SEMC) will be initialized in either debug script or dcd. * With this macro SKIP_SYSCLK_INIT, system pll (selected to be SEMC source clock in SDK projects) will be left unchanged. * Note: If another clock source is selected for SEMC, user may want to avoid changing that clock as well.*/ -#ifndef SKIP_SYSCLK_INIT + #ifndef SKIP_SYSCLK_INIT /* Init System PLL. */ CLOCK_InitSysPll(&sysPllConfig_BOARD_BootClockRUN); /* Init System pfd0. */ @@ -243,7 +242,7 @@ void clocks_init(void) { CLOCK_InitSysPfd(kCLOCK_Pfd2, 24); /* Init System pfd3. */ CLOCK_InitSysPfd(kCLOCK_Pfd3, 16); -#endif + #endif /* DeInit Audio PLL. */ CLOCK_DeinitAudioPll(); /* Bypass Audio PLL. */ @@ -320,11 +319,11 @@ void clocks_init(void) { /* Set ENET1 Tx clock source. */ IOMUXC_EnableMode(IOMUXC_GPR, kIOMUXC_GPR_ENET1RefClkMode, false); /* Set ENET2 Tx clock source. */ -#if defined(FSL_IOMUXC_DRIVER_VERSION) && (FSL_IOMUXC_DRIVER_VERSION != (MAKE_VERSION(2, 0, 0))) + #if defined(FSL_IOMUXC_DRIVER_VERSION) && (FSL_IOMUXC_DRIVER_VERSION != (MAKE_VERSION(2, 0, 0))) IOMUXC_EnableMode(IOMUXC_GPR, kIOMUXC_GPR_ENET2RefClkMode, false); -#else + #else IOMUXC_EnableMode(IOMUXC_GPR, IOMUXC_GPR_GPR1_ENET2_CLK_SEL_MASK, false); -#endif + #endif /* Set GPT1 High frequency reference clock source. */ IOMUXC_GPR->GPR5 &= ~IOMUXC_GPR_GPR5_VREF_1M_CLK_GPT1_MASK; /* Set GPT2 High frequency reference clock source. */ diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/periph.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/periph.c index fd1e4ddb85..e1c6968fcf 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/periph.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/periph.c @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pins.c b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pins.c index ce098ea2bc..0e440b6b63 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pins.c +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pins.c @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/periph.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/periph.h index 9b9713bb4d..ab0ebf0454 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/periph.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/periph.h @@ -31,38 +31,38 @@ #include "pins.h" typedef struct { - uint8_t bank_idx:4; - uint8_t mux_mode:4; + uint8_t bank_idx : 4; + uint8_t mux_mode : 4; uint32_t input_reg; uint8_t input_idx; const mcu_pin_obj_t *pin; } mcu_periph_obj_t; #define PERIPH_PIN(p_bank_idx, p_mux_mode, p_input_reg, p_input_idx, p_pin) \ -{ \ - .bank_idx = p_bank_idx, \ - .mux_mode = p_mux_mode, \ - .input_reg = p_input_reg == 0 ? 0 : (uint32_t)&(IOMUXC->SELECT_INPUT[p_input_reg]), \ - .input_idx = p_input_idx, \ - .pin = p_pin, \ -} + { \ + .bank_idx = p_bank_idx, \ + .mux_mode = p_mux_mode, \ + .input_reg = p_input_reg == 0 ? 0 : (uint32_t)&(IOMUXC->SELECT_INPUT[p_input_reg]), \ + .input_idx = p_input_idx, \ + .pin = p_pin, \ + } typedef struct { PWM_Type *pwm; - pwm_submodule_t submodule:4; - pwm_channels_t channel:4; + pwm_submodule_t submodule : 4; + pwm_channels_t channel : 4; uint8_t mux_mode; const mcu_pin_obj_t *pin; } mcu_pwm_obj_t; #define PWM_PIN(p_pwm, p_submodule, p_channel, p_mux_mode, p_pin) \ -{ \ - .pwm = p_pwm, \ - .submodule = p_submodule, \ - .channel = p_channel, \ - .mux_mode = p_mux_mode, \ - .pin = p_pin, \ -} + { \ + .pwm = p_pwm, \ + .submodule = p_submodule, \ + .channel = p_channel, \ + .mux_mode = p_mux_mode, \ + .pin = p_pin, \ + } extern LPI2C_Type *mcu_i2c_banks[]; extern LPSPI_Type *mcu_spi_banks[]; diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/pins.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/pins.h index 7168854a5e..d6d12771c5 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/pins.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/pins.h @@ -59,18 +59,18 @@ typedef struct { } mcu_pin_obj_t; #define PIN(p_gpio, p_number, p_enum, p_adc, p_adc_channel, p_mux_reset, p_pad_reset) \ -{ \ - { &mcu_pin_type }, \ - .gpio = p_gpio, \ - .number = p_number, \ - .mux_idx = kIOMUXC_SW_MUX_CTL_PAD_ ## p_enum, \ - .mux_reg = (uint32_t)&(IOMUXC->SW_MUX_CTL_PAD[kIOMUXC_SW_MUX_CTL_PAD_ ## p_enum]), \ - .cfg_reg = (uint32_t)&(IOMUXC->SW_PAD_CTL_PAD[kIOMUXC_SW_PAD_CTL_PAD_ ## p_enum]), \ - .adc = p_adc, \ - .adc_channel = p_adc_channel, \ - .mux_reset = p_mux_reset, \ - .pad_reset = p_pad_reset, \ -} + { \ + { &mcu_pin_type }, \ + .gpio = p_gpio, \ + .number = p_number, \ + .mux_idx = kIOMUXC_SW_MUX_CTL_PAD_##p_enum, \ + .mux_reg = (uint32_t)&(IOMUXC->SW_MUX_CTL_PAD[kIOMUXC_SW_MUX_CTL_PAD_##p_enum]), \ + .cfg_reg = (uint32_t)&(IOMUXC->SW_PAD_CTL_PAD[kIOMUXC_SW_PAD_CTL_PAD_##p_enum]), \ + .adc = p_adc, \ + .adc_channel = p_adc_channel, \ + .mux_reset = p_mux_reset, \ + .pad_reset = p_pad_reset, \ + } #ifdef MIMXRT1011_SERIES #include "MIMXRT1011/pins.h" diff --git a/ports/mimxrt10xx/supervisor/flexspi_nor_flash_ops.c b/ports/mimxrt10xx/supervisor/flexspi_nor_flash_ops.c index bd471f9305..251e6f9acd 100644 --- a/ports/mimxrt10xx/supervisor/flexspi_nor_flash_ops.c +++ b/ports/mimxrt10xx/supervisor/flexspi_nor_flash_ops.c @@ -12,24 +12,24 @@ #include "boards/flash_config.h" #include "supervisor/linker.h" -status_t PLACE_IN_ITCM(flexspi_nor_write_enable)(FLEXSPI_Type *base, uint32_t baseAddr) +status_t PLACE_IN_ITCM(flexspi_nor_write_enable)(FLEXSPI_Type * base, uint32_t baseAddr) { flexspi_transfer_t flashXfer; status_t status; /* Write enable */ flashXfer.deviceAddress = baseAddr; - flashXfer.port = kFLEXSPI_PortA1; - flashXfer.cmdType = kFLEXSPI_Command; - flashXfer.SeqNumber = 1; - flashXfer.seqIndex = ROM_INDEX_WRITEENABLE; + flashXfer.port = kFLEXSPI_PortA1; + flashXfer.cmdType = kFLEXSPI_Command; + flashXfer.SeqNumber = 1; + flashXfer.seqIndex = ROM_INDEX_WRITEENABLE; status = FLEXSPI_TransferBlocking(base, &flashXfer); return status; } -status_t PLACE_IN_ITCM(flexspi_nor_wait_bus_busy)(FLEXSPI_Type *base) +status_t PLACE_IN_ITCM(flexspi_nor_wait_bus_busy)(FLEXSPI_Type * base) { /* Wait status ready. */ bool isBusy; @@ -38,57 +38,54 @@ status_t PLACE_IN_ITCM(flexspi_nor_wait_bus_busy)(FLEXSPI_Type *base) flexspi_transfer_t flashXfer; flashXfer.deviceAddress = 0; - flashXfer.port = kFLEXSPI_PortA1; - flashXfer.cmdType = kFLEXSPI_Read; - flashXfer.SeqNumber = 1; - flashXfer.seqIndex = ROM_INDEX_READSTATUSREG; - flashXfer.data = &readValue; - flashXfer.dataSize = 1; + flashXfer.port = kFLEXSPI_PortA1; + flashXfer.cmdType = kFLEXSPI_Read; + flashXfer.SeqNumber = 1; + flashXfer.seqIndex = ROM_INDEX_READSTATUSREG; + flashXfer.data = &readValue; + flashXfer.dataSize = 1; do { status = FLEXSPI_TransferBlocking(base, &flashXfer); - if (status != kStatus_Success) - { + if (status != kStatus_Success) { return status; } size_t busyBit = readValue & (1U << qspiflash_config.memConfig.busyOffset); isBusy = (qspiflash_config.memConfig.busyBitPolarity == 0 && busyBit != 0) || - (qspiflash_config.memConfig.busyBitPolarity == 1 && busyBit == 0); + (qspiflash_config.memConfig.busyBitPolarity == 1 && busyBit == 0); } while (isBusy); return status; } -status_t PLACE_IN_ITCM(flexspi_nor_flash_erase_sector)(FLEXSPI_Type *base, uint32_t address) +status_t PLACE_IN_ITCM(flexspi_nor_flash_erase_sector)(FLEXSPI_Type * base, uint32_t address) { status_t status; flexspi_transfer_t flashXfer; /* Write enable */ flashXfer.deviceAddress = address; - flashXfer.port = kFLEXSPI_PortA1; - flashXfer.cmdType = kFLEXSPI_Command; - flashXfer.SeqNumber = 1; - flashXfer.seqIndex = ROM_INDEX_WRITEENABLE; + flashXfer.port = kFLEXSPI_PortA1; + flashXfer.cmdType = kFLEXSPI_Command; + flashXfer.SeqNumber = 1; + flashXfer.seqIndex = ROM_INDEX_WRITEENABLE; status = FLEXSPI_TransferBlocking(base, &flashXfer); - if (status != kStatus_Success) - { + if (status != kStatus_Success) { return status; } flashXfer.deviceAddress = address; - flashXfer.port = kFLEXSPI_PortA1; - flashXfer.cmdType = kFLEXSPI_Command; - flashXfer.SeqNumber = 1; - flashXfer.seqIndex = ROM_INDEX_ERASESECTOR; - status = FLEXSPI_TransferBlocking(base, &flashXfer); + flashXfer.port = kFLEXSPI_PortA1; + flashXfer.cmdType = kFLEXSPI_Command; + flashXfer.SeqNumber = 1; + flashXfer.seqIndex = ROM_INDEX_ERASESECTOR; + status = FLEXSPI_TransferBlocking(base, &flashXfer); - if (status != kStatus_Success) - { + if (status != kStatus_Success) { return status; } @@ -100,7 +97,7 @@ status_t PLACE_IN_ITCM(flexspi_nor_flash_erase_sector)(FLEXSPI_Type *base, uint3 return status; } -status_t PLACE_IN_ITCM(flexspi_nor_flash_page_program)(FLEXSPI_Type *base, uint32_t dstAddr, const uint32_t *src) +status_t PLACE_IN_ITCM(flexspi_nor_flash_page_program)(FLEXSPI_Type * base, uint32_t dstAddr, const uint32_t *src) { status_t status; flexspi_transfer_t flashXfer; @@ -108,35 +105,33 @@ status_t PLACE_IN_ITCM(flexspi_nor_flash_page_program)(FLEXSPI_Type *base, uint3 /* Write enable */ status = flexspi_nor_write_enable(base, dstAddr); - if (status != kStatus_Success) - { + if (status != kStatus_Success) { return status; } /* Prepare page program command */ flashXfer.deviceAddress = dstAddr; - flashXfer.port = kFLEXSPI_PortA1; - flashXfer.cmdType = kFLEXSPI_Write; - flashXfer.SeqNumber = 1; - flashXfer.seqIndex = ROM_INDEX_PAGEPROGRAM; - flashXfer.data = (uint32_t *)src; - flashXfer.dataSize = FLASH_PAGE_SIZE; - status = FLEXSPI_TransferBlocking(base, &flashXfer); + flashXfer.port = kFLEXSPI_PortA1; + flashXfer.cmdType = kFLEXSPI_Write; + flashXfer.SeqNumber = 1; + flashXfer.seqIndex = ROM_INDEX_PAGEPROGRAM; + flashXfer.data = (uint32_t *)src; + flashXfer.dataSize = FLASH_PAGE_SIZE; + status = FLEXSPI_TransferBlocking(base, &flashXfer); - if (status != kStatus_Success) - { + if (status != kStatus_Success) { return status; } status = flexspi_nor_wait_bus_busy(base); /* Do software reset. */ -#if defined(FSL_FEATURE_SOC_OTFAD_COUNT) + #if defined(FSL_FEATURE_SOC_OTFAD_COUNT) base->AHBCR |= FLEXSPI_AHBCR_CLRAHBRXBUF_MASK | FLEXSPI_AHBCR_CLRAHBTXBUF_MASK; base->AHBCR &= ~(FLEXSPI_AHBCR_CLRAHBRXBUF_MASK | FLEXSPI_AHBCR_CLRAHBTXBUF_MASK); -#else + #else FLEXSPI_SoftwareReset(base); -#endif + #endif return status; } diff --git a/ports/mimxrt10xx/supervisor/internal_flash.c b/ports/mimxrt10xx/supervisor/internal_flash.c index 9c0d9f8956..84c478bcfb 100644 --- a/ports/mimxrt10xx/supervisor/internal_flash.c +++ b/ports/mimxrt10xx/supervisor/internal_flash.c @@ -49,7 +49,7 @@ extern uint32_t __fatfs_flash_length[]; #define NO_CACHE 0xffffffff #define SECTOR_SIZE 0x1000 /* 4K */ -uint8_t _flash_cache[SECTOR_SIZE] __attribute__((aligned(4))); +uint8_t _flash_cache[SECTOR_SIZE] __attribute__((aligned(4))); uint32_t _flash_page_addr = NO_CACHE; extern status_t flexspi_nor_flash_erase_sector(FLEXSPI_Type *base, uint32_t address); @@ -58,7 +58,7 @@ extern status_t flexspi_nor_enable_quad_mode(FLEXSPI_Type *base); void PLACE_IN_ITCM(supervisor_flash_init)(void) { // Update the LUT to make sure all entries are available. - FLEXSPI_UpdateLUT(FLEXSPI, 0, (const uint32_t*) &qspiflash_config.memConfig.lookupTable, 64); + FLEXSPI_UpdateLUT(FLEXSPI, 0, (const uint32_t *)&qspiflash_config.memConfig.lookupTable, 64); } static inline uint32_t lba2addr(uint32_t block) { @@ -74,7 +74,9 @@ uint32_t supervisor_flash_get_block_count(void) { } void PLACE_IN_ITCM(port_internal_flash_flush)(void) { - if (_flash_page_addr == NO_CACHE) return; + if (_flash_page_addr == NO_CACHE) { + return; + } status_t status; // Skip if data is the same @@ -109,13 +111,13 @@ mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t n supervisor_flash_flush(); uint32_t src = lba2addr(block); - memcpy(dest, (uint8_t*)src, FILESYSTEM_BLOCK_SIZE * num_blocks); + memcpy(dest, (uint8_t *)src, FILESYSTEM_BLOCK_SIZE * num_blocks); return 0; // success } mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32_t num_blocks) { while (num_blocks) { - uint32_t const addr = lba2addr(lba); + uint32_t const addr = lba2addr(lba); uint32_t const page_addr = addr & ~(SECTOR_SIZE - 1); uint32_t count = 8 - (lba % 8); // up to page boundary @@ -135,8 +137,8 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 memcpy(_flash_cache + (addr & (SECTOR_SIZE - 1)), src, count * FILESYSTEM_BLOCK_SIZE); // adjust for next run - lba += count; - src += count * FILESYSTEM_BLOCK_SIZE; + lba += count; + src += count * FILESYSTEM_BLOCK_SIZE; num_blocks -= count; } diff --git a/ports/mimxrt10xx/supervisor/port.c b/ports/mimxrt10xx/supervisor/port.c index 33a85d2b72..2493252d78 100644 --- a/ports/mimxrt10xx/supervisor/port.c +++ b/ports/mimxrt10xx/supervisor/port.c @@ -110,8 +110,8 @@ extern void main(void); // This replaces the Reset_Handler in startup_*.S and SystemInit in system_*.c. __attribute__((used, naked)) void Reset_Handler(void) { __disable_irq(); - SCB->VTOR = (uint32_t) &__isr_vector; - __set_MSP((uint32_t) &_ld_stack_top); + SCB->VTOR = (uint32_t)&__isr_vector; + __set_MSP((uint32_t)&_ld_stack_top); /* Disable I cache and D cache */ SCB_DisableICache(); @@ -135,7 +135,7 @@ __attribute__((used, naked)) void Reset_Handler(void) { IOMUXC_GPR->GPR14 = current_gpr14; #if ((__FPU_PRESENT == 1) && (__FPU_USED == 1)) - SCB->CPACR |= ((3UL << 10*2) | (3UL << 11*2)); /* set CP10, CP11 Full Access */ + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10, CP11 Full Access */ #endif /* ((__FPU_PRESENT == 1) && (__FPU_USED == 1)) */ /* Disable Watchdog Power Down Counter */ @@ -147,11 +147,10 @@ __attribute__((used, naked)) void Reset_Handler(void) { WDOG2->WCR &= ~WDOG_WCR_WDE_MASK; RTWDOG->CNT = 0xD928C520U; /* 0xD928C520U is the update key */ RTWDOG->TOVAL = 0xFFFF; - RTWDOG->CS = (uint32_t) ((RTWDOG->CS) & ~RTWDOG_CS_EN_MASK) | RTWDOG_CS_UPDATE_MASK; + RTWDOG->CS = (uint32_t)((RTWDOG->CS) & ~RTWDOG_CS_EN_MASK) | RTWDOG_CS_UPDATE_MASK; /* Disable Systick which might be enabled by bootrom */ - if (SysTick->CTRL & SysTick_CTRL_ENABLE_Msk) - { + if (SysTick->CTRL & SysTick_CTRL_ENABLE_Msk) { SysTick->CTRL &= ~SysTick_CTRL_ENABLE_Msk; } @@ -160,7 +159,7 @@ __attribute__((used, naked)) void Reset_Handler(void) { // Copy all of the itcm code to run from ITCM. Do this while the MPU is disabled because we write // protect it. - for (uint32_t i = 0; i < ((size_t) &_ld_itcm_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_itcm_size) / 4; i++) { (&_ld_itcm_destination)[i] = (&_ld_itcm_flash_copy)[i]; } @@ -226,22 +225,22 @@ __attribute__((used, naked)) void Reset_Handler(void) { SCB_EnableICache(); // Copy all of the data to run from DTCM. - for (uint32_t i = 0; i < ((size_t) &_ld_dtcm_data_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_dtcm_data_size) / 4; i++) { (&_ld_dtcm_data_destination)[i] = (&_ld_dtcm_data_flash_copy)[i]; } // Clear DTCM bss. - for (uint32_t i = 0; i < ((size_t) &_ld_dtcm_bss_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_dtcm_bss_size) / 4; i++) { (&_ld_dtcm_bss_start)[i] = 0; } // Copy all of the data to run from OCRAM. - for (uint32_t i = 0; i < ((size_t) &_ld_ocram_data_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_ocram_data_size) / 4; i++) { (&_ld_ocram_data_destination)[i] = (&_ld_ocram_data_flash_copy)[i]; } // Clear OCRAM bss. - for (uint32_t i = 0; i < ((size_t) &_ld_ocram_bss_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_ocram_bss_size) / 4; i++) { (&_ld_ocram_bss_start)[i] = 0; } @@ -254,9 +253,9 @@ safe_mode_t port_init(void) { clocks_init(); -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC rtc_init(); -#endif + #endif // Always enable the SNVS interrupt. The GPC won't wake us up unless at least one interrupt is // enabled. It won't occur very often so it'll be low overhead. @@ -275,43 +274,43 @@ safe_mode_t port_init(void) { void reset_port(void) { spi_reset(); -#if CIRCUITPY_AUDIOIO + #if CIRCUITPY_AUDIOIO audio_dma_reset(); audioout_reset(); -#endif -#if CIRCUITPY_AUDIOBUSIO + #endif + #if CIRCUITPY_AUDIOBUSIO i2sout_reset(); - //pdmin_reset(); -#endif + // pdmin_reset(); + #endif -#if CIRCUITPY_TOUCHIO && CIRCUITPY_TOUCHIO_USE_NATIVE + #if CIRCUITPY_TOUCHIO && CIRCUITPY_TOUCHIO_USE_NATIVE touchin_reset(); -#endif + #endif // eic_reset(); -#if CIRCUITPY_PULSEIO + #if CIRCUITPY_PULSEIO pulseout_reset(); -#endif -#if CIRCUITPY_PWMIO + #endif + #if CIRCUITPY_PWMIO pwmout_reset(); -#endif + #endif -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC rtc_reset(); -#endif + #endif -#if CIRCUITPY_GAMEPAD + #if CIRCUITPY_GAMEPAD gamepad_reset(); -#endif -#if CIRCUITPY_GAMEPADSHIFT + #endif + #if CIRCUITPY_GAMEPADSHIFT gamepadshift_reset(); -#endif -#if CIRCUITPY_PEW + #endif + #if CIRCUITPY_PEW pew_reset(); -#endif + #endif - //reset_event_system(); + // reset_event_system(); reset_all_pins(); } @@ -356,12 +355,12 @@ uint32_t port_get_saved_word(void) { return SNVS->LPGPR[1]; } -uint64_t port_get_raw_ticks(uint8_t* subticks) { +uint64_t port_get_raw_ticks(uint8_t *subticks) { uint64_t ticks = 0; uint64_t next_ticks = 1; while (ticks != next_ticks) { ticks = next_ticks; - next_ticks = ((uint64_t) SNVS->HPRTCMR) << 32 | SNVS->HPRTCLR; + next_ticks = ((uint64_t)SNVS->HPRTCMR) << 32 | SNVS->HPRTCLR; } if (subticks != NULL) { *subticks = ticks % 32; @@ -397,7 +396,8 @@ void port_interrupt_after_ticks(uint32_t ticks) { current_ticks += ticks; SNVS->HPCR &= ~SNVS_HPCR_HPTA_EN_MASK; // Wait for the alarm to be disabled. - while ((SNVS->HPCR & SNVS_HPCR_HPTA_EN_MASK) != 0) {} + while ((SNVS->HPCR & SNVS_HPCR_HPTA_EN_MASK) != 0) { + } SNVS->HPTAMR = current_ticks >> (32 - 5); SNVS->HPTALR = current_ticks << 5 | subticks; SNVS->HPCR |= SNVS_HPCR_HPTA_EN_MASK; @@ -407,9 +407,9 @@ void port_idle_until_interrupt(void) { // App note here: https://www.nxp.com/docs/en/application-note/AN12085.pdf // Clear the FPU interrupt because it can prevent us from sleeping. - if (__get_FPSCR() & ~(0x9f)) { - __set_FPSCR(__get_FPSCR() & ~(0x9f)); - (void) __get_FPSCR(); + if (__get_FPSCR() & ~(0x9f)) { + __set_FPSCR(__get_FPSCR() & ~(0x9f)); + (void)__get_FPSCR(); } NVIC_ClearPendingIRQ(SNVS_HP_WRAPPER_IRQn); CLOCK_SetMode(kCLOCK_ModeWait); @@ -420,43 +420,39 @@ void port_idle_until_interrupt(void) { /** * \brief Default interrupt handler for unused IRQs. */ -__attribute__((used)) void MemManage_Handler(void) -{ +__attribute__((used)) void MemManage_Handler(void) { reset_into_safe_mode(MEM_MANAGE); while (true) { - asm("nop;"); + asm ("nop;"); } } /** * \brief Default interrupt handler for unused IRQs. */ -__attribute__((used)) void BusFault_Handler(void) -{ +__attribute__((used)) void BusFault_Handler(void) { reset_into_safe_mode(MEM_MANAGE); while (true) { - asm("nop;"); + asm ("nop;"); } } /** * \brief Default interrupt handler for unused IRQs. */ -__attribute__((used)) void UsageFault_Handler(void) -{ +__attribute__((used)) void UsageFault_Handler(void) { reset_into_safe_mode(MEM_MANAGE); while (true) { - asm("nop;"); + asm ("nop;"); } } /** * \brief Default interrupt handler for unused IRQs. */ -__attribute__((used)) void HardFault_Handler(void) -{ +__attribute__((used)) void HardFault_Handler(void) { reset_into_safe_mode(HARD_CRASH); while (true) { - asm("nop;"); + asm ("nop;"); } } diff --git a/ports/mimxrt10xx/supervisor/serial.c b/ports/mimxrt10xx/supervisor/serial.c index 01656a819c..ea706d8a8c 100644 --- a/ports/mimxrt10xx/supervisor/serial.c +++ b/ports/mimxrt10xx/supervisor/serial.c @@ -35,7 +35,7 @@ // static LPUART_Type *uart_instance = LPUART1; // evk static LPUART_Type *uart_instance = LPUART4; // feather 1011 -//static LPUART_Type *uart_instance = LPUART2; // feather 1062 +// static LPUART_Type *uart_instance = LPUART2; // feather 1062 static uint32_t UartSrcFreq(void) { uint32_t freq; @@ -79,8 +79,8 @@ bool serial_bytes_available(void) { return LPUART_GetStatusFlags(uart_instance) & kLPUART_RxDataRegFullFlag; } -void serial_write(const char* text) { - LPUART_WriteBlocking(uart_instance, (uint8_t*)text, strlen(text)); +void serial_write(const char *text) { + LPUART_WriteBlocking(uart_instance, (uint8_t *)text, strlen(text)); } void serial_write_substring(const char *text, uint32_t len) { @@ -88,5 +88,5 @@ void serial_write_substring(const char *text, uint32_t len) { return; } - LPUART_WriteBlocking(uart_instance, (uint8_t*)text, len); + LPUART_WriteBlocking(uart_instance, (uint8_t *)text, len); } diff --git a/ports/mimxrt10xx/supervisor/usb.c b/ports/mimxrt10xx/supervisor/usb.c index 91135289c8..57f0387990 100644 --- a/ports/mimxrt10xx/supervisor/usb.c +++ b/ports/mimxrt10xx/supervisor/usb.c @@ -33,11 +33,11 @@ void init_usb_hardware(void) { CLOCK_EnableUsbhs0PhyPllClock(kCLOCK_Usbphy480M, 480000000U); CLOCK_EnableUsbhs0Clock(kCLOCK_Usb480M, 480000000U); -#ifdef USBPHY + #ifdef USBPHY USBPHY_Type *usb_phy = USBPHY; -#else + #else USBPHY_Type *usb_phy = USBPHY1; -#endif + #endif // Enable PHY support for Low speed device + LS via FS Hub usb_phy->CTRL |= USBPHY_CTRL_SET_ENUTMILEVEL2_MASK | USBPHY_CTRL_SET_ENUTMILEVEL3_MASK; diff --git a/ports/nrf/background.c b/ports/nrf/background.c index 10543ddb21..269bf6737f 100644 --- a/ports/nrf/background.c +++ b/ports/nrf/background.c @@ -46,14 +46,16 @@ #include "common-hal/_bleio/bonding.h" #endif -void port_start_background_task(void) {} -void port_finish_background_task(void) {} +void port_start_background_task(void) { +} +void port_finish_background_task(void) { +} void port_background_task(void) { -#if CIRCUITPY_AUDIOPWMIO + #if CIRCUITPY_AUDIOPWMIO audiopwmout_background(); -#endif -#if CIRCUITPY_AUDIOBUSIO + #endif + #if CIRCUITPY_AUDIOBUSIO i2s_background(); -#endif + #endif } diff --git a/ports/nrf/bluetooth/ble_drv.c b/ports/nrf/bluetooth/ble_drv.c index 67c6f34687..f1a982024c 100644 --- a/ports/nrf/bluetooth/ble_drv.c +++ b/ports/nrf/bluetooth/ble_drv.c @@ -55,7 +55,7 @@ void ble_drv_reset() { sd_flash_operation_status = SD_FLASH_OPERATION_DONE; } -void ble_drv_add_event_handler_entry(ble_drv_evt_handler_entry_t* entry, ble_drv_evt_handler_t func, void *param) { +void ble_drv_add_event_handler_entry(ble_drv_evt_handler_entry_t *entry, ble_drv_evt_handler_t func, void *param) { entry->next = MP_STATE_VM(ble_drv_evt_handler_entries); entry->param = param; entry->func = func; @@ -92,34 +92,34 @@ void ble_drv_remove_event_handler(ble_drv_evt_handler_t func, void *param) { } } -extern void tusb_hal_nrf_power_event (uint32_t event); +extern void tusb_hal_nrf_power_event(uint32_t event); void SD_EVT_IRQHandler(void) { uint32_t evt_id; while (sd_evt_get(&evt_id) != NRF_ERROR_NOT_FOUND) { switch (evt_id) { // usb power event - case NRF_EVT_POWER_USB_DETECTED: - case NRF_EVT_POWER_USB_POWER_READY: - case NRF_EVT_POWER_USB_REMOVED: { - int32_t usbevt = (evt_id == NRF_EVT_POWER_USB_DETECTED ) ? NRFX_POWER_USB_EVT_DETECTED: - (evt_id == NRF_EVT_POWER_USB_POWER_READY) ? NRFX_POWER_USB_EVT_READY : - (evt_id == NRF_EVT_POWER_USB_REMOVED ) ? NRFX_POWER_USB_EVT_REMOVED : -1; + case NRF_EVT_POWER_USB_DETECTED: + case NRF_EVT_POWER_USB_POWER_READY: + case NRF_EVT_POWER_USB_REMOVED: { + int32_t usbevt = (evt_id == NRF_EVT_POWER_USB_DETECTED) ? NRFX_POWER_USB_EVT_DETECTED: + (evt_id == NRF_EVT_POWER_USB_POWER_READY) ? NRFX_POWER_USB_EVT_READY : + (evt_id == NRF_EVT_POWER_USB_REMOVED) ? NRFX_POWER_USB_EVT_REMOVED : -1; - tusb_hal_nrf_power_event(usbevt); - } + tusb_hal_nrf_power_event(usbevt); + } break; // Set flag indicating that a flash operation has finished. - case NRF_EVT_FLASH_OPERATION_SUCCESS: - sd_flash_operation_status = SD_FLASH_OPERATION_DONE; - break; - case NRF_EVT_FLASH_OPERATION_ERROR: - sd_flash_operation_status = SD_FLASH_OPERATION_ERROR; - break; + case NRF_EVT_FLASH_OPERATION_SUCCESS: + sd_flash_operation_status = SD_FLASH_OPERATION_DONE; + break; + case NRF_EVT_FLASH_OPERATION_ERROR: + sd_flash_operation_status = SD_FLASH_OPERATION_ERROR; + break; - default: - break; + default: + break; } } @@ -134,7 +134,7 @@ void SD_EVT_IRQHandler(void) { break; } - ble_evt_t* event = (ble_evt_t *)m_ble_evt_buf; + ble_evt_t *event = (ble_evt_t *)m_ble_evt_buf; #if CIRCUITPY_VERBOSE_BLE mp_printf(&mp_plat_print, "BLE event: 0x%04x\n", event->header.evt_id); #endif @@ -154,7 +154,7 @@ void SD_EVT_IRQHandler(void) { } #if CIRCUITPY_VERBOSE_BLE if (event->header.evt_id == BLE_GATTS_EVT_WRITE) { - ble_gatts_evt_write_t* write_evt = &event->evt.gatts_evt.params.write; + ble_gatts_evt_write_t *write_evt = &event->evt.gatts_evt.params.write; mp_printf(&mp_plat_print, "Write to: UUID(0x%04x) handle %x of length %d auth %x\n", write_evt->uuid.uuid, write_evt->handle, write_evt->len, write_evt->auth_required); } #endif diff --git a/ports/nrf/bluetooth/ble_drv.h b/ports/nrf/bluetooth/ble_drv.h index d69f83e6ef..e7649fceee 100644 --- a/ports/nrf/bluetooth/ble_drv.h +++ b/ports/nrf/bluetooth/ble_drv.h @@ -41,7 +41,7 @@ #define MSEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000) / (RESOLUTION)) #define SEC_TO_UNITS(TIME, RESOLUTION) (((TIME) * 1000000) / (RESOLUTION)) -#define UNITS_TO_SEC(TIME, RESOLUTION) (((TIME) * (RESOLUTION)) / 1000000) +#define UNITS_TO_SEC(TIME, RESOLUTION) (((TIME)*(RESOLUTION)) / 1000000) // 0.625 msecs (625 usecs) #define ADV_INTERVAL_UNIT_FLOAT_SECS (0.000625) // Microseconds is the base unit. The macros above know that. @@ -49,7 +49,7 @@ #define UNIT_1_25_MS (1250) #define UNIT_10_MS (10000) -typedef bool (*ble_drv_evt_handler_t)(ble_evt_t*, void*); +typedef bool (*ble_drv_evt_handler_t)(ble_evt_t *, void *); typedef enum { SD_FLASH_OPERATION_DONE, @@ -71,6 +71,6 @@ void ble_drv_add_event_handler(ble_drv_evt_handler_t func, void *param); void ble_drv_remove_event_handler(ble_drv_evt_handler_t func, void *param); // Allow for user provided entries to prevent allocations outside the VM. -void ble_drv_add_event_handler_entry(ble_drv_evt_handler_entry_t* entry, ble_drv_evt_handler_t func, void *param); +void ble_drv_add_event_handler_entry(ble_drv_evt_handler_entry_t *entry, ble_drv_evt_handler_t func, void *param); #endif // MICROPY_INCLUDED_NRF_BLUETOOTH_BLE_DRV_H diff --git a/ports/nrf/bluetooth/ble_uart.c b/ports/nrf/bluetooth/ble_uart.c index 1b87b82d11..df64568678 100644 --- a/ports/nrf/bluetooth/ble_uart.c +++ b/ports/nrf/bluetooth/ble_uart.c @@ -66,26 +66,24 @@ static ringbuffer_t m_rx_ring_buffer = { STATIC void on_ble_evt(ble_evt_t *ble_evt, void *param) { switch (ble_evt->header.evt_id) { - case BLE_GAP_EVT_DISCONNECTED: - { + case BLE_GAP_EVT_DISCONNECTED: { mp_obj_t device_obj = MP_OBJ_FROM_PTR(&m_device); mp_call_function_0(mp_load_attr(device_obj, qstr_from_str("start_advertising"))); break; } - case BLE_GATTS_EVT_WRITE: - { + case BLE_GATTS_EVT_WRITE: { ble_gatts_evt_write_t *write = &ble_evt->evt.gatts_evt.params.write; if (write->handle == m_tx_chara->cccd_handle) { m_cccd_enabled = true; } else if (write->handle == m_rx_chara->handle) { for (size_t i = 0; i < write->len; ++i) { -#if MICROPY_KBD_EXCEPTION + #if MICROPY_KBD_EXCEPTION if (write->data[i] == mp_interrupt_char) { mp_keyboard_interrupt(); } else -#endif + #endif { bufferWrite(&m_rx_ring_buffer, write->data[i]); } @@ -143,7 +141,7 @@ void ble_uart_init(void) { } bool ble_uart_connected(void) { - return (m_device.conn_handle != BLE_CONN_HANDLE_INVALID); + return m_device.conn_handle != BLE_CONN_HANDLE_INVALID; } char ble_uart_rx_chr(void) { @@ -179,7 +177,7 @@ void mp_hal_stdout_tx_strn(const char *str, size_t len) { } mp_buffer_info_t bufinfo = { - .buf = (uint8_t*)str, + .buf = (uint8_t *)str, .len = send_len, }; diff --git a/ports/nrf/bluetooth/ringbuffer.h b/ports/nrf/bluetooth/ringbuffer.h index 9a06e7ccc4..baf2732931 100644 --- a/ports/nrf/bluetooth/ringbuffer.h +++ b/ports/nrf/bluetooth/ringbuffer.h @@ -65,18 +65,18 @@ #define _ringbuffer_h #define ringBuffer_typedef(T, NAME) \ - typedef struct { \ - int size; \ - volatile int start; \ - volatile int end; \ - T* elems; \ - } NAME + typedef struct { \ + int size; \ + volatile int start; \ + volatile int end; \ + T *elems; \ + } NAME #define bufferInit(BUF, S, T) \ - BUF.size = S+1; \ - BUF.start = 0; \ - BUF.end = 0; \ - BUF.elems = (T*)calloc(BUF.size, sizeof(T)) + BUF.size = S + 1; \ + BUF.start = 0; \ + BUF.end = 0; \ + BUF.elems = (T *)calloc(BUF.size, sizeof(T)) #define bufferDestroy(BUF) free((BUF)->elems) @@ -86,11 +86,11 @@ #define isBufferFull(BUF) (nextEndIndex(BUF) == (BUF)->start) #define bufferWrite(BUF, ELEM) \ - (BUF)->elems[(BUF)->end] = ELEM; \ - (BUF)->end = ((BUF)->end + 1) % (BUF)->size; \ - if (isBufferEmpty(BUF)) { \ - (BUF)->start = nextStartIndex(BUF); \ - } + (BUF)->elems[(BUF)->end] = ELEM; \ + (BUF)->end = ((BUF)->end + 1) % (BUF)->size; \ + if (isBufferEmpty(BUF)) { \ + (BUF)->start = nextStartIndex(BUF); \ + } #define bufferRead(BUF, ELEM) \ ELEM = (BUF)->elems[(BUF)->start]; \ diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble.h index e2abcd7ad8..2ee2c74dce 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble.h @@ -71,17 +71,17 @@ extern "C" { */ enum BLE_COMMON_SVCS { - SD_BLE_ENABLE = BLE_SVC_BASE, /**< Enable and initialize the BLE stack */ - SD_BLE_EVT_GET, /**< Get an event from the pending events queue. */ - SD_BLE_UUID_VS_ADD, /**< Add a Vendor Specific base UUID. */ - SD_BLE_UUID_DECODE, /**< Decode UUID bytes. */ - SD_BLE_UUID_ENCODE, /**< Encode UUID bytes. */ - SD_BLE_VERSION_GET, /**< Get the local version information (company ID, Link Layer Version, Link Layer Subversion). */ - SD_BLE_USER_MEM_REPLY, /**< User Memory Reply. */ - SD_BLE_OPT_SET, /**< Set a BLE option. */ - SD_BLE_OPT_GET, /**< Get a BLE option. */ - SD_BLE_CFG_SET, /**< Add a configuration to the BLE stack. */ - SD_BLE_UUID_VS_REMOVE, /**< Remove a Vendor Specific base UUID. */ + SD_BLE_ENABLE = BLE_SVC_BASE, /**< Enable and initialize the BLE stack */ + SD_BLE_EVT_GET, /**< Get an event from the pending events queue. */ + SD_BLE_UUID_VS_ADD, /**< Add a Vendor Specific base UUID. */ + SD_BLE_UUID_DECODE, /**< Decode UUID bytes. */ + SD_BLE_UUID_ENCODE, /**< Encode UUID bytes. */ + SD_BLE_VERSION_GET, /**< Get the local version information (company ID, Link Layer Version, Link Layer Subversion). */ + SD_BLE_USER_MEM_REPLY, /**< User Memory Reply. */ + SD_BLE_OPT_SET, /**< Set a BLE option. */ + SD_BLE_OPT_GET, /**< Get a BLE option. */ + SD_BLE_CFG_SET, /**< Add a configuration to the BLE stack. */ + SD_BLE_UUID_VS_REMOVE, /**< Remove a Vendor Specific base UUID. */ }; /** @@ -89,8 +89,8 @@ enum BLE_COMMON_SVCS */ enum BLE_COMMON_EVTS { - BLE_EVT_USER_MEM_REQUEST = BLE_EVT_BASE + 0, /**< User Memory request. @ref ble_evt_user_mem_request_t */ - BLE_EVT_USER_MEM_RELEASE = BLE_EVT_BASE + 1, /**< User Memory release. @ref ble_evt_user_mem_release_t */ + BLE_EVT_USER_MEM_REQUEST = BLE_EVT_BASE + 0, /**< User Memory request. @ref ble_evt_user_mem_request_t */ + BLE_EVT_USER_MEM_RELEASE = BLE_EVT_BASE + 1, /**< User Memory release. @ref ble_evt_user_mem_release_t */ }; /**@brief BLE Connection Configuration IDs. @@ -112,7 +112,7 @@ enum BLE_CONN_CFGS */ enum BLE_COMMON_CFGS { - BLE_COMMON_CFG_VS_UUID = BLE_CFG_BASE, /**< Vendor specific base UUID configuration */ + BLE_COMMON_CFG_VS_UUID = BLE_CFG_BASE, /**< Vendor specific base UUID configuration */ }; /**@brief Common Option IDs. @@ -120,9 +120,9 @@ enum BLE_COMMON_CFGS */ enum BLE_COMMON_OPTS { - BLE_COMMON_OPT_PA_LNA = BLE_OPT_BASE + 0, /**< PA and LNA options */ - BLE_COMMON_OPT_CONN_EVT_EXT = BLE_OPT_BASE + 1, /**< Extended connection events option */ - BLE_COMMON_OPT_EXTENDED_RC_CAL = BLE_OPT_BASE + 2, /**< Extended RC calibration option */ + BLE_COMMON_OPT_PA_LNA = BLE_OPT_BASE + 0,/**< PA and LNA options */ + BLE_COMMON_OPT_CONN_EVT_EXT = BLE_OPT_BASE + 1,/**< Extended connection events option */ + BLE_COMMON_OPT_EXTENDED_RC_CAL = BLE_OPT_BASE + 2, /**< Extended RC calibration option */ }; /** @} */ @@ -143,8 +143,8 @@ enum BLE_COMMON_OPTS * If that value has not been configured for any connections then @ref BLE_GATT_ATT_MTU_DEFAULT must be used instead. */ #define BLE_EVT_LEN_MAX(ATT_MTU) ( \ - offsetof(ble_evt_t, evt.gattc_evt.params.prim_srvc_disc_rsp.services) + ((ATT_MTU) - 1) / 4 * sizeof(ble_gattc_service_t) \ -) + offsetof(ble_evt_t, evt.gattc_evt.params.prim_srvc_disc_rsp.services) + ((ATT_MTU)-1) / 4 * sizeof(ble_gattc_service_t) \ + ) /** @defgroup BLE_USER_MEM_TYPES User Memory Types * @{ */ @@ -174,53 +174,53 @@ enum BLE_COMMON_OPTS /**@brief User Memory Block. */ typedef struct { - uint8_t *p_mem; /**< Pointer to the start of the user memory block. */ - uint16_t len; /**< Length in bytes of the user memory block. */ + uint8_t *p_mem; /**< Pointer to the start of the user memory block. */ + uint16_t len; /**< Length in bytes of the user memory block. */ } ble_user_mem_block_t; /**@brief Event structure for @ref BLE_EVT_USER_MEM_REQUEST. */ typedef struct { - uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ + uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ } ble_evt_user_mem_request_t; /**@brief Event structure for @ref BLE_EVT_USER_MEM_RELEASE. */ typedef struct { - uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ - ble_user_mem_block_t mem_block; /**< User memory block */ + uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ + ble_user_mem_block_t mem_block; /**< User memory block */ } ble_evt_user_mem_release_t; /**@brief Event structure for events not associated with a specific function module. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which this event occurred. */ - union - { - ble_evt_user_mem_request_t user_mem_request; /**< User Memory Request Event Parameters. */ - ble_evt_user_mem_release_t user_mem_release; /**< User Memory Release Event Parameters. */ - } params; /**< Event parameter union. */ + uint16_t conn_handle; /**< Connection Handle on which this event occurred. */ + union + { + ble_evt_user_mem_request_t user_mem_request; /**< User Memory Request Event Parameters. */ + ble_evt_user_mem_release_t user_mem_release; /**< User Memory Release Event Parameters. */ + } params; /**< Event parameter union. */ } ble_common_evt_t; /**@brief BLE Event header. */ typedef struct { - uint16_t evt_id; /**< Value from a BLE__EVT series. */ - uint16_t evt_len; /**< Length in octets including this header. */ + uint16_t evt_id; /**< Value from a BLE__EVT series. */ + uint16_t evt_len; /**< Length in octets including this header. */ } ble_evt_hdr_t; /**@brief Common BLE Event type, wrapping the module specific event reports. */ typedef struct { - ble_evt_hdr_t header; /**< Event header. */ - union - { - ble_common_evt_t common_evt; /**< Common Event, evt_id in BLE_EVT_* series. */ - ble_gap_evt_t gap_evt; /**< GAP originated event, evt_id in BLE_GAP_EVT_* series. */ - ble_gattc_evt_t gattc_evt; /**< GATT client originated event, evt_id in BLE_GATTC_EVT* series. */ - ble_gatts_evt_t gatts_evt; /**< GATT server originated event, evt_id in BLE_GATTS_EVT* series. */ - ble_l2cap_evt_t l2cap_evt; /**< L2CAP originated event, evt_id in BLE_L2CAP_EVT* series. */ - } evt; /**< Event union. */ + ble_evt_hdr_t header; /**< Event header. */ + union + { + ble_common_evt_t common_evt; /**< Common Event, evt_id in BLE_EVT_* series. */ + ble_gap_evt_t gap_evt; /**< GAP originated event, evt_id in BLE_GAP_EVT_* series. */ + ble_gattc_evt_t gattc_evt; /**< GATT client originated event, evt_id in BLE_GATTC_EVT* series. */ + ble_gatts_evt_t gatts_evt; /**< GATT server originated event, evt_id in BLE_GATTS_EVT* series. */ + ble_l2cap_evt_t l2cap_evt; /**< L2CAP originated event, evt_id in BLE_L2CAP_EVT* series. */ + } evt; /**< Event union. */ } ble_evt_t; @@ -229,9 +229,9 @@ typedef struct */ typedef struct { - uint8_t version_number; /**< Link Layer Version number. See https://www.bluetooth.org/en-us/specification/assigned-numbers/link-layer for assigned values. */ - uint16_t company_id; /**< Company ID, Nordic Semiconductor's company ID is 89 (0x0059) (https://www.bluetooth.org/apps/content/Default.aspx?doc_id=49708). */ - uint16_t subversion_number; /**< Link Layer Sub Version number, corresponds to the SoftDevice Config ID or Firmware ID (FWID). */ + uint8_t version_number; /**< Link Layer Version number. See https://www.bluetooth.org/en-us/specification/assigned-numbers/link-layer for assigned values. */ + uint16_t company_id; /**< Company ID, Nordic Semiconductor's company ID is 89 (0x0059) (https://www.bluetooth.org/apps/content/Default.aspx?doc_id=49708). */ + uint16_t subversion_number; /**< Link Layer Sub Version number, corresponds to the SoftDevice Config ID or Firmware ID (FWID). */ } ble_version_t; /** @@ -239,9 +239,9 @@ typedef struct */ typedef struct { - uint8_t enable :1; /**< Enable toggling for this amplifier */ - uint8_t active_high :1; /**< Set the pin to be active high */ - uint8_t gpio_pin :6; /**< The GPIO pin to toggle for this amplifier */ + uint8_t enable : 1; /**< Enable toggling for this amplifier */ + uint8_t active_high : 1; /**< Set the pin to be active high */ + uint8_t gpio_pin : 6; /**< The GPIO pin to toggle for this amplifier */ } ble_pa_lna_cfg_t; /** @@ -259,12 +259,12 @@ typedef struct */ typedef struct { - ble_pa_lna_cfg_t pa_cfg; /**< Power Amplifier configuration */ - ble_pa_lna_cfg_t lna_cfg; /**< Low Noise Amplifier configuration */ + ble_pa_lna_cfg_t pa_cfg; /**< Power Amplifier configuration */ + ble_pa_lna_cfg_t lna_cfg; /**< Low Noise Amplifier configuration */ - uint8_t ppi_ch_id_set; /**< PPI channel used for radio pin setting */ - uint8_t ppi_ch_id_clr; /**< PPI channel used for radio pin clearing */ - uint8_t gpiote_ch_id; /**< GPIOTE channel used for radio pin toggling */ + uint8_t ppi_ch_id_set; /**< PPI channel used for radio pin setting */ + uint8_t ppi_ch_id_clr; /**< PPI channel used for radio pin clearing */ + uint8_t gpiote_ch_id; /**< GPIOTE channel used for radio pin toggling */ } ble_common_opt_pa_lna_t; /** @@ -280,7 +280,7 @@ typedef struct */ typedef struct { - uint8_t enable : 1; /**< Enable extended BLE connection events, disabled by default. */ + uint8_t enable : 1; /**< Enable extended BLE connection events, disabled by default. */ } ble_common_opt_conn_evt_ext_t; /** @@ -300,22 +300,22 @@ typedef struct */ typedef struct { - uint8_t enable : 1; /**< Enable extended RC calibration, enabled by default. */ + uint8_t enable : 1; /**< Enable extended RC calibration, enabled by default. */ } ble_common_opt_extended_rc_cal_t; /**@brief Option structure for common options. */ typedef union { - ble_common_opt_pa_lna_t pa_lna; /**< Parameters for controlling PA and LNA pin toggling. */ - ble_common_opt_conn_evt_ext_t conn_evt_ext; /**< Parameters for enabling extended connection events. */ - ble_common_opt_extended_rc_cal_t extended_rc_cal; /**< Parameters for enabling extended RC calibration. */ + ble_common_opt_pa_lna_t pa_lna; /**< Parameters for controlling PA and LNA pin toggling. */ + ble_common_opt_conn_evt_ext_t conn_evt_ext; /**< Parameters for enabling extended connection events. */ + ble_common_opt_extended_rc_cal_t extended_rc_cal; /**< Parameters for enabling extended RC calibration. */ } ble_common_opt_t; /**@brief Common BLE Option type, wrapping the module specific options. */ typedef union { - ble_common_opt_t common_opt; /**< COMMON options, opt_id in @ref BLE_COMMON_OPTS series. */ - ble_gap_opt_t gap_opt; /**< GAP option, opt_id in @ref BLE_GAP_OPTS series. */ + ble_common_opt_t common_opt; /**< COMMON options, opt_id in @ref BLE_COMMON_OPTS series. */ + ble_gap_opt_t gap_opt; /**< GAP option, opt_id in @ref BLE_GAP_OPTS series. */ } ble_opt_t; /**@brief BLE connection configuration type, wrapping the module specific configurations, set with @@ -337,17 +337,17 @@ typedef union */ typedef struct { - uint8_t conn_cfg_tag; /**< The application chosen tag it can use with the + uint8_t conn_cfg_tag; /**< The application chosen tag it can use with the @ref sd_ble_gap_adv_start() and @ref sd_ble_gap_connect() calls to select this configuration when creating a connection. Must be different for all connection configurations added and not @ref BLE_CONN_CFG_TAG_DEFAULT. */ - union { - ble_gap_conn_cfg_t gap_conn_cfg; /**< GAP connection configuration, cfg_id is @ref BLE_CONN_CFG_GAP. */ - ble_gattc_conn_cfg_t gattc_conn_cfg; /**< GATTC connection configuration, cfg_id is @ref BLE_CONN_CFG_GATTC. */ - ble_gatts_conn_cfg_t gatts_conn_cfg; /**< GATTS connection configuration, cfg_id is @ref BLE_CONN_CFG_GATTS. */ - ble_gatt_conn_cfg_t gatt_conn_cfg; /**< GATT connection configuration, cfg_id is @ref BLE_CONN_CFG_GATT. */ - ble_l2cap_conn_cfg_t l2cap_conn_cfg; /**< L2CAP connection configuration, cfg_id is @ref BLE_CONN_CFG_L2CAP. */ - } params; /**< Connection configuration union. */ + union { + ble_gap_conn_cfg_t gap_conn_cfg; /**< GAP connection configuration, cfg_id is @ref BLE_CONN_CFG_GAP. */ + ble_gattc_conn_cfg_t gattc_conn_cfg; /**< GATTC connection configuration, cfg_id is @ref BLE_CONN_CFG_GATTC. */ + ble_gatts_conn_cfg_t gatts_conn_cfg; /**< GATTS connection configuration, cfg_id is @ref BLE_CONN_CFG_GATTS. */ + ble_gatt_conn_cfg_t gatt_conn_cfg; /**< GATT connection configuration, cfg_id is @ref BLE_CONN_CFG_GATT. */ + ble_l2cap_conn_cfg_t l2cap_conn_cfg; /**< L2CAP connection configuration, cfg_id is @ref BLE_CONN_CFG_L2CAP. */ + } params; /**< Connection configuration union. */ } ble_conn_cfg_t; /** @@ -357,7 +357,7 @@ typedef struct */ typedef struct { - uint8_t vs_uuid_count; /**< Number of 128-bit Vendor Specific base UUID bases to allocate memory for. + uint8_t vs_uuid_count; /**< Number of 128-bit Vendor Specific base UUID bases to allocate memory for. Default value is @ref BLE_UUID_VS_COUNT_DEFAULT. Maximum value is @ref BLE_UUID_VS_COUNT_MAX. */ } ble_common_cfg_vs_uuid_t; @@ -365,16 +365,16 @@ typedef struct /**@brief Common BLE Configuration type, wrapping the common configurations. */ typedef union { - ble_common_cfg_vs_uuid_t vs_uuid_cfg; /**< Vendor Specific base UUID configuration, cfg_id is @ref BLE_COMMON_CFG_VS_UUID. */ + ble_common_cfg_vs_uuid_t vs_uuid_cfg; /**< Vendor Specific base UUID configuration, cfg_id is @ref BLE_COMMON_CFG_VS_UUID. */ } ble_common_cfg_t; /**@brief BLE Configuration type, wrapping the module specific configurations. */ typedef union { - ble_conn_cfg_t conn_cfg; /**< Connection specific configurations, cfg_id in @ref BLE_CONN_CFGS series. */ - ble_common_cfg_t common_cfg; /**< Global common configurations, cfg_id in @ref BLE_COMMON_CFGS series. */ - ble_gap_cfg_t gap_cfg; /**< Global GAP configurations, cfg_id in @ref BLE_GAP_CFGS series. */ - ble_gatts_cfg_t gatts_cfg; /**< Global GATTS configuration, cfg_id in @ref BLE_GATTS_CFGS series. */ + ble_conn_cfg_t conn_cfg; /**< Connection specific configurations, cfg_id in @ref BLE_CONN_CFGS series. */ + ble_common_cfg_t common_cfg; /**< Global common configurations, cfg_id in @ref BLE_COMMON_CFGS series. */ + ble_gap_cfg_t gap_cfg; /**< Global GAP configurations, cfg_id in @ref BLE_GAP_CFGS series. */ + ble_gatts_cfg_t gatts_cfg; /**< Global GATTS configuration, cfg_id in @ref BLE_GATTS_CFGS series. */ } ble_cfg_t; /** @} */ @@ -450,7 +450,7 @@ SVCALL(SD_BLE_ENABLE, uint32_t, sd_ble_enable(uint32_t * p_app_ram_base)); * @retval ::NRF_ERROR_NO_MEM The amount of memory assigned to the SoftDevice by app_ram_base is not * large enough to fit this configuration's memory requirement. */ -SVCALL(SD_BLE_CFG_SET, uint32_t, sd_ble_cfg_set(uint32_t cfg_id, ble_cfg_t const * p_cfg, uint32_t app_ram_base)); +SVCALL(SD_BLE_CFG_SET, uint32_t, sd_ble_cfg_set(uint32_t cfg_id, ble_cfg_t const *p_cfg, uint32_t app_ram_base)); /**@brief Get an event from the pending events queue. * @@ -488,7 +488,7 @@ SVCALL(SD_BLE_CFG_SET, uint32_t, sd_ble_cfg_set(uint32_t cfg_id, ble_cfg_t const * @retval ::NRF_ERROR_NOT_FOUND No events ready to be pulled. * @retval ::NRF_ERROR_DATA_SIZE Event ready but could not fit into the supplied buffer. */ -SVCALL(SD_BLE_EVT_GET, uint32_t, sd_ble_evt_get(uint8_t *p_dest, uint16_t *p_len)); +SVCALL(SD_BLE_EVT_GET, uint32_t, sd_ble_evt_get(uint8_t * p_dest, uint16_t * p_len)); /**@brief Add a Vendor Specific base UUID. @@ -517,7 +517,7 @@ SVCALL(SD_BLE_EVT_GET, uint32_t, sd_ble_evt_get(uint8_t *p_dest, uint16_t *p_len * @retval ::NRF_ERROR_INVALID_ADDR If p_vs_uuid or p_uuid_type is NULL or invalid. * @retval ::NRF_ERROR_NO_MEM If there are no more free slots for VS UUIDs. */ -SVCALL(SD_BLE_UUID_VS_ADD, uint32_t, sd_ble_uuid_vs_add(ble_uuid128_t const *p_vs_uuid, uint8_t *p_uuid_type)); +SVCALL(SD_BLE_UUID_VS_ADD, uint32_t, sd_ble_uuid_vs_add(ble_uuid128_t const *p_vs_uuid, uint8_t * p_uuid_type)); /**@brief Remove a Vendor Specific base UUID. @@ -539,7 +539,7 @@ SVCALL(SD_BLE_UUID_VS_ADD, uint32_t, sd_ble_uuid_vs_add(ble_uuid128_t const *p_v * @retval ::NRF_ERROR_FORBIDDEN If the Vendor Specific base UUID is in use by the ATT Server. */ -SVCALL(SD_BLE_UUID_VS_REMOVE, uint32_t, sd_ble_uuid_vs_remove(uint8_t *p_uuid_type)); +SVCALL(SD_BLE_UUID_VS_REMOVE, uint32_t, sd_ble_uuid_vs_remove(uint8_t * p_uuid_type)); /** @brief Decode little endian raw UUID bytes (16-bit or 128-bit) into a 24 bit @ref ble_uuid_t structure. @@ -560,7 +560,7 @@ SVCALL(SD_BLE_UUID_VS_REMOVE, uint32_t, sd_ble_uuid_vs_remove(uint8_t *p_uuid_ty * @retval ::NRF_ERROR_INVALID_LENGTH Invalid UUID length. * @retval ::NRF_ERROR_NOT_FOUND For a 128-bit UUID, no match in the populated table of UUIDs. */ -SVCALL(SD_BLE_UUID_DECODE, uint32_t, sd_ble_uuid_decode(uint8_t uuid_le_len, uint8_t const *p_uuid_le, ble_uuid_t *p_uuid)); +SVCALL(SD_BLE_UUID_DECODE, uint32_t, sd_ble_uuid_decode(uint8_t uuid_le_len, uint8_t const *p_uuid_le, ble_uuid_t * p_uuid)); /** @brief Encode a @ref ble_uuid_t structure into little endian raw UUID bytes (16-bit or 128-bit). @@ -575,7 +575,7 @@ SVCALL(SD_BLE_UUID_DECODE, uint32_t, sd_ble_uuid_decode(uint8_t uuid_le_len, uin * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::NRF_ERROR_INVALID_PARAM Invalid UUID type. */ -SVCALL(SD_BLE_UUID_ENCODE, uint32_t, sd_ble_uuid_encode(ble_uuid_t const *p_uuid, uint8_t *p_uuid_le_len, uint8_t *p_uuid_le)); +SVCALL(SD_BLE_UUID_ENCODE, uint32_t, sd_ble_uuid_encode(ble_uuid_t const *p_uuid, uint8_t * p_uuid_le_len, uint8_t * p_uuid_le)); /**@brief Get Version Information. @@ -588,7 +588,7 @@ SVCALL(SD_BLE_UUID_ENCODE, uint32_t, sd_ble_uuid_encode(ble_uuid_t const *p_uuid * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::NRF_ERROR_BUSY The BLE stack is busy (typically doing a locally-initiated disconnection procedure). */ -SVCALL(SD_BLE_VERSION_GET, uint32_t, sd_ble_version_get(ble_version_t *p_version)); +SVCALL(SD_BLE_VERSION_GET, uint32_t, sd_ble_version_get(ble_version_t * p_version)); /**@brief Provide a user memory block. @@ -653,7 +653,7 @@ SVCALL(SD_BLE_OPT_SET, uint32_t, sd_ble_opt_set(uint32_t opt_id, ble_opt_t const * @retval ::NRF_ERROR_NOT_SUPPORTED This option is not supported. * */ -SVCALL(SD_BLE_OPT_GET, uint32_t, sd_ble_opt_get(uint32_t opt_id, ble_opt_t *p_opt)); +SVCALL(SD_BLE_OPT_GET, uint32_t, sd_ble_opt_get(uint32_t opt_id, ble_opt_t * p_opt)); /** @} */ #ifdef __cplusplus diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_err.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_err.h index 1b4820dc3d..64e610a2f2 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_err.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_err.h @@ -62,12 +62,12 @@ extern "C" { /* @defgroup BLE_ERRORS Error Codes * @{ */ -#define BLE_ERROR_NOT_ENABLED (NRF_ERROR_STK_BASE_NUM+0x001) /**< @ref sd_ble_enable has not been called. */ -#define BLE_ERROR_INVALID_CONN_HANDLE (NRF_ERROR_STK_BASE_NUM+0x002) /**< Invalid connection handle. */ -#define BLE_ERROR_INVALID_ATTR_HANDLE (NRF_ERROR_STK_BASE_NUM+0x003) /**< Invalid attribute handle. */ -#define BLE_ERROR_INVALID_ADV_HANDLE (NRF_ERROR_STK_BASE_NUM+0x004) /**< Invalid advertising handle. */ -#define BLE_ERROR_INVALID_ROLE (NRF_ERROR_STK_BASE_NUM+0x005) /**< Invalid role. */ -#define BLE_ERROR_BLOCKED_BY_OTHER_LINKS (NRF_ERROR_STK_BASE_NUM+0x006) /**< The attempt to change link settings failed due to the scheduling of other links. */ +#define BLE_ERROR_NOT_ENABLED (NRF_ERROR_STK_BASE_NUM + 0x001) /**< @ref sd_ble_enable has not been called. */ +#define BLE_ERROR_INVALID_CONN_HANDLE (NRF_ERROR_STK_BASE_NUM + 0x002) /**< Invalid connection handle. */ +#define BLE_ERROR_INVALID_ATTR_HANDLE (NRF_ERROR_STK_BASE_NUM + 0x003) /**< Invalid attribute handle. */ +#define BLE_ERROR_INVALID_ADV_HANDLE (NRF_ERROR_STK_BASE_NUM + 0x004) /**< Invalid advertising handle. */ +#define BLE_ERROR_INVALID_ROLE (NRF_ERROR_STK_BASE_NUM + 0x005) /**< Invalid role. */ +#define BLE_ERROR_BLOCKED_BY_OTHER_LINKS (NRF_ERROR_STK_BASE_NUM + 0x006) /**< The attempt to change link settings failed due to the scheduling of other links. */ /** @} */ @@ -75,10 +75,10 @@ extern "C" { * @brief Assignment of subranges for module specific error codes. * @note For specific error codes, see ble_.h or ble_error_.h. * @{ */ -#define NRF_L2CAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x100) /**< L2CAP specific errors. */ -#define NRF_GAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x200) /**< GAP specific errors. */ -#define NRF_GATTC_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x300) /**< GATT client specific errors. */ -#define NRF_GATTS_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x400) /**< GATT server specific errors. */ +#define NRF_L2CAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM + 0x100) /**< L2CAP specific errors. */ +#define NRF_GAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM + 0x200) /**< GAP specific errors. */ +#define NRF_GATTC_ERR_BASE (NRF_ERROR_STK_BASE_NUM + 0x300) /**< GATT client specific errors. */ +#define NRF_GATTS_ERR_BASE (NRF_ERROR_STK_BASE_NUM + 0x400) /**< GATT server specific errors. */ /** @} */ #ifdef __cplusplus diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gap.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gap.h index 6750e742f7..f5a8199a98 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gap.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gap.h @@ -64,46 +64,46 @@ extern "C" { */ enum BLE_GAP_SVCS { - SD_BLE_GAP_ADDR_SET = BLE_GAP_SVC_BASE, /**< Set own Bluetooth Address. */ - SD_BLE_GAP_ADDR_GET = BLE_GAP_SVC_BASE + 1, /**< Get own Bluetooth Address. */ - SD_BLE_GAP_WHITELIST_SET = BLE_GAP_SVC_BASE + 2, /**< Set active whitelist. */ - SD_BLE_GAP_DEVICE_IDENTITIES_SET = BLE_GAP_SVC_BASE + 3, /**< Set device identity list. */ - SD_BLE_GAP_PRIVACY_SET = BLE_GAP_SVC_BASE + 4, /**< Set Privacy settings*/ - SD_BLE_GAP_PRIVACY_GET = BLE_GAP_SVC_BASE + 5, /**< Get Privacy settings*/ - SD_BLE_GAP_ADV_SET_CONFIGURE = BLE_GAP_SVC_BASE + 6, /**< Configure an advertising set. */ - SD_BLE_GAP_ADV_START = BLE_GAP_SVC_BASE + 7, /**< Start Advertising. */ - SD_BLE_GAP_ADV_STOP = BLE_GAP_SVC_BASE + 8, /**< Stop Advertising. */ - SD_BLE_GAP_CONN_PARAM_UPDATE = BLE_GAP_SVC_BASE + 9, /**< Connection Parameter Update. */ - SD_BLE_GAP_DISCONNECT = BLE_GAP_SVC_BASE + 10, /**< Disconnect. */ - SD_BLE_GAP_TX_POWER_SET = BLE_GAP_SVC_BASE + 11, /**< Set TX Power. */ - SD_BLE_GAP_APPEARANCE_SET = BLE_GAP_SVC_BASE + 12, /**< Set Appearance. */ - SD_BLE_GAP_APPEARANCE_GET = BLE_GAP_SVC_BASE + 13, /**< Get Appearance. */ - SD_BLE_GAP_PPCP_SET = BLE_GAP_SVC_BASE + 14, /**< Set PPCP. */ - SD_BLE_GAP_PPCP_GET = BLE_GAP_SVC_BASE + 15, /**< Get PPCP. */ - SD_BLE_GAP_DEVICE_NAME_SET = BLE_GAP_SVC_BASE + 16, /**< Set Device Name. */ - SD_BLE_GAP_DEVICE_NAME_GET = BLE_GAP_SVC_BASE + 17, /**< Get Device Name. */ - SD_BLE_GAP_AUTHENTICATE = BLE_GAP_SVC_BASE + 18, /**< Initiate Pairing/Bonding. */ - SD_BLE_GAP_SEC_PARAMS_REPLY = BLE_GAP_SVC_BASE + 19, /**< Reply with Security Parameters. */ - SD_BLE_GAP_AUTH_KEY_REPLY = BLE_GAP_SVC_BASE + 20, /**< Reply with an authentication key. */ - SD_BLE_GAP_LESC_DHKEY_REPLY = BLE_GAP_SVC_BASE + 21, /**< Reply with an LE Secure Connections DHKey. */ - SD_BLE_GAP_KEYPRESS_NOTIFY = BLE_GAP_SVC_BASE + 22, /**< Notify of a keypress during an authentication procedure. */ - SD_BLE_GAP_LESC_OOB_DATA_GET = BLE_GAP_SVC_BASE + 23, /**< Get the local LE Secure Connections OOB data. */ - SD_BLE_GAP_LESC_OOB_DATA_SET = BLE_GAP_SVC_BASE + 24, /**< Set the remote LE Secure Connections OOB data. */ - SD_BLE_GAP_ENCRYPT = BLE_GAP_SVC_BASE + 25, /**< Initiate encryption procedure. */ - SD_BLE_GAP_SEC_INFO_REPLY = BLE_GAP_SVC_BASE + 26, /**< Reply with Security Information. */ - SD_BLE_GAP_CONN_SEC_GET = BLE_GAP_SVC_BASE + 27, /**< Obtain connection security level. */ - SD_BLE_GAP_RSSI_START = BLE_GAP_SVC_BASE + 28, /**< Start reporting of changes in RSSI. */ - SD_BLE_GAP_RSSI_STOP = BLE_GAP_SVC_BASE + 29, /**< Stop reporting of changes in RSSI. */ - SD_BLE_GAP_SCAN_START = BLE_GAP_SVC_BASE + 30, /**< Start Scanning. */ - SD_BLE_GAP_SCAN_STOP = BLE_GAP_SVC_BASE + 31, /**< Stop Scanning. */ - SD_BLE_GAP_CONNECT = BLE_GAP_SVC_BASE + 32, /**< Connect. */ - SD_BLE_GAP_CONNECT_CANCEL = BLE_GAP_SVC_BASE + 33, /**< Cancel ongoing connection procedure. */ - SD_BLE_GAP_RSSI_GET = BLE_GAP_SVC_BASE + 34, /**< Get the last RSSI sample. */ - SD_BLE_GAP_PHY_UPDATE = BLE_GAP_SVC_BASE + 35, /**< Initiate or respond to a PHY Update Procedure. */ - SD_BLE_GAP_DATA_LENGTH_UPDATE = BLE_GAP_SVC_BASE + 36, /**< Initiate or respond to a Data Length Update Procedure. */ - SD_BLE_GAP_QOS_CHANNEL_SURVEY_START = BLE_GAP_SVC_BASE + 37, /**< Start Quality of Service (QoS) channel survey module. */ - SD_BLE_GAP_QOS_CHANNEL_SURVEY_STOP = BLE_GAP_SVC_BASE + 38, /**< Stop Quality of Service (QoS) channel survey module. */ - SD_BLE_GAP_ADV_ADDR_GET = BLE_GAP_SVC_BASE + 39, /**< Get the Address used on air while Advertising. */ + SD_BLE_GAP_ADDR_SET = BLE_GAP_SVC_BASE, /**< Set own Bluetooth Address. */ + SD_BLE_GAP_ADDR_GET = BLE_GAP_SVC_BASE + 1, /**< Get own Bluetooth Address. */ + SD_BLE_GAP_WHITELIST_SET = BLE_GAP_SVC_BASE + 2, /**< Set active whitelist. */ + SD_BLE_GAP_DEVICE_IDENTITIES_SET = BLE_GAP_SVC_BASE + 3, /**< Set device identity list. */ + SD_BLE_GAP_PRIVACY_SET = BLE_GAP_SVC_BASE + 4, /**< Set Privacy settings*/ + SD_BLE_GAP_PRIVACY_GET = BLE_GAP_SVC_BASE + 5, /**< Get Privacy settings*/ + SD_BLE_GAP_ADV_SET_CONFIGURE = BLE_GAP_SVC_BASE + 6, /**< Configure an advertising set. */ + SD_BLE_GAP_ADV_START = BLE_GAP_SVC_BASE + 7, /**< Start Advertising. */ + SD_BLE_GAP_ADV_STOP = BLE_GAP_SVC_BASE + 8, /**< Stop Advertising. */ + SD_BLE_GAP_CONN_PARAM_UPDATE = BLE_GAP_SVC_BASE + 9, /**< Connection Parameter Update. */ + SD_BLE_GAP_DISCONNECT = BLE_GAP_SVC_BASE + 10,/**< Disconnect. */ + SD_BLE_GAP_TX_POWER_SET = BLE_GAP_SVC_BASE + 11,/**< Set TX Power. */ + SD_BLE_GAP_APPEARANCE_SET = BLE_GAP_SVC_BASE + 12,/**< Set Appearance. */ + SD_BLE_GAP_APPEARANCE_GET = BLE_GAP_SVC_BASE + 13,/**< Get Appearance. */ + SD_BLE_GAP_PPCP_SET = BLE_GAP_SVC_BASE + 14,/**< Set PPCP. */ + SD_BLE_GAP_PPCP_GET = BLE_GAP_SVC_BASE + 15,/**< Get PPCP. */ + SD_BLE_GAP_DEVICE_NAME_SET = BLE_GAP_SVC_BASE + 16,/**< Set Device Name. */ + SD_BLE_GAP_DEVICE_NAME_GET = BLE_GAP_SVC_BASE + 17,/**< Get Device Name. */ + SD_BLE_GAP_AUTHENTICATE = BLE_GAP_SVC_BASE + 18,/**< Initiate Pairing/Bonding. */ + SD_BLE_GAP_SEC_PARAMS_REPLY = BLE_GAP_SVC_BASE + 19,/**< Reply with Security Parameters. */ + SD_BLE_GAP_AUTH_KEY_REPLY = BLE_GAP_SVC_BASE + 20,/**< Reply with an authentication key. */ + SD_BLE_GAP_LESC_DHKEY_REPLY = BLE_GAP_SVC_BASE + 21,/**< Reply with an LE Secure Connections DHKey. */ + SD_BLE_GAP_KEYPRESS_NOTIFY = BLE_GAP_SVC_BASE + 22,/**< Notify of a keypress during an authentication procedure. */ + SD_BLE_GAP_LESC_OOB_DATA_GET = BLE_GAP_SVC_BASE + 23,/**< Get the local LE Secure Connections OOB data. */ + SD_BLE_GAP_LESC_OOB_DATA_SET = BLE_GAP_SVC_BASE + 24,/**< Set the remote LE Secure Connections OOB data. */ + SD_BLE_GAP_ENCRYPT = BLE_GAP_SVC_BASE + 25,/**< Initiate encryption procedure. */ + SD_BLE_GAP_SEC_INFO_REPLY = BLE_GAP_SVC_BASE + 26,/**< Reply with Security Information. */ + SD_BLE_GAP_CONN_SEC_GET = BLE_GAP_SVC_BASE + 27,/**< Obtain connection security level. */ + SD_BLE_GAP_RSSI_START = BLE_GAP_SVC_BASE + 28,/**< Start reporting of changes in RSSI. */ + SD_BLE_GAP_RSSI_STOP = BLE_GAP_SVC_BASE + 29,/**< Stop reporting of changes in RSSI. */ + SD_BLE_GAP_SCAN_START = BLE_GAP_SVC_BASE + 30,/**< Start Scanning. */ + SD_BLE_GAP_SCAN_STOP = BLE_GAP_SVC_BASE + 31,/**< Stop Scanning. */ + SD_BLE_GAP_CONNECT = BLE_GAP_SVC_BASE + 32,/**< Connect. */ + SD_BLE_GAP_CONNECT_CANCEL = BLE_GAP_SVC_BASE + 33,/**< Cancel ongoing connection procedure. */ + SD_BLE_GAP_RSSI_GET = BLE_GAP_SVC_BASE + 34,/**< Get the last RSSI sample. */ + SD_BLE_GAP_PHY_UPDATE = BLE_GAP_SVC_BASE + 35,/**< Initiate or respond to a PHY Update Procedure. */ + SD_BLE_GAP_DATA_LENGTH_UPDATE = BLE_GAP_SVC_BASE + 36,/**< Initiate or respond to a Data Length Update Procedure. */ + SD_BLE_GAP_QOS_CHANNEL_SURVEY_START = BLE_GAP_SVC_BASE + 37,/**< Start Quality of Service (QoS) channel survey module. */ + SD_BLE_GAP_QOS_CHANNEL_SURVEY_STOP = BLE_GAP_SVC_BASE + 38,/**< Stop Quality of Service (QoS) channel survey module. */ + SD_BLE_GAP_ADV_ADDR_GET = BLE_GAP_SVC_BASE + 39,/**< Get the Address used on air while Advertising. */ }; /**@brief GAP Event IDs. @@ -111,29 +111,29 @@ enum BLE_GAP_SVCS */ enum BLE_GAP_EVTS { - BLE_GAP_EVT_CONNECTED = BLE_GAP_EVT_BASE, /**< Connected to peer. \n See @ref ble_gap_evt_connected_t */ - BLE_GAP_EVT_DISCONNECTED = BLE_GAP_EVT_BASE + 1, /**< Disconnected from peer. \n See @ref ble_gap_evt_disconnected_t. */ - BLE_GAP_EVT_CONN_PARAM_UPDATE = BLE_GAP_EVT_BASE + 2, /**< Connection Parameters updated. \n See @ref ble_gap_evt_conn_param_update_t. */ - BLE_GAP_EVT_SEC_PARAMS_REQUEST = BLE_GAP_EVT_BASE + 3, /**< Request to provide security parameters. \n Reply with @ref sd_ble_gap_sec_params_reply. \n See @ref ble_gap_evt_sec_params_request_t. */ - BLE_GAP_EVT_SEC_INFO_REQUEST = BLE_GAP_EVT_BASE + 4, /**< Request to provide security information. \n Reply with @ref sd_ble_gap_sec_info_reply. \n See @ref ble_gap_evt_sec_info_request_t. */ - BLE_GAP_EVT_PASSKEY_DISPLAY = BLE_GAP_EVT_BASE + 5, /**< Request to display a passkey to the user. \n In LESC Numeric Comparison, reply with @ref sd_ble_gap_auth_key_reply. \n See @ref ble_gap_evt_passkey_display_t. */ - BLE_GAP_EVT_KEY_PRESSED = BLE_GAP_EVT_BASE + 6, /**< Notification of a keypress on the remote device.\n See @ref ble_gap_evt_key_pressed_t */ - BLE_GAP_EVT_AUTH_KEY_REQUEST = BLE_GAP_EVT_BASE + 7, /**< Request to provide an authentication key. \n Reply with @ref sd_ble_gap_auth_key_reply. \n See @ref ble_gap_evt_auth_key_request_t. */ - BLE_GAP_EVT_LESC_DHKEY_REQUEST = BLE_GAP_EVT_BASE + 8, /**< Request to calculate an LE Secure Connections DHKey. \n Reply with @ref sd_ble_gap_lesc_dhkey_reply. \n See @ref ble_gap_evt_lesc_dhkey_request_t */ - BLE_GAP_EVT_AUTH_STATUS = BLE_GAP_EVT_BASE + 9, /**< Authentication procedure completed with status. \n See @ref ble_gap_evt_auth_status_t. */ - BLE_GAP_EVT_CONN_SEC_UPDATE = BLE_GAP_EVT_BASE + 10, /**< Connection security updated. \n See @ref ble_gap_evt_conn_sec_update_t. */ - BLE_GAP_EVT_TIMEOUT = BLE_GAP_EVT_BASE + 11, /**< Timeout expired. \n See @ref ble_gap_evt_timeout_t. */ - BLE_GAP_EVT_RSSI_CHANGED = BLE_GAP_EVT_BASE + 12, /**< RSSI report. \n See @ref ble_gap_evt_rssi_changed_t. */ - BLE_GAP_EVT_ADV_REPORT = BLE_GAP_EVT_BASE + 13, /**< Advertising report. \n See @ref ble_gap_evt_adv_report_t. */ - BLE_GAP_EVT_SEC_REQUEST = BLE_GAP_EVT_BASE + 14, /**< Security Request. \n See @ref ble_gap_evt_sec_request_t. */ - BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 15, /**< Connection Parameter Update Request. \n Reply with @ref sd_ble_gap_conn_param_update. \n See @ref ble_gap_evt_conn_param_update_request_t. */ - BLE_GAP_EVT_SCAN_REQ_REPORT = BLE_GAP_EVT_BASE + 16, /**< Scan request report. \n See @ref ble_gap_evt_scan_req_report_t. */ - BLE_GAP_EVT_PHY_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 17, /**< PHY Update Request. \n Reply with @ref sd_ble_gap_phy_update. \n See @ref ble_gap_evt_phy_update_request_t. */ - BLE_GAP_EVT_PHY_UPDATE = BLE_GAP_EVT_BASE + 18, /**< PHY Update Procedure is complete. \n See @ref ble_gap_evt_phy_update_t. */ - BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 19, /**< Data Length Update Request. \n Reply with @ref sd_ble_gap_data_length_update.\n See @ref ble_gap_evt_data_length_update_request_t. */ - BLE_GAP_EVT_DATA_LENGTH_UPDATE = BLE_GAP_EVT_BASE + 20, /**< LL Data Channel PDU payload length updated. \n See @ref ble_gap_evt_data_length_update_t. */ - BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT = BLE_GAP_EVT_BASE + 21, /**< Channel survey report. \n See @ref ble_gap_evt_qos_channel_survey_report_t. */ - BLE_GAP_EVT_ADV_SET_TERMINATED = BLE_GAP_EVT_BASE + 22, /**< Advertising set terminated. \n See @ref ble_gap_evt_adv_set_terminated_t. */ + BLE_GAP_EVT_CONNECTED = BLE_GAP_EVT_BASE, /**< Connected to peer. \n See @ref ble_gap_evt_connected_t */ + BLE_GAP_EVT_DISCONNECTED = BLE_GAP_EVT_BASE + 1, /**< Disconnected from peer. \n See @ref ble_gap_evt_disconnected_t. */ + BLE_GAP_EVT_CONN_PARAM_UPDATE = BLE_GAP_EVT_BASE + 2, /**< Connection Parameters updated. \n See @ref ble_gap_evt_conn_param_update_t. */ + BLE_GAP_EVT_SEC_PARAMS_REQUEST = BLE_GAP_EVT_BASE + 3, /**< Request to provide security parameters. \n Reply with @ref sd_ble_gap_sec_params_reply. \n See @ref ble_gap_evt_sec_params_request_t. */ + BLE_GAP_EVT_SEC_INFO_REQUEST = BLE_GAP_EVT_BASE + 4, /**< Request to provide security information. \n Reply with @ref sd_ble_gap_sec_info_reply. \n See @ref ble_gap_evt_sec_info_request_t. */ + BLE_GAP_EVT_PASSKEY_DISPLAY = BLE_GAP_EVT_BASE + 5, /**< Request to display a passkey to the user. \n In LESC Numeric Comparison, reply with @ref sd_ble_gap_auth_key_reply. \n See @ref ble_gap_evt_passkey_display_t. */ + BLE_GAP_EVT_KEY_PRESSED = BLE_GAP_EVT_BASE + 6, /**< Notification of a keypress on the remote device.\n See @ref ble_gap_evt_key_pressed_t */ + BLE_GAP_EVT_AUTH_KEY_REQUEST = BLE_GAP_EVT_BASE + 7, /**< Request to provide an authentication key. \n Reply with @ref sd_ble_gap_auth_key_reply. \n See @ref ble_gap_evt_auth_key_request_t. */ + BLE_GAP_EVT_LESC_DHKEY_REQUEST = BLE_GAP_EVT_BASE + 8, /**< Request to calculate an LE Secure Connections DHKey. \n Reply with @ref sd_ble_gap_lesc_dhkey_reply. \n See @ref ble_gap_evt_lesc_dhkey_request_t */ + BLE_GAP_EVT_AUTH_STATUS = BLE_GAP_EVT_BASE + 9, /**< Authentication procedure completed with status. \n See @ref ble_gap_evt_auth_status_t. */ + BLE_GAP_EVT_CONN_SEC_UPDATE = BLE_GAP_EVT_BASE + 10,/**< Connection security updated. \n See @ref ble_gap_evt_conn_sec_update_t. */ + BLE_GAP_EVT_TIMEOUT = BLE_GAP_EVT_BASE + 11,/**< Timeout expired. \n See @ref ble_gap_evt_timeout_t. */ + BLE_GAP_EVT_RSSI_CHANGED = BLE_GAP_EVT_BASE + 12,/**< RSSI report. \n See @ref ble_gap_evt_rssi_changed_t. */ + BLE_GAP_EVT_ADV_REPORT = BLE_GAP_EVT_BASE + 13,/**< Advertising report. \n See @ref ble_gap_evt_adv_report_t. */ + BLE_GAP_EVT_SEC_REQUEST = BLE_GAP_EVT_BASE + 14,/**< Security Request. \n See @ref ble_gap_evt_sec_request_t. */ + BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 15,/**< Connection Parameter Update Request. \n Reply with @ref sd_ble_gap_conn_param_update. \n See @ref ble_gap_evt_conn_param_update_request_t. */ + BLE_GAP_EVT_SCAN_REQ_REPORT = BLE_GAP_EVT_BASE + 16,/**< Scan request report. \n See @ref ble_gap_evt_scan_req_report_t. */ + BLE_GAP_EVT_PHY_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 17,/**< PHY Update Request. \n Reply with @ref sd_ble_gap_phy_update. \n See @ref ble_gap_evt_phy_update_request_t. */ + BLE_GAP_EVT_PHY_UPDATE = BLE_GAP_EVT_BASE + 18,/**< PHY Update Procedure is complete. \n See @ref ble_gap_evt_phy_update_t. */ + BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 19, /**< Data Length Update Request. \n Reply with @ref sd_ble_gap_data_length_update.\n See @ref ble_gap_evt_data_length_update_request_t. */ + BLE_GAP_EVT_DATA_LENGTH_UPDATE = BLE_GAP_EVT_BASE + 20, /**< LL Data Channel PDU payload length updated. \n See @ref ble_gap_evt_data_length_update_t. */ + BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT = BLE_GAP_EVT_BASE + 21, /**< Channel survey report. \n See @ref ble_gap_evt_qos_channel_survey_report_t. */ + BLE_GAP_EVT_ADV_SET_TERMINATED = BLE_GAP_EVT_BASE + 22, /**< Advertising set terminated. \n See @ref ble_gap_evt_adv_set_terminated_t. */ }; /**@brief GAP Option IDs. @@ -141,12 +141,12 @@ enum BLE_GAP_EVTS */ enum BLE_GAP_OPTS { - BLE_GAP_OPT_CH_MAP = BLE_GAP_OPT_BASE, /**< Channel Map. @ref ble_gap_opt_ch_map_t */ - BLE_GAP_OPT_LOCAL_CONN_LATENCY = BLE_GAP_OPT_BASE + 1, /**< Local connection latency. @ref ble_gap_opt_local_conn_latency_t */ - BLE_GAP_OPT_PASSKEY = BLE_GAP_OPT_BASE + 2, /**< Set passkey. @ref ble_gap_opt_passkey_t */ - BLE_GAP_OPT_COMPAT_MODE_1 = BLE_GAP_OPT_BASE + 3, /**< Compatibility mode. @ref ble_gap_opt_compat_mode_1_t */ - BLE_GAP_OPT_AUTH_PAYLOAD_TIMEOUT = BLE_GAP_OPT_BASE + 4, /**< Set Authenticated payload timeout. @ref ble_gap_opt_auth_payload_timeout_t */ - BLE_GAP_OPT_SLAVE_LATENCY_DISABLE = BLE_GAP_OPT_BASE + 5, /**< Disable slave latency. @ref ble_gap_opt_slave_latency_disable_t */ + BLE_GAP_OPT_CH_MAP = BLE_GAP_OPT_BASE, /**< Channel Map. @ref ble_gap_opt_ch_map_t */ + BLE_GAP_OPT_LOCAL_CONN_LATENCY = BLE_GAP_OPT_BASE + 1, /**< Local connection latency. @ref ble_gap_opt_local_conn_latency_t */ + BLE_GAP_OPT_PASSKEY = BLE_GAP_OPT_BASE + 2, /**< Set passkey. @ref ble_gap_opt_passkey_t */ + BLE_GAP_OPT_COMPAT_MODE_1 = BLE_GAP_OPT_BASE + 3, /**< Compatibility mode. @ref ble_gap_opt_compat_mode_1_t */ + BLE_GAP_OPT_AUTH_PAYLOAD_TIMEOUT = BLE_GAP_OPT_BASE + 4, /**< Set Authenticated payload timeout. @ref ble_gap_opt_auth_payload_timeout_t */ + BLE_GAP_OPT_SLAVE_LATENCY_DISABLE = BLE_GAP_OPT_BASE + 5, /**< Disable slave latency. @ref ble_gap_opt_slave_latency_disable_t */ }; /**@brief GAP Configuration IDs. @@ -155,17 +155,17 @@ enum BLE_GAP_OPTS */ enum BLE_GAP_CFGS { - BLE_GAP_CFG_ROLE_COUNT = BLE_GAP_CFG_BASE, /**< Role count configuration. */ - BLE_GAP_CFG_DEVICE_NAME = BLE_GAP_CFG_BASE + 1, /**< Device name configuration. */ + BLE_GAP_CFG_ROLE_COUNT = BLE_GAP_CFG_BASE, /**< Role count configuration. */ + BLE_GAP_CFG_DEVICE_NAME = BLE_GAP_CFG_BASE + 1,/**< Device name configuration. */ }; /**@brief GAP TX Power roles. */ enum BLE_GAP_TX_POWER_ROLES { - BLE_GAP_TX_POWER_ROLE_ADV = 1, /**< Advertiser role. */ - BLE_GAP_TX_POWER_ROLE_SCAN_INIT = 2, /**< Scanner and initiator role. */ - BLE_GAP_TX_POWER_ROLE_CONN = 3, /**< Connection role. */ + BLE_GAP_TX_POWER_ROLE_ADV = 1, /**< Advertiser role. */ + BLE_GAP_TX_POWER_ROLE_SCAN_INIT = 2, /**< Scanner and initiator role. */ + BLE_GAP_TX_POWER_ROLE_CONN = 3, /**< Connection role. */ }; /** @} */ @@ -315,28 +315,28 @@ enum BLE_GAP_TX_POWER_ROLES * @{ */ #define BLE_GAP_ADV_INTERVAL_MIN 0x000020 /**< Minimum Advertising interval in 625 us units, i.e. 20 ms. */ #define BLE_GAP_ADV_INTERVAL_MAX 0x004000 /**< Maximum Advertising interval in 625 us units, i.e. 10.24 s. */ - /**@} */ +/**@} */ /**@defgroup BLE_GAP_SCAN_INTERVALS GAP Scan interval max and min * @{ */ #define BLE_GAP_SCAN_INTERVAL_MIN 0x0004 /**< Minimum Scan interval in 625 us units, i.e. 2.5 ms. */ #define BLE_GAP_SCAN_INTERVAL_MAX 0xFFFF /**< Maximum Scan interval in 625 us units, i.e. 40,959.375 s. */ - /** @} */ +/** @} */ /**@defgroup BLE_GAP_SCAN_WINDOW GAP Scan window max and min * @{ */ #define BLE_GAP_SCAN_WINDOW_MIN 0x0004 /**< Minimum Scan window in 625 us units, i.e. 2.5 ms. */ #define BLE_GAP_SCAN_WINDOW_MAX 0xFFFF /**< Maximum Scan window in 625 us units, i.e. 40,959.375 s. */ - /** @} */ +/** @} */ /**@defgroup BLE_GAP_SCAN_TIMEOUT GAP Scan timeout max and min * @{ */ #define BLE_GAP_SCAN_TIMEOUT_MIN 0x0001 /**< Minimum Scan timeout in 10 ms units, i.e 10 ms. */ #define BLE_GAP_SCAN_TIMEOUT_UNLIMITED 0x0000 /**< Continue to scan forever. */ - /** @} */ +/** @} */ /**@defgroup BLE_GAP_SCAN_BUFFER_SIZE GAP Minimum scanner buffer size * @@ -555,19 +555,19 @@ enum BLE_GAP_TX_POWER_ROLES * See @ref ble_gap_conn_sec_mode_t. * @{ */ /**@brief Set sec_mode pointed to by ptr to have no access rights.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(ptr) do {(ptr)->sm = 0; (ptr)->lv = 0;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(ptr) do {(ptr)->sm = 0; (ptr)->lv = 0;} while (0) /**@brief Set sec_mode pointed to by ptr to require no protection, open link.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_OPEN(ptr) do {(ptr)->sm = 1; (ptr)->lv = 1;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_OPEN(ptr) do {(ptr)->sm = 1; (ptr)->lv = 1;} while (0) /**@brief Set sec_mode pointed to by ptr to require encryption, but no MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 2;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 2;} while (0) /**@brief Set sec_mode pointed to by ptr to require encryption and MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 3;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 3;} while (0) /**@brief Set sec_mode pointed to by ptr to require LESC encryption and MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_LESC_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 4;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_LESC_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 4;} while (0) /**@brief Set sec_mode pointed to by ptr to require signing or encryption, no MITM protection needed.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 1;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 1;} while (0) /**@brief Set sec_mode pointed to by ptr to require signing or encryption with MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 2;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 2;} while (0) /**@} */ @@ -642,7 +642,7 @@ enum BLE_GAP_TX_POWER_ROLES #define BLE_GAP_QOS_CHANNEL_SURVEY_INTERVAL_CONTINUOUS (0) /**< Continuous channel survey. */ #define BLE_GAP_QOS_CHANNEL_SURVEY_INTERVAL_MIN_US (7500) /**< Minimum channel survey interval in microseconds (7.5 ms). */ #define BLE_GAP_QOS_CHANNEL_SURVEY_INTERVAL_MAX_US (4000000) /**< Maximum channel survey interval in microseconds (4 s). */ - /**@} */ +/**@} */ /** @} */ @@ -653,45 +653,45 @@ enum BLE_GAP_TX_POWER_ROLES /**@brief Advertising event properties. */ typedef struct { - uint8_t type; /**< Advertising type. See @ref BLE_GAP_ADV_TYPES. */ - uint8_t anonymous : 1; /**< Omit advertiser's address from all PDUs. + uint8_t type; /**< Advertising type. See @ref BLE_GAP_ADV_TYPES. */ + uint8_t anonymous : 1;/**< Omit advertiser's address from all PDUs. @note Anonymous advertising is only available for @ref BLE_GAP_ADV_TYPE_EXTENDED_NONCONNECTABLE_NONSCANNABLE_UNDIRECTED and @ref BLE_GAP_ADV_TYPE_EXTENDED_NONCONNECTABLE_NONSCANNABLE_DIRECTED. */ - uint8_t include_tx_power : 1; /**< This feature is not supported on this SoftDevice. */ + uint8_t include_tx_power : 1; /**< This feature is not supported on this SoftDevice. */ } ble_gap_adv_properties_t; /**@brief Advertising report type. */ typedef struct { - uint16_t connectable : 1; /**< Connectable advertising event type. */ - uint16_t scannable : 1; /**< Scannable advertising event type. */ - uint16_t directed : 1; /**< Directed advertising event type. */ - uint16_t scan_response : 1; /**< Received a scan response. */ - uint16_t extended_pdu : 1; /**< Received an extended advertising set. */ - uint16_t status : 2; /**< Data status. See @ref BLE_GAP_ADV_DATA_STATUS. */ - uint16_t reserved : 9; /**< Reserved for future use. */ + uint16_t connectable : 1;/**< Connectable advertising event type. */ + uint16_t scannable : 1;/**< Scannable advertising event type. */ + uint16_t directed : 1;/**< Directed advertising event type. */ + uint16_t scan_response : 1; /**< Received a scan response. */ + uint16_t extended_pdu : 1;/**< Received an extended advertising set. */ + uint16_t status : 2;/**< Data status. See @ref BLE_GAP_ADV_DATA_STATUS. */ + uint16_t reserved : 9;/**< Reserved for future use. */ } ble_gap_adv_report_type_t; /**@brief Advertising Auxiliary Pointer. */ typedef struct { - uint16_t aux_offset; /**< Time offset from the beginning of advertising packet to the auxiliary packet in 100 us units. */ - uint8_t aux_phy; /**< Indicates the PHY on which the auxiliary advertising packet is sent. See @ref BLE_GAP_PHYS. */ + uint16_t aux_offset; /**< Time offset from the beginning of advertising packet to the auxiliary packet in 100 us units. */ + uint8_t aux_phy; /**< Indicates the PHY on which the auxiliary advertising packet is sent. See @ref BLE_GAP_PHYS. */ } ble_gap_aux_pointer_t; /**@brief Bluetooth Low Energy address. */ typedef struct { - uint8_t addr_id_peer : 1; /**< Only valid for peer addresses. + uint8_t addr_id_peer : 1; /**< Only valid for peer addresses. This bit is set by the SoftDevice to indicate whether the address has been resolved from a Resolvable Private Address (when the peer is using privacy). If set to 1, @ref addr and @ref addr_type refer to the identity address of the resolved address. This bit is ignored when a variable of type @ref ble_gap_addr_t is used as input to API functions. */ - uint8_t addr_type : 7; /**< See @ref BLE_GAP_ADDR_TYPES. */ - uint8_t addr[BLE_GAP_ADDR_LEN]; /**< 48-bit address, LSB format. + uint8_t addr_type : 7; /**< See @ref BLE_GAP_ADDR_TYPES. */ + uint8_t addr[BLE_GAP_ADDR_LEN]; /**< 48-bit address, LSB format. @ref addr is not used if @ref addr_type is @ref BLE_GAP_ADDR_TYPE_ANONYMOUS. */ } ble_gap_addr_t; @@ -709,10 +709,10 @@ typedef struct */ typedef struct { - uint16_t min_conn_interval; /**< Minimum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t max_conn_interval; /**< Maximum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t slave_latency; /**< Slave Latency in number of connection events, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t conn_sup_timeout; /**< Connection Supervision Timeout in 10 ms units, see @ref BLE_GAP_CP_LIMITS.*/ + uint16_t min_conn_interval; /**< Minimum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ + uint16_t max_conn_interval; /**< Maximum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ + uint16_t slave_latency; /**< Slave Latency in number of connection events, see @ref BLE_GAP_CP_LIMITS.*/ + uint16_t conn_sup_timeout; /**< Connection Supervision Timeout in 10 ms units, see @ref BLE_GAP_CP_LIMITS.*/ } ble_gap_conn_params_t; @@ -728,8 +728,8 @@ typedef struct */ typedef struct { - uint8_t sm : 4; /**< Security Mode (1 or 2), 0 for no permissions at all. */ - uint8_t lv : 4; /**< Level (1, 2, 3 or 4), 0 for no permissions at all. */ + uint8_t sm : 4; /**< Security Mode (1 or 2), 0 for no permissions at all. */ + uint8_t lv : 4; /**< Level (1, 2, 3 or 4), 0 for no permissions at all. */ } ble_gap_conn_sec_mode_t; @@ -737,14 +737,14 @@ typedef struct /**@brief GAP connection security status.*/ typedef struct { - ble_gap_conn_sec_mode_t sec_mode; /**< Currently active security mode for this connection.*/ - uint8_t encr_key_size; /**< Length of currently active encryption key, 7 to 16 octets (only applicable for bonding procedures). */ + ble_gap_conn_sec_mode_t sec_mode; /**< Currently active security mode for this connection.*/ + uint8_t encr_key_size; /**< Length of currently active encryption key, 7 to 16 octets (only applicable for bonding procedures). */ } ble_gap_conn_sec_t; /**@brief Identity Resolving Key. */ typedef struct { - uint8_t irk[BLE_GAP_SEC_KEY_LEN]; /**< Array containing IRK. */ + uint8_t irk[BLE_GAP_SEC_KEY_LEN]; /**< Array containing IRK. */ } ble_gap_irk_t; @@ -759,8 +759,8 @@ typedef uint8_t ble_gap_ch_mask_t[5]; /**@brief GAP advertising parameters. */ typedef struct { - ble_gap_adv_properties_t properties; /**< The properties of the advertising events. */ - ble_gap_addr_t const *p_peer_addr; /**< Address of a known peer. + ble_gap_adv_properties_t properties; /**< The properties of the advertising events. */ + ble_gap_addr_t const *p_peer_addr; /**< Address of a known peer. @note ble_gap_addr_t::addr_type cannot be @ref BLE_GAP_ADDR_TYPE_ANONYMOUS. - When privacy is enabled and the local device uses @@ -774,16 +774,16 @@ typedef struct in the device identity list, the peer IRK for that device will be used to generate @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE target addresses used in the advertising event PDUs. */ - uint32_t interval; /**< Advertising interval in 625 us units. @sa BLE_GAP_ADV_INTERVALS. + uint32_t interval; /**< Advertising interval in 625 us units. @sa BLE_GAP_ADV_INTERVALS. @note If @ref ble_gap_adv_properties_t::type is set to @ref BLE_GAP_ADV_TYPE_CONNECTABLE_NONSCANNABLE_DIRECTED_HIGH_DUTY_CYCLE advertising, this parameter is ignored. */ - uint16_t duration; /**< Advertising duration in 10 ms units. When timeout is reached, + uint16_t duration; /**< Advertising duration in 10 ms units. When timeout is reached, an event of type @ref BLE_GAP_EVT_ADV_SET_TERMINATED is raised. @sa BLE_GAP_ADV_TIMEOUT_VALUES. @note The SoftDevice will always complete at least one advertising event even if the duration is set too low. */ - uint8_t max_adv_evts; /**< Maximum advertising events that shall be sent prior to disabling + uint8_t max_adv_evts; /**< Maximum advertising events that shall be sent prior to disabling advertising. Setting the value to 0 disables the limitation. When the count of advertising events specified by this parameter (if not 0) is reached, advertising will be automatically stopped @@ -791,17 +791,17 @@ typedef struct @note If @ref ble_gap_adv_properties_t::type is set to @ref BLE_GAP_ADV_TYPE_CONNECTABLE_NONSCANNABLE_DIRECTED_HIGH_DUTY_CYCLE, this parameter is ignored. */ - ble_gap_ch_mask_t channel_mask; /**< Channel mask for primary and secondary advertising channels. + ble_gap_ch_mask_t channel_mask; /**< Channel mask for primary and secondary advertising channels. At least one of the primary channels, that is channel index 37-39, must be used. Masking away secondary advertising channels is not supported. */ - uint8_t filter_policy; /**< Filter Policy. @sa BLE_GAP_ADV_FILTER_POLICIES. */ - uint8_t primary_phy; /**< Indicates the PHY on which the primary advertising channel packets + uint8_t filter_policy; /**< Filter Policy. @sa BLE_GAP_ADV_FILTER_POLICIES. */ + uint8_t primary_phy; /**< Indicates the PHY on which the primary advertising channel packets are transmitted. If set to @ref BLE_GAP_PHY_AUTO, @ref BLE_GAP_PHY_1MBPS will be used. Valid values are @ref BLE_GAP_PHY_1MBPS and @ref BLE_GAP_PHY_CODED. @note The primary_phy shall indicate @ref BLE_GAP_PHY_1MBPS if @ref ble_gap_adv_properties_t::type is not an extended advertising type. */ - uint8_t secondary_phy; /**< Indicates the PHY on which the secondary advertising channel packets + uint8_t secondary_phy; /**< Indicates the PHY on which the secondary advertising channel packets are transmitted. If set to @ref BLE_GAP_PHY_AUTO, @ref BLE_GAP_PHY_1MBPS will be used. Valid values are @@ -811,11 +811,11 @@ typedef struct connection and send AUX_ADV_IND packets on. @note This parameter will be ignored when @ref ble_gap_adv_properties_t::type is not an extended advertising type. */ - uint8_t set_id:4; /**< The advertising set identifier distinguishes this advertising set from other + uint8_t set_id : 4; /**< The advertising set identifier distinguishes this advertising set from other advertising sets transmitted by this and other devices. @note This parameter will be ignored when @ref ble_gap_adv_properties_t::type is not an extended advertising type. */ - uint8_t scan_req_notification:1; /**< Enable scan request notifications for this advertising set. When a + uint8_t scan_req_notification : 1; /**< Enable scan request notifications for this advertising set. When a scan request is received and the scanner address is allowed by the filter policy, @ref BLE_GAP_EVT_SCAN_REQ_REPORT is raised. @note This parameter will be ignored when @@ -836,11 +836,11 @@ typedef struct * To update advertising data while advertising, provide new buffers to @ref sd_ble_gap_adv_set_configure. */ typedef struct { - ble_data_t adv_data; /**< Advertising data. + ble_data_t adv_data; /**< Advertising data. @note Advertising data can only be specified for a @ref ble_gap_adv_properties_t::type that is allowed to contain advertising data. */ - ble_data_t scan_rsp_data; /**< Scan response data. + ble_data_t scan_rsp_data; /**< Scan response data. @note Scan response data can only be specified for a @ref ble_gap_adv_properties_t::type that is scannable. */ @@ -850,11 +850,11 @@ typedef struct /**@brief GAP scanning parameters. */ typedef struct { - uint8_t extended : 1; /**< If 1, the scanner will accept extended advertising packets. + uint8_t extended : 1; /**< If 1, the scanner will accept extended advertising packets. If set to 0, the scanner will not receive advertising packets on secondary advertising channels, and will not be able to receive long advertising PDUs. */ - uint8_t report_incomplete_evts : 1; /**< If 1, events of type @ref ble_gap_evt_adv_report_t may have + uint8_t report_incomplete_evts : 1; /**< If 1, events of type @ref ble_gap_evt_adv_report_t may have @ref ble_gap_adv_report_type_t::status set to @ref BLE_GAP_ADV_DATA_STATUS_INCOMPLETE_MORE_DATA. This parameter is ignored when used with @ref sd_ble_gap_connect @@ -862,13 +862,13 @@ typedef struct advertising event, and is only available for extended scanning, see @ref sd_ble_gap_scan_start. @note This feature is not supported by this SoftDevice. */ - uint8_t active : 1; /**< If 1, perform active scanning by sending scan requests. + uint8_t active : 1; /**< If 1, perform active scanning by sending scan requests. This parameter is ignored when used with @ref sd_ble_gap_connect. */ - uint8_t filter_policy : 2; /**< Scanning filter policy. @sa BLE_GAP_SCAN_FILTER_POLICIES. + uint8_t filter_policy : 2; /**< Scanning filter policy. @sa BLE_GAP_SCAN_FILTER_POLICIES. @note Only @ref BLE_GAP_SCAN_FP_ACCEPT_ALL and @ref BLE_GAP_SCAN_FP_WHITELIST are valid when used with @ref sd_ble_gap_connect */ - uint8_t scan_phys; /**< Bitfield of PHYs to scan on. If set to @ref BLE_GAP_PHY_AUTO, + uint8_t scan_phys; /**< Bitfield of PHYs to scan on. If set to @ref BLE_GAP_PHY_AUTO, scan_phys will default to @ref BLE_GAP_PHY_1MBPS. - If @ref ble_gap_scan_params_t::extended is set to 0, the only supported PHY is @ref BLE_GAP_PHY_1MBPS. @@ -884,13 +884,13 @@ typedef struct PHY will also contain @ref BLE_GAP_PHY_CODED. If the only scan PHY is @ref BLE_GAP_PHY_CODED, the primary scan PHY is @ref BLE_GAP_PHY_CODED only. */ - uint16_t interval; /**< Scan interval in 625 us units. @sa BLE_GAP_SCAN_INTERVALS. */ - uint16_t window; /**< Scan window in 625 us units. @sa BLE_GAP_SCAN_WINDOW. + uint16_t interval; /**< Scan interval in 625 us units. @sa BLE_GAP_SCAN_INTERVALS. */ + uint16_t window; /**< Scan window in 625 us units. @sa BLE_GAP_SCAN_WINDOW. If scan_phys contains both @ref BLE_GAP_PHY_1MBPS and @ref BLE_GAP_PHY_CODED interval shall be larger than or equal to twice the scan window. */ - uint16_t timeout; /**< Scan timeout in 10 ms units. @sa BLE_GAP_SCAN_TIMEOUT. */ - ble_gap_ch_mask_t channel_mask; /**< Channel mask for primary and secondary advertising channels. + uint16_t timeout; /**< Scan timeout in 10 ms units. @sa BLE_GAP_SCAN_TIMEOUT. */ + ble_gap_ch_mask_t channel_mask; /**< Channel mask for primary and secondary advertising channels. At least one of the primary channels, that is channel index 37-39, must be set to 0. Masking away secondary channels is not supported. */ @@ -916,10 +916,10 @@ typedef struct */ typedef struct { - uint8_t privacy_mode; /**< Privacy mode, see @ref BLE_GAP_PRIVACY_MODES. Default is @ref BLE_GAP_PRIVACY_MODE_OFF. */ - uint8_t private_addr_type; /**< The private address type must be either @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE or @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE. */ - uint16_t private_addr_cycle_s; /**< Private address cycle interval in seconds. Providing an address cycle value of 0 will use the default value defined by @ref BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S. */ - ble_gap_irk_t *p_device_irk; /**< When used as input, pointer to IRK structure that will be used as the default IRK. If NULL, the device default IRK will be used. + uint8_t privacy_mode; /**< Privacy mode, see @ref BLE_GAP_PRIVACY_MODES. Default is @ref BLE_GAP_PRIVACY_MODE_OFF. */ + uint8_t private_addr_type; /**< The private address type must be either @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE or @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE. */ + uint16_t private_addr_cycle_s; /**< Private address cycle interval in seconds. Providing an address cycle value of 0 will use the default value defined by @ref BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S. */ + ble_gap_irk_t *p_device_irk; /**< When used as input, pointer to IRK structure that will be used as the default IRK. If NULL, the device default IRK will be used. When used as output, pointer to IRK structure where the current default IRK will be written to. If NULL, this argument is ignored. By default, the default IRK is used to generate random private resolvable addresses for the local device unless instructed otherwise. */ } ble_gap_privacy_params_t; @@ -935,98 +935,98 @@ typedef struct */ typedef struct { - uint8_t tx_phys; /**< Preferred transmit PHYs, see @ref BLE_GAP_PHYS. */ - uint8_t rx_phys; /**< Preferred receive PHYs, see @ref BLE_GAP_PHYS. */ + uint8_t tx_phys; /**< Preferred transmit PHYs, see @ref BLE_GAP_PHYS. */ + uint8_t rx_phys; /**< Preferred receive PHYs, see @ref BLE_GAP_PHYS. */ } ble_gap_phys_t; /** @brief Keys that can be exchanged during a bonding procedure. */ typedef struct { - uint8_t enc : 1; /**< Long Term Key and Master Identification. */ - uint8_t id : 1; /**< Identity Resolving Key and Identity Address Information. */ - uint8_t sign : 1; /**< Connection Signature Resolving Key. */ - uint8_t link : 1; /**< Derive the Link Key from the LTK. */ + uint8_t enc : 1; /**< Long Term Key and Master Identification. */ + uint8_t id : 1; /**< Identity Resolving Key and Identity Address Information. */ + uint8_t sign : 1; /**< Connection Signature Resolving Key. */ + uint8_t link : 1; /**< Derive the Link Key from the LTK. */ } ble_gap_sec_kdist_t; /**@brief GAP security parameters. */ typedef struct { - uint8_t bond : 1; /**< Perform bonding. */ - uint8_t mitm : 1; /**< Enable Man In The Middle protection. */ - uint8_t lesc : 1; /**< Enable LE Secure Connection pairing. */ - uint8_t keypress : 1; /**< Enable generation of keypress notifications. */ - uint8_t io_caps : 3; /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */ - uint8_t oob : 1; /**< The OOB data flag. + uint8_t bond : 1; /**< Perform bonding. */ + uint8_t mitm : 1; /**< Enable Man In The Middle protection. */ + uint8_t lesc : 1; /**< Enable LE Secure Connection pairing. */ + uint8_t keypress : 1; /**< Enable generation of keypress notifications. */ + uint8_t io_caps : 3; /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */ + uint8_t oob : 1; /**< The OOB data flag. - In LE legacy pairing, this flag is set if a device has out of band authentication data. The OOB method is used if both of the devices have out of band authentication data. - In LE Secure Connections pairing, this flag is set if a device has the peer device's out of band authentication data. The OOB method is used if at least one device has the peer device's OOB data available. */ - uint8_t min_key_size; /**< Minimum encryption key size in octets between 7 and 16. If 0 then not applicable in this instance. */ - uint8_t max_key_size; /**< Maximum encryption key size in octets between min_key_size and 16. */ - ble_gap_sec_kdist_t kdist_own; /**< Key distribution bitmap: keys that the local device will distribute. */ - ble_gap_sec_kdist_t kdist_peer; /**< Key distribution bitmap: keys that the remote device will distribute. */ + uint8_t min_key_size; /**< Minimum encryption key size in octets between 7 and 16. If 0 then not applicable in this instance. */ + uint8_t max_key_size; /**< Maximum encryption key size in octets between min_key_size and 16. */ + ble_gap_sec_kdist_t kdist_own; /**< Key distribution bitmap: keys that the local device will distribute. */ + ble_gap_sec_kdist_t kdist_peer; /**< Key distribution bitmap: keys that the remote device will distribute. */ } ble_gap_sec_params_t; /**@brief GAP Encryption Information. */ typedef struct { - uint8_t ltk[BLE_GAP_SEC_KEY_LEN]; /**< Long Term Key. */ - uint8_t lesc : 1; /**< Key generated using LE Secure Connections. */ - uint8_t auth : 1; /**< Authenticated Key. */ - uint8_t ltk_len : 6; /**< LTK length in octets. */ + uint8_t ltk[BLE_GAP_SEC_KEY_LEN]; /**< Long Term Key. */ + uint8_t lesc : 1; /**< Key generated using LE Secure Connections. */ + uint8_t auth : 1; /**< Authenticated Key. */ + uint8_t ltk_len : 6; /**< LTK length in octets. */ } ble_gap_enc_info_t; /**@brief GAP Master Identification. */ typedef struct { - uint16_t ediv; /**< Encrypted Diversifier. */ - uint8_t rand[BLE_GAP_SEC_RAND_LEN]; /**< Random Number. */ + uint16_t ediv; /**< Encrypted Diversifier. */ + uint8_t rand[BLE_GAP_SEC_RAND_LEN]; /**< Random Number. */ } ble_gap_master_id_t; /**@brief GAP Signing Information. */ typedef struct { - uint8_t csrk[BLE_GAP_SEC_KEY_LEN]; /**< Connection Signature Resolving Key. */ + uint8_t csrk[BLE_GAP_SEC_KEY_LEN]; /**< Connection Signature Resolving Key. */ } ble_gap_sign_info_t; /**@brief GAP LE Secure Connections P-256 Public Key. */ typedef struct { - uint8_t pk[BLE_GAP_LESC_P256_PK_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman P-256 Public Key. Stored in the standard SMP protocol format: {X,Y} both in little-endian. */ + uint8_t pk[BLE_GAP_LESC_P256_PK_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman P-256 Public Key. Stored in the standard SMP protocol format: {X,Y} both in little-endian. */ } ble_gap_lesc_p256_pk_t; /**@brief GAP LE Secure Connections DHKey. */ typedef struct { - uint8_t key[BLE_GAP_LESC_DHKEY_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman Key. Stored in little-endian. */ + uint8_t key[BLE_GAP_LESC_DHKEY_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman Key. Stored in little-endian. */ } ble_gap_lesc_dhkey_t; /**@brief GAP LE Secure Connections OOB data. */ typedef struct { - ble_gap_addr_t addr; /**< Bluetooth address of the device. */ - uint8_t r[BLE_GAP_SEC_KEY_LEN]; /**< Random Number. */ - uint8_t c[BLE_GAP_SEC_KEY_LEN]; /**< Confirm Value. */ + ble_gap_addr_t addr; /**< Bluetooth address of the device. */ + uint8_t r[BLE_GAP_SEC_KEY_LEN]; /**< Random Number. */ + uint8_t c[BLE_GAP_SEC_KEY_LEN]; /**< Confirm Value. */ } ble_gap_lesc_oob_data_t; /**@brief Event structure for @ref BLE_GAP_EVT_CONNECTED. */ typedef struct { - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 + ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 and the address is the device's identity address. */ - uint8_t role; /**< BLE role for this connection, see @ref BLE_GAP_ROLES */ - ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ - uint8_t adv_handle; /**< Advertising handle in which advertising has ended. + uint8_t role; /**< BLE role for this connection, see @ref BLE_GAP_ROLES */ + ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ + uint8_t adv_handle; /**< Advertising handle in which advertising has ended. This variable is only set if role is set to @ref BLE_GAP_ROLE_PERIPH. */ - ble_gap_adv_data_t adv_data; /**< Advertising buffers corresponding to the terminated + ble_gap_adv_data_t adv_data; /**< Advertising buffers corresponding to the terminated advertising set. The advertising buffers provided in @ref sd_ble_gap_adv_set_configure are now released. This variable is only set if role is set to @ref BLE_GAP_ROLE_PERIPH. */ @@ -1036,53 +1036,53 @@ typedef struct /**@brief Event structure for @ref BLE_GAP_EVT_DISCONNECTED. */ typedef struct { - uint8_t reason; /**< HCI error code, see @ref BLE_HCI_STATUS_CODES. */ + uint8_t reason; /**< HCI error code, see @ref BLE_HCI_STATUS_CODES. */ } ble_gap_evt_disconnected_t; /**@brief Event structure for @ref BLE_GAP_EVT_CONN_PARAM_UPDATE. */ typedef struct { - ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ + ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ } ble_gap_evt_conn_param_update_t; /**@brief Event structure for @ref BLE_GAP_EVT_PHY_UPDATE_REQUEST. */ typedef struct { - ble_gap_phys_t peer_preferred_phys; /**< The PHYs the peer prefers to use. */ + ble_gap_phys_t peer_preferred_phys; /**< The PHYs the peer prefers to use. */ } ble_gap_evt_phy_update_request_t; /**@brief Event Structure for @ref BLE_GAP_EVT_PHY_UPDATE. */ typedef struct { - uint8_t status; /**< Status of the procedure, see @ref BLE_HCI_STATUS_CODES.*/ - uint8_t tx_phy; /**< TX PHY for this connection, see @ref BLE_GAP_PHYS. */ - uint8_t rx_phy; /**< RX PHY for this connection, see @ref BLE_GAP_PHYS. */ + uint8_t status; /**< Status of the procedure, see @ref BLE_HCI_STATUS_CODES.*/ + uint8_t tx_phy; /**< TX PHY for this connection, see @ref BLE_GAP_PHYS. */ + uint8_t rx_phy; /**< RX PHY for this connection, see @ref BLE_GAP_PHYS. */ } ble_gap_evt_phy_update_t; /**@brief Event structure for @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST. */ typedef struct { - ble_gap_sec_params_t peer_params; /**< Initiator Security Parameters. */ + ble_gap_sec_params_t peer_params; /**< Initiator Security Parameters. */ } ble_gap_evt_sec_params_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_SEC_INFO_REQUEST. */ typedef struct { - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. */ - ble_gap_master_id_t master_id; /**< Master Identification for LTK lookup. */ - uint8_t enc_info : 1; /**< If 1, Encryption Information required. */ - uint8_t id_info : 1; /**< If 1, Identity Information required. */ - uint8_t sign_info : 1; /**< If 1, Signing Information required. */ + ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. */ + ble_gap_master_id_t master_id; /**< Master Identification for LTK lookup. */ + uint8_t enc_info : 1; /**< If 1, Encryption Information required. */ + uint8_t id_info : 1; /**< If 1, Identity Information required. */ + uint8_t sign_info : 1; /**< If 1, Signing Information required. */ } ble_gap_evt_sec_info_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_PASSKEY_DISPLAY. */ typedef struct { - uint8_t passkey[BLE_GAP_PASSKEY_LEN]; /**< 6-digit passkey in ASCII ('0'-'9' digits only). */ - uint8_t match_request : 1; /**< If 1 requires the application to report the match using @ref sd_ble_gap_auth_key_reply + uint8_t passkey[BLE_GAP_PASSKEY_LEN]; /**< 6-digit passkey in ASCII ('0'-'9' digits only). */ + uint8_t match_request : 1; /**< If 1 requires the application to report the match using @ref sd_ble_gap_auth_key_reply with either @ref BLE_GAP_AUTH_KEY_TYPE_NONE if there is no match or @ref BLE_GAP_AUTH_KEY_TYPE_PASSKEY if there is a match. */ } ble_gap_evt_passkey_display_t; @@ -1090,22 +1090,22 @@ typedef struct /**@brief Event structure for @ref BLE_GAP_EVT_KEY_PRESSED. */ typedef struct { - uint8_t kp_not; /**< Keypress notification type, see @ref BLE_GAP_KP_NOT_TYPES. */ + uint8_t kp_not; /**< Keypress notification type, see @ref BLE_GAP_KP_NOT_TYPES. */ } ble_gap_evt_key_pressed_t; /**@brief Event structure for @ref BLE_GAP_EVT_AUTH_KEY_REQUEST. */ typedef struct { - uint8_t key_type; /**< See @ref BLE_GAP_AUTH_KEY_TYPES. */ + uint8_t key_type; /**< See @ref BLE_GAP_AUTH_KEY_TYPES. */ } ble_gap_evt_auth_key_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_LESC_DHKEY_REQUEST. */ typedef struct { - ble_gap_lesc_p256_pk_t *p_pk_peer; /**< LE Secure Connections remote P-256 Public Key. This will point to the application-supplied memory + ble_gap_lesc_p256_pk_t *p_pk_peer; /**< LE Secure Connections remote P-256 Public Key. This will point to the application-supplied memory inside the keyset during the call to @ref sd_ble_gap_sec_params_reply. */ - uint8_t oobd_req :1; /**< LESC OOB data required. A call to @ref sd_ble_gap_lesc_oob_data_set is required to complete the procedure. */ + uint8_t oobd_req : 1; /**< LESC OOB data required. A call to @ref sd_ble_gap_lesc_oob_data_set is required to complete the procedure. */ } ble_gap_evt_lesc_dhkey_request_t; @@ -1114,36 +1114,36 @@ typedef struct */ typedef struct { - uint8_t lv1 : 1; /**< If 1: Level 1 is supported. */ - uint8_t lv2 : 1; /**< If 1: Level 2 is supported. */ - uint8_t lv3 : 1; /**< If 1: Level 3 is supported. */ - uint8_t lv4 : 1; /**< If 1: Level 4 is supported. */ + uint8_t lv1 : 1; /**< If 1: Level 1 is supported. */ + uint8_t lv2 : 1; /**< If 1: Level 2 is supported. */ + uint8_t lv3 : 1; /**< If 1: Level 3 is supported. */ + uint8_t lv4 : 1; /**< If 1: Level 4 is supported. */ } ble_gap_sec_levels_t; /**@brief Encryption Key. */ typedef struct { - ble_gap_enc_info_t enc_info; /**< Encryption Information. */ - ble_gap_master_id_t master_id; /**< Master Identification. */ + ble_gap_enc_info_t enc_info; /**< Encryption Information. */ + ble_gap_master_id_t master_id; /**< Master Identification. */ } ble_gap_enc_key_t; /**@brief Identity Key. */ typedef struct { - ble_gap_irk_t id_info; /**< Identity Resolving Key. */ - ble_gap_addr_t id_addr_info; /**< Identity Address. */ + ble_gap_irk_t id_info; /**< Identity Resolving Key. */ + ble_gap_addr_t id_addr_info; /**< Identity Address. */ } ble_gap_id_key_t; /**@brief Security Keys. */ typedef struct { - ble_gap_enc_key_t *p_enc_key; /**< Encryption Key, or NULL. */ - ble_gap_id_key_t *p_id_key; /**< Identity Key, or NULL. */ - ble_gap_sign_info_t *p_sign_key; /**< Signing Key, or NULL. */ - ble_gap_lesc_p256_pk_t *p_pk; /**< LE Secure Connections P-256 Public Key. When in debug mode the application must use the value defined + ble_gap_enc_key_t *p_enc_key; /**< Encryption Key, or NULL. */ + ble_gap_id_key_t *p_id_key; /**< Identity Key, or NULL. */ + ble_gap_sign_info_t *p_sign_key; /**< Signing Key, or NULL. */ + ble_gap_lesc_p256_pk_t *p_pk; /**< LE Secure Connections P-256 Public Key. When in debug mode the application must use the value defined in the Core Bluetooth Specification v4.2 Vol.3, Part H, Section 2.3.5.6.1 */ } ble_gap_sec_keys_t; @@ -1151,80 +1151,80 @@ typedef struct /**@brief Security key set for both local and peer keys. */ typedef struct { - ble_gap_sec_keys_t keys_own; /**< Keys distributed by the local device. For LE Secure Connections the encryption key will be generated locally and will always be stored if bonding. */ - ble_gap_sec_keys_t keys_peer; /**< Keys distributed by the remote device. For LE Secure Connections, p_enc_key must always be NULL. */ + ble_gap_sec_keys_t keys_own; /**< Keys distributed by the local device. For LE Secure Connections the encryption key will be generated locally and will always be stored if bonding. */ + ble_gap_sec_keys_t keys_peer; /**< Keys distributed by the remote device. For LE Secure Connections, p_enc_key must always be NULL. */ } ble_gap_sec_keyset_t; /**@brief Data Length Update Procedure parameters. */ typedef struct { - uint16_t max_tx_octets; /**< Maximum number of payload octets that a Controller supports for transmission of a single Link Layer Data Channel PDU. */ - uint16_t max_rx_octets; /**< Maximum number of payload octets that a Controller supports for reception of a single Link Layer Data Channel PDU. */ - uint16_t max_tx_time_us; /**< Maximum time, in microseconds, that a Controller supports for transmission of a single Link Layer Data Channel PDU. */ - uint16_t max_rx_time_us; /**< Maximum time, in microseconds, that a Controller supports for reception of a single Link Layer Data Channel PDU. */ + uint16_t max_tx_octets; /**< Maximum number of payload octets that a Controller supports for transmission of a single Link Layer Data Channel PDU. */ + uint16_t max_rx_octets; /**< Maximum number of payload octets that a Controller supports for reception of a single Link Layer Data Channel PDU. */ + uint16_t max_tx_time_us; /**< Maximum time, in microseconds, that a Controller supports for transmission of a single Link Layer Data Channel PDU. */ + uint16_t max_rx_time_us; /**< Maximum time, in microseconds, that a Controller supports for reception of a single Link Layer Data Channel PDU. */ } ble_gap_data_length_params_t; /**@brief Data Length Update Procedure local limitation. */ typedef struct { - uint16_t tx_payload_limited_octets; /**< If > 0, the requested TX packet length is too long by this many octets. */ - uint16_t rx_payload_limited_octets; /**< If > 0, the requested RX packet length is too long by this many octets. */ - uint16_t tx_rx_time_limited_us; /**< If > 0, the requested combination of TX and RX packet lengths is too long by this many microseconds. */ + uint16_t tx_payload_limited_octets; /**< If > 0, the requested TX packet length is too long by this many octets. */ + uint16_t rx_payload_limited_octets; /**< If > 0, the requested RX packet length is too long by this many octets. */ + uint16_t tx_rx_time_limited_us; /**< If > 0, the requested combination of TX and RX packet lengths is too long by this many microseconds. */ } ble_gap_data_length_limitation_t; /**@brief Event structure for @ref BLE_GAP_EVT_AUTH_STATUS. */ typedef struct { - uint8_t auth_status; /**< Authentication status, see @ref BLE_GAP_SEC_STATUS. */ - uint8_t error_src : 2; /**< On error, source that caused the failure, see @ref BLE_GAP_SEC_STATUS_SOURCES. */ - uint8_t bonded : 1; /**< Procedure resulted in a bond. */ - uint8_t lesc : 1; /**< Procedure resulted in a LE Secure Connection. */ - ble_gap_sec_levels_t sm1_levels; /**< Levels supported in Security Mode 1. */ - ble_gap_sec_levels_t sm2_levels; /**< Levels supported in Security Mode 2. */ - ble_gap_sec_kdist_t kdist_own; /**< Bitmap stating which keys were exchanged (distributed) by the local device. If bonding with LE Secure Connections, the enc bit will be always set. */ - ble_gap_sec_kdist_t kdist_peer; /**< Bitmap stating which keys were exchanged (distributed) by the remote device. If bonding with LE Secure Connections, the enc bit will never be set. */ + uint8_t auth_status; /**< Authentication status, see @ref BLE_GAP_SEC_STATUS. */ + uint8_t error_src : 2; /**< On error, source that caused the failure, see @ref BLE_GAP_SEC_STATUS_SOURCES. */ + uint8_t bonded : 1; /**< Procedure resulted in a bond. */ + uint8_t lesc : 1; /**< Procedure resulted in a LE Secure Connection. */ + ble_gap_sec_levels_t sm1_levels; /**< Levels supported in Security Mode 1. */ + ble_gap_sec_levels_t sm2_levels; /**< Levels supported in Security Mode 2. */ + ble_gap_sec_kdist_t kdist_own; /**< Bitmap stating which keys were exchanged (distributed) by the local device. If bonding with LE Secure Connections, the enc bit will be always set. */ + ble_gap_sec_kdist_t kdist_peer; /**< Bitmap stating which keys were exchanged (distributed) by the remote device. If bonding with LE Secure Connections, the enc bit will never be set. */ } ble_gap_evt_auth_status_t; /**@brief Event structure for @ref BLE_GAP_EVT_CONN_SEC_UPDATE. */ typedef struct { - ble_gap_conn_sec_t conn_sec; /**< Connection security level. */ + ble_gap_conn_sec_t conn_sec; /**< Connection security level. */ } ble_gap_evt_conn_sec_update_t; /**@brief Event structure for @ref BLE_GAP_EVT_TIMEOUT. */ typedef struct { - uint8_t src; /**< Source of timeout event, see @ref BLE_GAP_TIMEOUT_SOURCES. */ - union - { - ble_data_t adv_report_buffer; /**< If source is set to @ref BLE_GAP_TIMEOUT_SRC_SCAN, the released + uint8_t src; /**< Source of timeout event, see @ref BLE_GAP_TIMEOUT_SOURCES. */ + union + { + ble_data_t adv_report_buffer; /**< If source is set to @ref BLE_GAP_TIMEOUT_SRC_SCAN, the released scan buffer is contained in this field. */ - } params; /**< Event Parameters. */ + } params; /**< Event Parameters. */ } ble_gap_evt_timeout_t; /**@brief Event structure for @ref BLE_GAP_EVT_RSSI_CHANGED. */ typedef struct { - int8_t rssi; /**< Received Signal Strength Indication in dBm. + int8_t rssi; /**< Received Signal Strength Indication in dBm. @note ERRATA-153 requires the rssi sample to be compensated based on a temperature measurement. */ - uint8_t ch_index; /**< Data Channel Index on which the Signal Strength is measured (0-36). */ + uint8_t ch_index; /**< Data Channel Index on which the Signal Strength is measured (0-36). */ } ble_gap_evt_rssi_changed_t; /**@brief Event structure for @ref BLE_GAP_EVT_ADV_SET_TERMINATED */ typedef struct { - uint8_t reason; /**< Reason for why the advertising set terminated. See + uint8_t reason; /**< Reason for why the advertising set terminated. See @ref BLE_GAP_EVT_ADV_SET_TERMINATED_REASON. */ - uint8_t adv_handle; /**< Advertising handle in which advertising has ended. */ - uint8_t num_completed_adv_events; /**< If @ref ble_gap_adv_params_t::max_adv_evts was not set to 0, + uint8_t adv_handle; /**< Advertising handle in which advertising has ended. */ + uint8_t num_completed_adv_events; /**< If @ref ble_gap_adv_params_t::max_adv_evts was not set to 0, this field indicates the number of completed advertising events. */ - ble_gap_adv_data_t adv_data; /**< Advertising buffers corresponding to the terminated + ble_gap_adv_data_t adv_data; /**< Advertising buffers corresponding to the terminated advertising set. The advertising buffers provided in @ref sd_ble_gap_adv_set_configure are now released. */ } ble_gap_evt_adv_set_terminated_t; @@ -1239,11 +1239,11 @@ typedef struct */ typedef struct { - ble_gap_adv_report_type_t type; /**< Advertising report type. See @ref ble_gap_adv_report_type_t. */ - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr is resolved: + ble_gap_adv_report_type_t type; /**< Advertising report type. See @ref ble_gap_adv_report_type_t. */ + ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr is resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 and the address is the peer's identity address. */ - ble_gap_addr_t direct_addr; /**< Contains the target address of the advertising event if + ble_gap_addr_t direct_addr; /**< Contains the target address of the advertising event if @ref ble_gap_adv_report_type_t::directed is set to 1. If the SoftDevice was able to resolve the address, @ref ble_gap_addr_t::addr_id_peer is set to 1 and the direct_addr @@ -1252,28 +1252,28 @@ typedef struct and the SoftDevice was unable to resolve it, the application may try to resolve this address to find out if the advertising event was directed to us. */ - uint8_t primary_phy; /**< Indicates the PHY on which the primary advertising packet was received. + uint8_t primary_phy; /**< Indicates the PHY on which the primary advertising packet was received. See @ref BLE_GAP_PHYS. */ - uint8_t secondary_phy; /**< Indicates the PHY on which the secondary advertising packet was received. + uint8_t secondary_phy; /**< Indicates the PHY on which the secondary advertising packet was received. See @ref BLE_GAP_PHYS. This field is set to @ref BLE_GAP_PHY_NOT_SET if no packets were received on a secondary advertising channel. */ - int8_t tx_power; /**< TX Power reported by the advertiser in the last packet header received. + int8_t tx_power; /**< TX Power reported by the advertiser in the last packet header received. This field is set to @ref BLE_GAP_POWER_LEVEL_INVALID if the last received packet did not contain the Tx Power field. @note TX Power is only included in extended advertising packets. */ - int8_t rssi; /**< Received Signal Strength Indication in dBm of the last packet received. + int8_t rssi; /**< Received Signal Strength Indication in dBm of the last packet received. @note ERRATA-153 requires the rssi sample to be compensated based on a temperature measurement. */ - uint8_t ch_index; /**< Channel Index on which the last advertising packet is received (0-39). */ - uint8_t set_id; /**< Set ID of the received advertising data. Set ID is not present + uint8_t ch_index; /**< Channel Index on which the last advertising packet is received (0-39). */ + uint8_t set_id; /**< Set ID of the received advertising data. Set ID is not present if set to @ref BLE_GAP_ADV_REPORT_SET_ID_NOT_AVAILABLE. */ - uint16_t data_id:12; /**< The advertising data ID of the received advertising data. Data ID + uint16_t data_id : 12; /**< The advertising data ID of the received advertising data. Data ID is not present if @ref ble_gap_evt_adv_report_t::set_id is set to @ref BLE_GAP_ADV_REPORT_SET_ID_NOT_AVAILABLE. */ - ble_data_t data; /**< Received advertising or scan response data. If + ble_data_t data; /**< Received advertising or scan response data. If @ref ble_gap_adv_report_type_t::status is not set to @ref BLE_GAP_ADV_DATA_STATUS_INCOMPLETE_MORE_DATA, the data buffer provided in @ref sd_ble_gap_scan_start is now released. */ - ble_gap_aux_pointer_t aux_pointer; /**< The offset and PHY of the next advertising packet in this extended advertising + ble_gap_aux_pointer_t aux_pointer; /**< The offset and PHY of the next advertising packet in this extended advertising event. @note This field is only set if @ref ble_gap_adv_report_type_t::status is set to @ref BLE_GAP_ADV_DATA_STATUS_INCOMPLETE_MORE_DATA. */ } ble_gap_evt_adv_report_t; @@ -1282,27 +1282,27 @@ typedef struct /**@brief Event structure for @ref BLE_GAP_EVT_SEC_REQUEST. */ typedef struct { - uint8_t bond : 1; /**< Perform bonding. */ - uint8_t mitm : 1; /**< Man In The Middle protection requested. */ - uint8_t lesc : 1; /**< LE Secure Connections requested. */ - uint8_t keypress : 1; /**< Generation of keypress notifications requested. */ + uint8_t bond : 1; /**< Perform bonding. */ + uint8_t mitm : 1; /**< Man In The Middle protection requested. */ + uint8_t lesc : 1; /**< LE Secure Connections requested. */ + uint8_t keypress : 1; /**< Generation of keypress notifications requested. */ } ble_gap_evt_sec_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST. */ typedef struct { - ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ + ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ } ble_gap_evt_conn_param_update_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_SCAN_REQ_REPORT. */ typedef struct { - uint8_t adv_handle; /**< Advertising handle for the advertising set which received the Scan Request */ - int8_t rssi; /**< Received Signal Strength Indication in dBm. + uint8_t adv_handle; /**< Advertising handle for the advertising set which received the Scan Request */ + int8_t rssi; /**< Received Signal Strength Indication in dBm. @note ERRATA-153 requires the rssi sample to be compensated based on a temperature measurement. */ - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 + ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 and the address is the device's identity address. */ } ble_gap_evt_scan_req_report_t; @@ -1310,20 +1310,20 @@ typedef struct /**@brief Event structure for @ref BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST. */ typedef struct { - ble_gap_data_length_params_t peer_params; /**< Peer data length parameters. */ + ble_gap_data_length_params_t peer_params; /**< Peer data length parameters. */ } ble_gap_evt_data_length_update_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_DATA_LENGTH_UPDATE. */ typedef struct { - ble_gap_data_length_params_t effective_params; /**< The effective data length parameters. */ + ble_gap_data_length_params_t effective_params; /**< The effective data length parameters. */ } ble_gap_evt_data_length_update_t; /**@brief Event structure for @ref BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT. */ typedef struct { - int8_t channel_energy[BLE_GAP_CHANNEL_COUNT]; /**< The measured energy on the Bluetooth Low Energy + int8_t channel_energy[BLE_GAP_CHANNEL_COUNT]; /**< The measured energy on the Bluetooth Low Energy channels, in dBm, indexed by Channel Index. If no measurement is available for the given channel, channel_energy is set to @ref BLE_GAP_POWER_LEVEL_INVALID. */ @@ -1332,33 +1332,33 @@ typedef struct /**@brief GAP event structure. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which event occurred. */ - union /**< union alternative identified by evt_id in enclosing struct. */ - { - ble_gap_evt_connected_t connected; /**< Connected Event Parameters. */ - ble_gap_evt_disconnected_t disconnected; /**< Disconnected Event Parameters. */ - ble_gap_evt_conn_param_update_t conn_param_update; /**< Connection Parameter Update Parameters. */ - ble_gap_evt_sec_params_request_t sec_params_request; /**< Security Parameters Request Event Parameters. */ - ble_gap_evt_sec_info_request_t sec_info_request; /**< Security Information Request Event Parameters. */ - ble_gap_evt_passkey_display_t passkey_display; /**< Passkey Display Event Parameters. */ - ble_gap_evt_key_pressed_t key_pressed; /**< Key Pressed Event Parameters. */ - ble_gap_evt_auth_key_request_t auth_key_request; /**< Authentication Key Request Event Parameters. */ - ble_gap_evt_lesc_dhkey_request_t lesc_dhkey_request; /**< LE Secure Connections DHKey calculation request. */ - ble_gap_evt_auth_status_t auth_status; /**< Authentication Status Event Parameters. */ - ble_gap_evt_conn_sec_update_t conn_sec_update; /**< Connection Security Update Event Parameters. */ - ble_gap_evt_timeout_t timeout; /**< Timeout Event Parameters. */ - ble_gap_evt_rssi_changed_t rssi_changed; /**< RSSI Event Parameters. */ - ble_gap_evt_adv_report_t adv_report; /**< Advertising Report Event Parameters. */ - ble_gap_evt_adv_set_terminated_t adv_set_terminated; /**< Advertising Set Terminated Event Parameters. */ - ble_gap_evt_sec_request_t sec_request; /**< Security Request Event Parameters. */ - ble_gap_evt_conn_param_update_request_t conn_param_update_request; /**< Connection Parameter Update Parameters. */ - ble_gap_evt_scan_req_report_t scan_req_report; /**< Scan Request Report Parameters. */ - ble_gap_evt_phy_update_request_t phy_update_request; /**< PHY Update Request Event Parameters. */ - ble_gap_evt_phy_update_t phy_update; /**< PHY Update Parameters. */ - ble_gap_evt_data_length_update_request_t data_length_update_request; /**< Data Length Update Request Event Parameters. */ - ble_gap_evt_data_length_update_t data_length_update; /**< Data Length Update Event Parameters. */ - ble_gap_evt_qos_channel_survey_report_t qos_channel_survey_report; /**< Quality of Service (QoS) Channel Survey Report Parameters. */ - } params; /**< Event Parameters. */ + uint16_t conn_handle; /**< Connection Handle on which event occurred. */ + union /**< union alternative identified by evt_id in enclosing struct. */ + { + ble_gap_evt_connected_t connected; /**< Connected Event Parameters. */ + ble_gap_evt_disconnected_t disconnected; /**< Disconnected Event Parameters. */ + ble_gap_evt_conn_param_update_t conn_param_update; /**< Connection Parameter Update Parameters. */ + ble_gap_evt_sec_params_request_t sec_params_request; /**< Security Parameters Request Event Parameters. */ + ble_gap_evt_sec_info_request_t sec_info_request; /**< Security Information Request Event Parameters. */ + ble_gap_evt_passkey_display_t passkey_display; /**< Passkey Display Event Parameters. */ + ble_gap_evt_key_pressed_t key_pressed; /**< Key Pressed Event Parameters. */ + ble_gap_evt_auth_key_request_t auth_key_request; /**< Authentication Key Request Event Parameters. */ + ble_gap_evt_lesc_dhkey_request_t lesc_dhkey_request; /**< LE Secure Connections DHKey calculation request. */ + ble_gap_evt_auth_status_t auth_status; /**< Authentication Status Event Parameters. */ + ble_gap_evt_conn_sec_update_t conn_sec_update; /**< Connection Security Update Event Parameters. */ + ble_gap_evt_timeout_t timeout; /**< Timeout Event Parameters. */ + ble_gap_evt_rssi_changed_t rssi_changed; /**< RSSI Event Parameters. */ + ble_gap_evt_adv_report_t adv_report; /**< Advertising Report Event Parameters. */ + ble_gap_evt_adv_set_terminated_t adv_set_terminated; /**< Advertising Set Terminated Event Parameters. */ + ble_gap_evt_sec_request_t sec_request; /**< Security Request Event Parameters. */ + ble_gap_evt_conn_param_update_request_t conn_param_update_request; /**< Connection Parameter Update Parameters. */ + ble_gap_evt_scan_req_report_t scan_req_report; /**< Scan Request Report Parameters. */ + ble_gap_evt_phy_update_request_t phy_update_request; /**< PHY Update Request Event Parameters. */ + ble_gap_evt_phy_update_t phy_update; /**< PHY Update Parameters. */ + ble_gap_evt_data_length_update_request_t data_length_update_request; /**< Data Length Update Request Event Parameters. */ + ble_gap_evt_data_length_update_t data_length_update; /**< Data Length Update Event Parameters. */ + ble_gap_evt_qos_channel_survey_report_t qos_channel_survey_report; /**< Quality of Service (QoS) Channel Survey Report Parameters. */ + } params; /**< Event Parameters. */ } ble_gap_evt_t; @@ -1372,9 +1372,9 @@ typedef struct */ typedef struct { - uint8_t conn_count; /**< The number of concurrent connections the application can create with this configuration. + uint8_t conn_count; /**< The number of concurrent connections the application can create with this configuration. The default and minimum value is @ref BLE_GAP_CONN_COUNT_DEFAULT. */ - uint16_t event_length; /**< The time set aside for this connection on every connection interval in 1.25 ms units. + uint16_t event_length; /**< The time set aside for this connection on every connection interval in 1.25 ms units. The default value is @ref BLE_GAP_EVENT_LENGTH_DEFAULT, the minimum value is @ref BLE_GAP_EVENT_LENGTH_MIN. The event length and the connection interval are the primary parameters for setting the throughput of a connection. @@ -1396,11 +1396,11 @@ typedef struct */ typedef struct { - uint8_t adv_set_count; /**< Maximum number of advertising sets. Default value is @ref BLE_GAP_ADV_SET_COUNT_DEFAULT. */ - uint8_t periph_role_count; /**< Maximum number of connections concurrently acting as a peripheral. Default value is @ref BLE_GAP_ROLE_COUNT_PERIPH_DEFAULT. */ - uint8_t central_role_count; /**< Maximum number of connections concurrently acting as a central. Default value is @ref BLE_GAP_ROLE_COUNT_CENTRAL_DEFAULT. */ - uint8_t central_sec_count; /**< Number of SMP instances shared between all connections acting as a central. Default value is @ref BLE_GAP_ROLE_COUNT_CENTRAL_SEC_DEFAULT. */ - uint8_t qos_channel_survey_role_available:1; /**< If set, the Quality of Service (QoS) channel survey module is available to the + uint8_t adv_set_count; /**< Maximum number of advertising sets. Default value is @ref BLE_GAP_ADV_SET_COUNT_DEFAULT. */ + uint8_t periph_role_count; /**< Maximum number of connections concurrently acting as a peripheral. Default value is @ref BLE_GAP_ROLE_COUNT_PERIPH_DEFAULT. */ + uint8_t central_role_count; /**< Maximum number of connections concurrently acting as a central. Default value is @ref BLE_GAP_ROLE_COUNT_CENTRAL_DEFAULT. */ + uint8_t central_sec_count; /**< Number of SMP instances shared between all connections acting as a central. Default value is @ref BLE_GAP_ROLE_COUNT_CENTRAL_SEC_DEFAULT. */ + uint8_t qos_channel_survey_role_available : 1; /**< If set, the Quality of Service (QoS) channel survey module is available to the application using @ref sd_ble_gap_qos_channel_survey_start. */ } ble_gap_cfg_role_count_t; @@ -1435,19 +1435,19 @@ typedef struct */ typedef struct { - ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ - uint8_t vloc:2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ - uint8_t *p_value; /**< Pointer to where the value (device name) is stored or will be stored. */ - uint16_t current_len; /**< Current length in bytes of the memory pointed to by p_value.*/ - uint16_t max_len; /**< Maximum length in bytes of the memory pointed to by p_value.*/ + ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ + uint8_t vloc : 2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ + uint8_t *p_value; /**< Pointer to where the value (device name) is stored or will be stored. */ + uint16_t current_len; /**< Current length in bytes of the memory pointed to by p_value.*/ + uint16_t max_len; /**< Maximum length in bytes of the memory pointed to by p_value.*/ } ble_gap_cfg_device_name_t; /**@brief Configuration structure for GAP configurations. */ typedef union { - ble_gap_cfg_role_count_t role_count_cfg; /**< Role count configuration, cfg_id is @ref BLE_GAP_CFG_ROLE_COUNT. */ - ble_gap_cfg_device_name_t device_name_cfg; /**< Device name configuration, cfg_id is @ref BLE_GAP_CFG_DEVICE_NAME. */ + ble_gap_cfg_role_count_t role_count_cfg; /**< Role count configuration, cfg_id is @ref BLE_GAP_CFG_ROLE_COUNT. */ + ble_gap_cfg_device_name_t device_name_cfg; /**< Device name configuration, cfg_id is @ref BLE_GAP_CFG_DEVICE_NAME. */ } ble_gap_cfg_t; @@ -1476,8 +1476,8 @@ typedef union */ typedef struct { - uint16_t conn_handle; /**< Connection Handle (only applicable for get) */ - uint8_t ch_map[5]; /**< Channel Map (37-bit). */ + uint16_t conn_handle; /**< Connection Handle (only applicable for get) */ + uint8_t ch_map[5]; /**< Channel Map (37-bit). */ } ble_gap_opt_ch_map_t; @@ -1505,9 +1505,9 @@ typedef struct */ typedef struct { - uint16_t conn_handle; /**< Connection Handle */ - uint16_t requested_latency; /**< Requested local connection latency. */ - uint16_t * p_actual_latency; /**< Pointer to storage for the actual local connection latency (can be set to NULL to skip return value). */ + uint16_t conn_handle; /**< Connection Handle */ + uint16_t requested_latency; /**< Requested local connection latency. */ + uint16_t *p_actual_latency; /**< Pointer to storage for the actual local connection latency (can be set to NULL to skip return value). */ } ble_gap_opt_local_conn_latency_t; /**@brief Disable slave latency @@ -1524,8 +1524,8 @@ typedef struct */ typedef struct { - uint16_t conn_handle; /**< Connection Handle */ - uint8_t disable : 1; /**< Set to 1 to disable slave latency. Set to 0 enable it again.*/ + uint16_t conn_handle; /**< Connection Handle */ + uint8_t disable : 1; /**< Set to 1 to disable slave latency. Set to 0 enable it again.*/ } ble_gap_opt_slave_latency_disable_t; /**@brief Passkey Option. @@ -1541,7 +1541,7 @@ typedef struct */ typedef struct { - uint8_t const * p_passkey; /**< Pointer to 6-digit ASCII string (digit 0..9 only, no NULL termination) passkey to be used during pairing. If this is NULL, the SoftDevice will generate a random passkey if required.*/ + uint8_t const *p_passkey; /**< Pointer to 6-digit ASCII string (digit 0..9 only, no NULL termination) passkey to be used during pairing. If this is NULL, the SoftDevice will generate a random passkey if required.*/ } ble_gap_opt_passkey_t; @@ -1562,7 +1562,7 @@ typedef struct */ typedef struct { - uint8_t enable : 1; /**< Enable compatibility mode 1.*/ + uint8_t enable : 1; /**< Enable compatibility mode 1.*/ } ble_gap_opt_compat_mode_1_t; @@ -1587,19 +1587,19 @@ typedef struct */ typedef struct { - uint16_t conn_handle; /**< Connection Handle */ - uint16_t auth_payload_timeout; /**< Requested timeout in 10 ms unit, see @ref BLE_GAP_AUTH_PAYLOAD_TIMEOUT. */ + uint16_t conn_handle; /**< Connection Handle */ + uint16_t auth_payload_timeout; /**< Requested timeout in 10 ms unit, see @ref BLE_GAP_AUTH_PAYLOAD_TIMEOUT. */ } ble_gap_opt_auth_payload_timeout_t; /**@brief Option structure for GAP options. */ typedef union { - ble_gap_opt_ch_map_t ch_map; /**< Parameters for the Channel Map option. */ - ble_gap_opt_local_conn_latency_t local_conn_latency; /**< Parameters for the Local connection latency option */ - ble_gap_opt_passkey_t passkey; /**< Parameters for the Passkey option.*/ - ble_gap_opt_compat_mode_1_t compat_mode_1; /**< Parameters for the compatibility mode 1 option.*/ - ble_gap_opt_auth_payload_timeout_t auth_payload_timeout; /**< Parameters for the authenticated payload timeout option.*/ - ble_gap_opt_slave_latency_disable_t slave_latency_disable; /**< Parameters for the Disable slave latency option */ + ble_gap_opt_ch_map_t ch_map; /**< Parameters for the Channel Map option. */ + ble_gap_opt_local_conn_latency_t local_conn_latency; /**< Parameters for the Local connection latency option */ + ble_gap_opt_passkey_t passkey; /**< Parameters for the Passkey option.*/ + ble_gap_opt_compat_mode_1_t compat_mode_1; /**< Parameters for the compatibility mode 1 option.*/ + ble_gap_opt_auth_payload_timeout_t auth_payload_timeout; /**< Parameters for the authenticated payload timeout option.*/ + ble_gap_opt_slave_latency_disable_t slave_latency_disable; /**< Parameters for the Disable slave latency option */ } ble_gap_opt_t; /**@} */ @@ -1648,7 +1648,7 @@ SVCALL(SD_BLE_GAP_ADDR_SET, uint32_t, sd_ble_gap_addr_set(ble_gap_addr_t const * * @retval ::NRF_SUCCESS Address successfully retrieved. * @retval ::NRF_ERROR_INVALID_ADDR Invalid or NULL pointer supplied. */ -SVCALL(SD_BLE_GAP_ADDR_GET, uint32_t, sd_ble_gap_addr_get(ble_gap_addr_t *p_addr)); +SVCALL(SD_BLE_GAP_ADDR_GET, uint32_t, sd_ble_gap_addr_get(ble_gap_addr_t * p_addr)); /**@brief Get the Bluetooth device address used by the advertiser. @@ -1667,7 +1667,7 @@ SVCALL(SD_BLE_GAP_ADDR_GET, uint32_t, sd_ble_gap_addr_get(ble_gap_addr_t *p_addr * @retval ::BLE_ERROR_INVALID_ADV_HANDLE The provided advertising handle was not found. * @retval ::NRF_ERROR_INVALID_STATE The advertising set is currently not advertising. */ -SVCALL(SD_BLE_GAP_ADV_ADDR_GET, uint32_t, sd_ble_gap_adv_addr_get(uint8_t adv_handle, ble_gap_addr_t *p_addr)); +SVCALL(SD_BLE_GAP_ADV_ADDR_GET, uint32_t, sd_ble_gap_adv_addr_get(uint8_t adv_handle, ble_gap_addr_t * p_addr)); /**@brief Set the active whitelist in the SoftDevice. @@ -1693,7 +1693,7 @@ SVCALL(SD_BLE_GAP_ADV_ADDR_GET, uint32_t, sd_ble_gap_adv_addr_get(uint8_t adv_ha * @retval ::NRF_ERROR_DATA_SIZE The given whitelist size is invalid (zero or too large); this can only return when * pp_wl_addrs is not NULL. */ -SVCALL(SD_BLE_GAP_WHITELIST_SET, uint32_t, sd_ble_gap_whitelist_set(ble_gap_addr_t const * const * pp_wl_addrs, uint8_t len)); +SVCALL(SD_BLE_GAP_WHITELIST_SET, uint32_t, sd_ble_gap_whitelist_set(ble_gap_addr_t const *const *pp_wl_addrs, uint8_t len)); /**@brief Set device identity list. @@ -1724,7 +1724,7 @@ SVCALL(SD_BLE_GAP_WHITELIST_SET, uint32_t, sd_ble_gap_whitelist_set(ble_gap_addr * @retval ::NRF_ERROR_DATA_SIZE The given device identity list size invalid (zero or too large); this can * only return when pp_id_keys is not NULL. */ -SVCALL(SD_BLE_GAP_DEVICE_IDENTITIES_SET, uint32_t, sd_ble_gap_device_identities_set(ble_gap_id_key_t const * const * pp_id_keys, ble_gap_irk_t const * const * pp_local_irks, uint8_t len)); +SVCALL(SD_BLE_GAP_DEVICE_IDENTITIES_SET, uint32_t, sd_ble_gap_device_identities_set(ble_gap_id_key_t const *const *pp_id_keys, ble_gap_irk_t const *const *pp_local_irks, uint8_t len)); /**@brief Set privacy settings. @@ -1762,7 +1762,7 @@ SVCALL(SD_BLE_GAP_PRIVACY_SET, uint32_t, sd_ble_gap_privacy_set(ble_gap_privacy_ * @retval ::NRF_ERROR_INVALID_ADDR The pointer given for returning the privacy settings may be NULL or invalid. * Otherwise, the p_device_irk pointer in privacy parameter is an invalid pointer. */ -SVCALL(SD_BLE_GAP_PRIVACY_GET, uint32_t, sd_ble_gap_privacy_get(ble_gap_privacy_params_t *p_privacy_params)); +SVCALL(SD_BLE_GAP_PRIVACY_GET, uint32_t, sd_ble_gap_privacy_get(ble_gap_privacy_params_t * p_privacy_params)); /**@brief Configure an advertising set. Set, clear or update advertising and scan response data. @@ -1809,7 +1809,7 @@ SVCALL(SD_BLE_GAP_PRIVACY_GET, uint32_t, sd_ble_gap_privacy_get(ble_gap_privacy_ * existing advertising handle instead. * @retval ::BLE_ERROR_GAP_UUID_LIST_MISMATCH Invalid UUID list supplied. */ -SVCALL(SD_BLE_GAP_ADV_SET_CONFIGURE, uint32_t, sd_ble_gap_adv_set_configure(uint8_t *p_adv_handle, ble_gap_adv_data_t const *p_adv_data, ble_gap_adv_params_t const *p_adv_params)); +SVCALL(SD_BLE_GAP_ADV_SET_CONFIGURE, uint32_t, sd_ble_gap_adv_set_configure(uint8_t * p_adv_handle, ble_gap_adv_data_t const *p_adv_data, ble_gap_adv_params_t const *p_adv_params)); /**@brief Start advertising (GAP Discoverable, Connectable modes, Broadcast Procedure). @@ -1975,7 +1975,7 @@ SVCALL(SD_BLE_GAP_APPEARANCE_SET, uint32_t, sd_ble_gap_appearance_set(uint16_t a * @retval ::NRF_SUCCESS Appearance value retrieved successfully. * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. */ -SVCALL(SD_BLE_GAP_APPEARANCE_GET, uint32_t, sd_ble_gap_appearance_get(uint16_t *p_appearance)); +SVCALL(SD_BLE_GAP_APPEARANCE_GET, uint32_t, sd_ble_gap_appearance_get(uint16_t * p_appearance)); /**@brief Set GAP Peripheral Preferred Connection Parameters. @@ -1996,7 +1996,7 @@ SVCALL(SD_BLE_GAP_PPCP_SET, uint32_t, sd_ble_gap_ppcp_set(ble_gap_conn_params_t * @retval ::NRF_SUCCESS Peripheral Preferred Connection Parameters retrieved successfully. * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. */ -SVCALL(SD_BLE_GAP_PPCP_GET, uint32_t, sd_ble_gap_ppcp_get(ble_gap_conn_params_t *p_conn_params)); +SVCALL(SD_BLE_GAP_PPCP_GET, uint32_t, sd_ble_gap_ppcp_get(ble_gap_conn_params_t * p_conn_params)); /**@brief Set GAP device name. @@ -2031,7 +2031,7 @@ SVCALL(SD_BLE_GAP_DEVICE_NAME_SET, uint32_t, sd_ble_gap_device_name_set(ble_gap_ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied. */ -SVCALL(SD_BLE_GAP_DEVICE_NAME_GET, uint32_t, sd_ble_gap_device_name_get(uint8_t *p_dev_name, uint16_t *p_len)); +SVCALL(SD_BLE_GAP_DEVICE_NAME_GET, uint32_t, sd_ble_gap_device_name_get(uint8_t * p_dev_name, uint16_t * p_len)); /**@brief Initiate the GAP Authentication procedure. @@ -2255,7 +2255,7 @@ SVCALL(SD_BLE_GAP_KEYPRESS_NOTIFY, uint32_t, sd_ble_gap_keypress_notify(uint16_t * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. */ -SVCALL(SD_BLE_GAP_LESC_OOB_DATA_GET, uint32_t, sd_ble_gap_lesc_oob_data_get(uint16_t conn_handle, ble_gap_lesc_p256_pk_t const *p_pk_own, ble_gap_lesc_oob_data_t *p_oobd_own)); +SVCALL(SD_BLE_GAP_LESC_OOB_DATA_GET, uint32_t, sd_ble_gap_lesc_oob_data_get(uint16_t conn_handle, ble_gap_lesc_p256_pk_t const *p_pk_own, ble_gap_lesc_oob_data_t * p_oobd_own)); /**@brief Provide the OOB data sent/received out of band. * @@ -2354,7 +2354,7 @@ SVCALL(SD_BLE_GAP_SEC_INFO_REPLY, uint32_t, sd_ble_gap_sec_info_reply(uint16_t c * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. */ -SVCALL(SD_BLE_GAP_CONN_SEC_GET, uint32_t, sd_ble_gap_conn_sec_get(uint16_t conn_handle, ble_gap_conn_sec_t *p_conn_sec)); +SVCALL(SD_BLE_GAP_CONN_SEC_GET, uint32_t, sd_ble_gap_conn_sec_get(uint16_t conn_handle, ble_gap_conn_sec_t * p_conn_sec)); /**@brief Start reporting the received signal strength to the application. @@ -2421,7 +2421,7 @@ SVCALL(SD_BLE_GAP_RSSI_STOP, uint32_t, sd_ble_gap_rssi_stop(uint16_t conn_handle * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. * @retval ::NRF_ERROR_INVALID_STATE RSSI reporting is not ongoing. */ -SVCALL(SD_BLE_GAP_RSSI_GET, uint32_t, sd_ble_gap_rssi_get(uint16_t conn_handle, int8_t *p_rssi, uint8_t *p_ch_index)); +SVCALL(SD_BLE_GAP_RSSI_GET, uint32_t, sd_ble_gap_rssi_get(uint16_t conn_handle, int8_t * p_rssi, uint8_t * p_ch_index)); /**@brief Start or continue scanning (GAP Discovery procedure, Observer Procedure). @@ -2474,7 +2474,7 @@ SVCALL(SD_BLE_GAP_RSSI_GET, uint32_t, sd_ble_gap_rssi_get(uint16_t conn_handle, * @retval ::NRF_ERROR_RESOURCES Not enough BLE role slots available. * Stop one or more currently active roles (Central, Peripheral or Broadcaster) and try again */ -SVCALL(SD_BLE_GAP_SCAN_START, uint32_t, sd_ble_gap_scan_start(ble_gap_scan_params_t const *p_scan_params, ble_data_t const * p_adv_report_buffer)); +SVCALL(SD_BLE_GAP_SCAN_START, uint32_t, sd_ble_gap_scan_start(ble_gap_scan_params_t const *p_scan_params, ble_data_t const *p_adv_report_buffer)); /**@brief Stop scanning (GAP Discovery procedure, Observer Procedure). @@ -2637,7 +2637,7 @@ SVCALL(SD_BLE_GAP_PHY_UPDATE, uint32_t, sd_ble_gap_phy_update(uint16_t conn_hand * @retval ::NRF_ERROR_BUSY Peer has already initiated a Data Length Update Procedure. Process the * pending @ref BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST event to respond. */ -SVCALL(SD_BLE_GAP_DATA_LENGTH_UPDATE, uint32_t, sd_ble_gap_data_length_update(uint16_t conn_handle, ble_gap_data_length_params_t const *p_dl_params, ble_gap_data_length_limitation_t *p_dl_limitation)); +SVCALL(SD_BLE_GAP_DATA_LENGTH_UPDATE, uint32_t, sd_ble_gap_data_length_update(uint16_t conn_handle, ble_gap_data_length_params_t const *p_dl_params, ble_gap_data_length_limitation_t * p_dl_limitation)); /**@brief Start the Quality of Service (QoS) channel survey module. * diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gatt.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gatt.h index 9cb577cc85..45b78a75ed 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gatt.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gatt.h @@ -189,7 +189,7 @@ extern "C" { */ typedef struct { - uint16_t att_mtu; /**< Maximum size of ATT packet the SoftDevice can send or receive. + uint16_t att_mtu; /**< Maximum size of ATT packet the SoftDevice can send or receive. The default and minimum value is @ref BLE_GATT_ATT_MTU_DEFAULT. @mscs @mmsc{@ref BLE_GATTC_MTU_EXCHANGE} @@ -201,22 +201,22 @@ typedef struct /**@brief GATT Characteristic Properties. */ typedef struct { - /* Standard properties */ - uint8_t broadcast :1; /**< Broadcasting of the value permitted. */ - uint8_t read :1; /**< Reading the value permitted. */ - uint8_t write_wo_resp :1; /**< Writing the value with Write Command permitted. */ - uint8_t write :1; /**< Writing the value with Write Request permitted. */ - uint8_t notify :1; /**< Notification of the value permitted. */ - uint8_t indicate :1; /**< Indications of the value permitted. */ - uint8_t auth_signed_wr :1; /**< Writing the value with Signed Write Command permitted. */ + /* Standard properties */ + uint8_t broadcast : 1;/**< Broadcasting of the value permitted. */ + uint8_t read : 1;/**< Reading the value permitted. */ + uint8_t write_wo_resp : 1;/**< Writing the value with Write Command permitted. */ + uint8_t write : 1;/**< Writing the value with Write Request permitted. */ + uint8_t notify : 1;/**< Notification of the value permitted. */ + uint8_t indicate : 1;/**< Indications of the value permitted. */ + uint8_t auth_signed_wr : 1;/**< Writing the value with Signed Write Command permitted. */ } ble_gatt_char_props_t; /**@brief GATT Characteristic Extended Properties. */ typedef struct { - /* Extended properties */ - uint8_t reliable_wr :1; /**< Writing the value with Queued Write operations permitted. */ - uint8_t wr_aux :1; /**< Writing the Characteristic User Description descriptor permitted. */ + /* Extended properties */ + uint8_t reliable_wr : 1;/**< Writing the value with Queued Write operations permitted. */ + uint8_t wr_aux : 1;/**< Writing the Characteristic User Description descriptor permitted. */ } ble_gatt_char_ext_props_t; /** @} */ diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gattc.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gattc.h index 7fb3920244..c4c8322ca1 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gattc.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gattc.h @@ -64,17 +64,17 @@ extern "C" { /**@brief GATTC API SVC numbers. */ enum BLE_GATTC_SVCS { - SD_BLE_GATTC_PRIMARY_SERVICES_DISCOVER = BLE_GATTC_SVC_BASE, /**< Primary Service Discovery. */ - SD_BLE_GATTC_RELATIONSHIPS_DISCOVER, /**< Relationship Discovery. */ - SD_BLE_GATTC_CHARACTERISTICS_DISCOVER, /**< Characteristic Discovery. */ - SD_BLE_GATTC_DESCRIPTORS_DISCOVER, /**< Characteristic Descriptor Discovery. */ - SD_BLE_GATTC_ATTR_INFO_DISCOVER, /**< Attribute Information Discovery. */ - SD_BLE_GATTC_CHAR_VALUE_BY_UUID_READ, /**< Read Characteristic Value by UUID. */ - SD_BLE_GATTC_READ, /**< Generic read. */ - SD_BLE_GATTC_CHAR_VALUES_READ, /**< Read multiple Characteristic Values. */ - SD_BLE_GATTC_WRITE, /**< Generic write. */ - SD_BLE_GATTC_HV_CONFIRM, /**< Handle Value Confirmation. */ - SD_BLE_GATTC_EXCHANGE_MTU_REQUEST, /**< Exchange MTU Request. */ + SD_BLE_GATTC_PRIMARY_SERVICES_DISCOVER = BLE_GATTC_SVC_BASE, /**< Primary Service Discovery. */ + SD_BLE_GATTC_RELATIONSHIPS_DISCOVER, /**< Relationship Discovery. */ + SD_BLE_GATTC_CHARACTERISTICS_DISCOVER, /**< Characteristic Discovery. */ + SD_BLE_GATTC_DESCRIPTORS_DISCOVER, /**< Characteristic Descriptor Discovery. */ + SD_BLE_GATTC_ATTR_INFO_DISCOVER, /**< Attribute Information Discovery. */ + SD_BLE_GATTC_CHAR_VALUE_BY_UUID_READ, /**< Read Characteristic Value by UUID. */ + SD_BLE_GATTC_READ, /**< Generic read. */ + SD_BLE_GATTC_CHAR_VALUES_READ, /**< Read multiple Characteristic Values. */ + SD_BLE_GATTC_WRITE, /**< Generic write. */ + SD_BLE_GATTC_HV_CONFIRM, /**< Handle Value Confirmation. */ + SD_BLE_GATTC_EXCHANGE_MTU_REQUEST, /**< Exchange MTU Request. */ }; /** @@ -82,19 +82,19 @@ enum BLE_GATTC_SVCS */ enum BLE_GATTC_EVTS { - BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP = BLE_GATTC_EVT_BASE, /**< Primary Service Discovery Response event. \n See @ref ble_gattc_evt_prim_srvc_disc_rsp_t. */ - BLE_GATTC_EVT_REL_DISC_RSP, /**< Relationship Discovery Response event. \n See @ref ble_gattc_evt_rel_disc_rsp_t. */ - BLE_GATTC_EVT_CHAR_DISC_RSP, /**< Characteristic Discovery Response event. \n See @ref ble_gattc_evt_char_disc_rsp_t. */ - BLE_GATTC_EVT_DESC_DISC_RSP, /**< Descriptor Discovery Response event. \n See @ref ble_gattc_evt_desc_disc_rsp_t. */ - BLE_GATTC_EVT_ATTR_INFO_DISC_RSP, /**< Attribute Information Response event. \n See @ref ble_gattc_evt_attr_info_disc_rsp_t. */ - BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP, /**< Read By UUID Response event. \n See @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t. */ - BLE_GATTC_EVT_READ_RSP, /**< Read Response event. \n See @ref ble_gattc_evt_read_rsp_t. */ - BLE_GATTC_EVT_CHAR_VALS_READ_RSP, /**< Read multiple Response event. \n See @ref ble_gattc_evt_char_vals_read_rsp_t. */ - BLE_GATTC_EVT_WRITE_RSP, /**< Write Response event. \n See @ref ble_gattc_evt_write_rsp_t. */ - BLE_GATTC_EVT_HVX, /**< Handle Value Notification or Indication event. \n Confirm indication with @ref sd_ble_gattc_hv_confirm. \n See @ref ble_gattc_evt_hvx_t. */ - BLE_GATTC_EVT_EXCHANGE_MTU_RSP, /**< Exchange MTU Response event. \n See @ref ble_gattc_evt_exchange_mtu_rsp_t. */ - BLE_GATTC_EVT_TIMEOUT, /**< Timeout event. \n See @ref ble_gattc_evt_timeout_t. */ - BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE /**< Write without Response transmission complete. \n See @ref ble_gattc_evt_write_cmd_tx_complete_t. */ + BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP = BLE_GATTC_EVT_BASE, /**< Primary Service Discovery Response event. \n See @ref ble_gattc_evt_prim_srvc_disc_rsp_t. */ + BLE_GATTC_EVT_REL_DISC_RSP, /**< Relationship Discovery Response event. \n See @ref ble_gattc_evt_rel_disc_rsp_t. */ + BLE_GATTC_EVT_CHAR_DISC_RSP, /**< Characteristic Discovery Response event. \n See @ref ble_gattc_evt_char_disc_rsp_t. */ + BLE_GATTC_EVT_DESC_DISC_RSP, /**< Descriptor Discovery Response event. \n See @ref ble_gattc_evt_desc_disc_rsp_t. */ + BLE_GATTC_EVT_ATTR_INFO_DISC_RSP, /**< Attribute Information Response event. \n See @ref ble_gattc_evt_attr_info_disc_rsp_t. */ + BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP, /**< Read By UUID Response event. \n See @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t. */ + BLE_GATTC_EVT_READ_RSP, /**< Read Response event. \n See @ref ble_gattc_evt_read_rsp_t. */ + BLE_GATTC_EVT_CHAR_VALS_READ_RSP, /**< Read multiple Response event. \n See @ref ble_gattc_evt_char_vals_read_rsp_t. */ + BLE_GATTC_EVT_WRITE_RSP, /**< Write Response event. \n See @ref ble_gattc_evt_write_rsp_t. */ + BLE_GATTC_EVT_HVX, /**< Handle Value Notification or Indication event. \n Confirm indication with @ref sd_ble_gattc_hv_confirm. \n See @ref ble_gattc_evt_hvx_t. */ + BLE_GATTC_EVT_EXCHANGE_MTU_RSP, /**< Exchange MTU Response event. \n See @ref ble_gattc_evt_exchange_mtu_rsp_t. */ + BLE_GATTC_EVT_TIMEOUT, /**< Timeout event. \n See @ref ble_gattc_evt_timeout_t. */ + BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE /**< Write without Response transmission complete. \n See @ref ble_gattc_evt_write_cmd_tx_complete_t. */ }; /** @} */ @@ -128,138 +128,138 @@ enum BLE_GATTC_EVTS */ typedef struct { - uint8_t write_cmd_tx_queue_size; /**< The guaranteed minimum number of Write without Response that can be queued for transmission. + uint8_t write_cmd_tx_queue_size; /**< The guaranteed minimum number of Write without Response that can be queued for transmission. The default value is @ref BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT */ } ble_gattc_conn_cfg_t; /**@brief Operation Handle Range. */ typedef struct { - uint16_t start_handle; /**< Start Handle. */ - uint16_t end_handle; /**< End Handle. */ + uint16_t start_handle; /**< Start Handle. */ + uint16_t end_handle; /**< End Handle. */ } ble_gattc_handle_range_t; /**@brief GATT service. */ typedef struct { - ble_uuid_t uuid; /**< Service UUID. */ - ble_gattc_handle_range_t handle_range; /**< Service Handle Range. */ + ble_uuid_t uuid; /**< Service UUID. */ + ble_gattc_handle_range_t handle_range; /**< Service Handle Range. */ } ble_gattc_service_t; /**@brief GATT include. */ typedef struct { - uint16_t handle; /**< Include Handle. */ - ble_gattc_service_t included_srvc; /**< Handle of the included service. */ + uint16_t handle; /**< Include Handle. */ + ble_gattc_service_t included_srvc; /**< Handle of the included service. */ } ble_gattc_include_t; /**@brief GATT characteristic. */ typedef struct { - ble_uuid_t uuid; /**< Characteristic UUID. */ - ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ - uint8_t char_ext_props : 1; /**< Extended properties present. */ - uint16_t handle_decl; /**< Handle of the Characteristic Declaration. */ - uint16_t handle_value; /**< Handle of the Characteristic Value. */ + ble_uuid_t uuid; /**< Characteristic UUID. */ + ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ + uint8_t char_ext_props : 1; /**< Extended properties present. */ + uint16_t handle_decl; /**< Handle of the Characteristic Declaration. */ + uint16_t handle_value; /**< Handle of the Characteristic Value. */ } ble_gattc_char_t; /**@brief GATT descriptor. */ typedef struct { - uint16_t handle; /**< Descriptor Handle. */ - ble_uuid_t uuid; /**< Descriptor UUID. */ + uint16_t handle; /**< Descriptor Handle. */ + ble_uuid_t uuid; /**< Descriptor UUID. */ } ble_gattc_desc_t; /**@brief Write Parameters. */ typedef struct { - uint8_t write_op; /**< Write Operation to be performed, see @ref BLE_GATT_WRITE_OPS. */ - uint8_t flags; /**< Flags, see @ref BLE_GATT_EXEC_WRITE_FLAGS. */ - uint16_t handle; /**< Handle to the attribute to be written. */ - uint16_t offset; /**< Offset in bytes. @note For WRITE_CMD and WRITE_REQ, offset must be 0. */ - uint16_t len; /**< Length of data in bytes. */ - uint8_t const *p_value; /**< Pointer to the value data. */ + uint8_t write_op; /**< Write Operation to be performed, see @ref BLE_GATT_WRITE_OPS. */ + uint8_t flags; /**< Flags, see @ref BLE_GATT_EXEC_WRITE_FLAGS. */ + uint16_t handle; /**< Handle to the attribute to be written. */ + uint16_t offset; /**< Offset in bytes. @note For WRITE_CMD and WRITE_REQ, offset must be 0. */ + uint16_t len; /**< Length of data in bytes. */ + uint8_t const *p_value; /**< Pointer to the value data. */ } ble_gattc_write_params_t; /**@brief Attribute Information for 16-bit Attribute UUID. */ typedef struct { - uint16_t handle; /**< Attribute handle. */ - ble_uuid_t uuid; /**< 16-bit Attribute UUID. */ + uint16_t handle; /**< Attribute handle. */ + ble_uuid_t uuid; /**< 16-bit Attribute UUID. */ } ble_gattc_attr_info16_t; /**@brief Attribute Information for 128-bit Attribute UUID. */ typedef struct { - uint16_t handle; /**< Attribute handle. */ - ble_uuid128_t uuid; /**< 128-bit Attribute UUID. */ + uint16_t handle; /**< Attribute handle. */ + ble_uuid128_t uuid; /**< 128-bit Attribute UUID. */ } ble_gattc_attr_info128_t; /**@brief Event structure for @ref BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP. */ typedef struct { - uint16_t count; /**< Service count. */ - ble_gattc_service_t services[1]; /**< Service data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t count; /**< Service count. */ + ble_gattc_service_t services[1]; /**< Service data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_prim_srvc_disc_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_REL_DISC_RSP. */ typedef struct { - uint16_t count; /**< Include count. */ - ble_gattc_include_t includes[1]; /**< Include data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t count; /**< Include count. */ + ble_gattc_include_t includes[1]; /**< Include data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_rel_disc_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_DISC_RSP. */ typedef struct { - uint16_t count; /**< Characteristic count. */ - ble_gattc_char_t chars[1]; /**< Characteristic data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t count; /**< Characteristic count. */ + ble_gattc_char_t chars[1]; /**< Characteristic data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_char_disc_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_DESC_DISC_RSP. */ typedef struct { - uint16_t count; /**< Descriptor count. */ - ble_gattc_desc_t descs[1]; /**< Descriptor data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t count; /**< Descriptor count. */ + ble_gattc_desc_t descs[1]; /**< Descriptor data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_desc_disc_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_ATTR_INFO_DISC_RSP. */ typedef struct { - uint16_t count; /**< Attribute count. */ - uint8_t format; /**< Attribute information format, see @ref BLE_GATTC_ATTR_INFO_FORMAT. */ - union { - ble_gattc_attr_info16_t attr_info16[1]; /**< Attribute information for 16-bit Attribute UUID. + uint16_t count; /**< Attribute count. */ + uint8_t format; /**< Attribute information format, see @ref BLE_GATTC_ATTR_INFO_FORMAT. */ + union { + ble_gattc_attr_info16_t attr_info16[1]; /**< Attribute information for 16-bit Attribute UUID. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ - ble_gattc_attr_info128_t attr_info128[1]; /**< Attribute information for 128-bit Attribute UUID. + ble_gattc_attr_info128_t attr_info128[1]; /**< Attribute information for 128-bit Attribute UUID. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ - } info; /**< Attribute information union. */ + } info; /**< Attribute information union. */ } ble_gattc_evt_attr_info_disc_rsp_t; /**@brief GATT read by UUID handle value pair. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - uint8_t *p_value; /**< Pointer to the Attribute Value, length is available in @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t::value_len. */ + uint16_t handle; /**< Attribute Handle. */ + uint8_t *p_value; /**< Pointer to the Attribute Value, length is available in @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t::value_len. */ } ble_gattc_handle_value_t; /**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP. */ typedef struct { - uint16_t count; /**< Handle-Value Pair Count. */ - uint16_t value_len; /**< Length of the value in Handle-Value(s) list. */ - uint8_t handle_value[1]; /**< Handle-Value(s) list. To iterate through the list use @ref sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter. + uint16_t count; /**< Handle-Value Pair Count. */ + uint16_t value_len; /**< Length of the value in Handle-Value(s) list. */ + uint8_t handle_value[1]; /**< Handle-Value(s) list. To iterate through the list use @ref sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_char_val_by_uuid_read_rsp_t; @@ -267,82 +267,82 @@ typedef struct /**@brief Event structure for @ref BLE_GATTC_EVT_READ_RSP. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - uint16_t offset; /**< Offset of the attribute data. */ - uint16_t len; /**< Attribute data length. */ - uint8_t data[1]; /**< Attribute data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t handle; /**< Attribute Handle. */ + uint16_t offset; /**< Offset of the attribute data. */ + uint16_t len; /**< Attribute data length. */ + uint8_t data[1]; /**< Attribute data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_read_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_VALS_READ_RSP. */ typedef struct { - uint16_t len; /**< Concatenated Attribute values length. */ - uint8_t values[1]; /**< Attribute values. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t len; /**< Concatenated Attribute values length. */ + uint8_t values[1]; /**< Attribute values. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_char_vals_read_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_WRITE_RSP. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - uint8_t write_op; /**< Type of write operation, see @ref BLE_GATT_WRITE_OPS. */ - uint16_t offset; /**< Data offset. */ - uint16_t len; /**< Data length. */ - uint8_t data[1]; /**< Data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t handle; /**< Attribute Handle. */ + uint8_t write_op; /**< Type of write operation, see @ref BLE_GATT_WRITE_OPS. */ + uint16_t offset; /**< Data offset. */ + uint16_t len; /**< Data length. */ + uint8_t data[1]; /**< Data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_write_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_HVX. */ typedef struct { - uint16_t handle; /**< Handle to which the HVx operation applies. */ - uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ - uint16_t len; /**< Attribute data length. */ - uint8_t data[1]; /**< Attribute data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t handle; /**< Handle to which the HVx operation applies. */ + uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ + uint16_t len; /**< Attribute data length. */ + uint8_t data[1]; /**< Attribute data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_hvx_t; /**@brief Event structure for @ref BLE_GATTC_EVT_EXCHANGE_MTU_RSP. */ typedef struct { - uint16_t server_rx_mtu; /**< Server RX MTU size. */ + uint16_t server_rx_mtu; /**< Server RX MTU size. */ } ble_gattc_evt_exchange_mtu_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_TIMEOUT. */ typedef struct { - uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ + uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ } ble_gattc_evt_timeout_t; /**@brief Event structure for @ref BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE. */ typedef struct { - uint8_t count; /**< Number of write without response transmissions completed. */ + uint8_t count; /**< Number of write without response transmissions completed. */ } ble_gattc_evt_write_cmd_tx_complete_t; /**@brief GATTC event structure. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which event occurred. */ - uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ - uint16_t error_handle; /**< In case of error: The handle causing the error. In all other cases @ref BLE_GATT_HANDLE_INVALID. */ - union - { - ble_gattc_evt_prim_srvc_disc_rsp_t prim_srvc_disc_rsp; /**< Primary Service Discovery Response Event Parameters. */ - ble_gattc_evt_rel_disc_rsp_t rel_disc_rsp; /**< Relationship Discovery Response Event Parameters. */ - ble_gattc_evt_char_disc_rsp_t char_disc_rsp; /**< Characteristic Discovery Response Event Parameters. */ - ble_gattc_evt_desc_disc_rsp_t desc_disc_rsp; /**< Descriptor Discovery Response Event Parameters. */ - ble_gattc_evt_char_val_by_uuid_read_rsp_t char_val_by_uuid_read_rsp; /**< Characteristic Value Read by UUID Response Event Parameters. */ - ble_gattc_evt_read_rsp_t read_rsp; /**< Read Response Event Parameters. */ - ble_gattc_evt_char_vals_read_rsp_t char_vals_read_rsp; /**< Characteristic Values Read Response Event Parameters. */ - ble_gattc_evt_write_rsp_t write_rsp; /**< Write Response Event Parameters. */ - ble_gattc_evt_hvx_t hvx; /**< Handle Value Notification/Indication Event Parameters. */ - ble_gattc_evt_exchange_mtu_rsp_t exchange_mtu_rsp; /**< Exchange MTU Response Event Parameters. */ - ble_gattc_evt_timeout_t timeout; /**< Timeout Event Parameters. */ - ble_gattc_evt_attr_info_disc_rsp_t attr_info_disc_rsp; /**< Attribute Information Discovery Event Parameters. */ - ble_gattc_evt_write_cmd_tx_complete_t write_cmd_tx_complete; /**< Write without Response transmission complete Event Parameters. */ - } params; /**< Event Parameters. @note Only valid if @ref gatt_status == @ref BLE_GATT_STATUS_SUCCESS. */ + uint16_t conn_handle; /**< Connection Handle on which event occurred. */ + uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ + uint16_t error_handle; /**< In case of error: The handle causing the error. In all other cases @ref BLE_GATT_HANDLE_INVALID. */ + union + { + ble_gattc_evt_prim_srvc_disc_rsp_t prim_srvc_disc_rsp; /**< Primary Service Discovery Response Event Parameters. */ + ble_gattc_evt_rel_disc_rsp_t rel_disc_rsp; /**< Relationship Discovery Response Event Parameters. */ + ble_gattc_evt_char_disc_rsp_t char_disc_rsp; /**< Characteristic Discovery Response Event Parameters. */ + ble_gattc_evt_desc_disc_rsp_t desc_disc_rsp; /**< Descriptor Discovery Response Event Parameters. */ + ble_gattc_evt_char_val_by_uuid_read_rsp_t char_val_by_uuid_read_rsp; /**< Characteristic Value Read by UUID Response Event Parameters. */ + ble_gattc_evt_read_rsp_t read_rsp; /**< Read Response Event Parameters. */ + ble_gattc_evt_char_vals_read_rsp_t char_vals_read_rsp; /**< Characteristic Values Read Response Event Parameters. */ + ble_gattc_evt_write_rsp_t write_rsp; /**< Write Response Event Parameters. */ + ble_gattc_evt_hvx_t hvx; /**< Handle Value Notification/Indication Event Parameters. */ + ble_gattc_evt_exchange_mtu_rsp_t exchange_mtu_rsp; /**< Exchange MTU Response Event Parameters. */ + ble_gattc_evt_timeout_t timeout; /**< Timeout Event Parameters. */ + ble_gattc_evt_attr_info_disc_rsp_t attr_info_disc_rsp; /**< Attribute Information Discovery Event Parameters. */ + ble_gattc_evt_write_cmd_tx_complete_t write_cmd_tx_complete; /**< Write without Response transmission complete Event Parameters. */ + } params; /**< Event Parameters. @note Only valid if @ref gatt_status == @ref BLE_GATT_STATUS_SUCCESS. */ } ble_gattc_evt_t; /** @} */ @@ -621,7 +621,7 @@ SVCALL(SD_BLE_GATTC_HV_CONFIRM, uint32_t, sd_ble_gattc_hv_confirm(uint16_t conn_ * @retval ::NRF_ERROR_BUSY Client procedure already in progress. * @retval ::NRF_ERROR_TIMEOUT There has been a GATT procedure timeout. No new GATT procedure can be performed without reestablishing the connection. */ -SVCALL(SD_BLE_GATTC_ATTR_INFO_DISCOVER, uint32_t, sd_ble_gattc_attr_info_discover(uint16_t conn_handle, ble_gattc_handle_range_t const * p_handle_range)); +SVCALL(SD_BLE_GATTC_ATTR_INFO_DISCOVER, uint32_t, sd_ble_gattc_attr_info_discover(uint16_t conn_handle, ble_gattc_handle_range_t const *p_handle_range)); /**@brief Start an ATT_MTU exchange by sending an Exchange MTU Request to the server. * @@ -685,22 +685,18 @@ __STATIC_INLINE uint32_t sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(ble_gat #ifndef SUPPRESS_INLINE_IMPLEMENTATION -__STATIC_INLINE uint32_t sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(ble_gattc_evt_t *p_gattc_evt, ble_gattc_handle_value_t *p_iter) -{ - uint32_t value_len = p_gattc_evt->params.char_val_by_uuid_read_rsp.value_len; - uint8_t *p_first = p_gattc_evt->params.char_val_by_uuid_read_rsp.handle_value; - uint8_t *p_next = p_iter->p_value ? p_iter->p_value + value_len : p_first; +__STATIC_INLINE uint32_t sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(ble_gattc_evt_t *p_gattc_evt, ble_gattc_handle_value_t *p_iter) { + uint32_t value_len = p_gattc_evt->params.char_val_by_uuid_read_rsp.value_len; + uint8_t *p_first = p_gattc_evt->params.char_val_by_uuid_read_rsp.handle_value; + uint8_t *p_next = p_iter->p_value ? p_iter->p_value + value_len : p_first; - if ((p_next - p_first) / (sizeof(uint16_t) + value_len) < p_gattc_evt->params.char_val_by_uuid_read_rsp.count) - { - p_iter->handle = (uint16_t)p_next[1] << 8 | p_next[0]; - p_iter->p_value = p_next + sizeof(uint16_t); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_NOT_FOUND; - } + if ((p_next - p_first) / (sizeof(uint16_t) + value_len) < p_gattc_evt->params.char_val_by_uuid_read_rsp.count) { + p_iter->handle = (uint16_t)p_next[1] << 8 | p_next[0]; + p_iter->p_value = p_next + sizeof(uint16_t); + return NRF_SUCCESS; + } else { + return NRF_ERROR_NOT_FOUND; + } } #endif /* SUPPRESS_INLINE_IMPLEMENTATION */ diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gatts.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gatts.h index 394d8d1897..1a7a51ac1e 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gatts.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_gatts.h @@ -67,20 +67,20 @@ extern "C" { */ enum BLE_GATTS_SVCS { - SD_BLE_GATTS_SERVICE_ADD = BLE_GATTS_SVC_BASE, /**< Add a service. */ - SD_BLE_GATTS_INCLUDE_ADD, /**< Add an included service. */ - SD_BLE_GATTS_CHARACTERISTIC_ADD, /**< Add a characteristic. */ - SD_BLE_GATTS_DESCRIPTOR_ADD, /**< Add a generic attribute. */ - SD_BLE_GATTS_VALUE_SET, /**< Set an attribute value. */ - SD_BLE_GATTS_VALUE_GET, /**< Get an attribute value. */ - SD_BLE_GATTS_HVX, /**< Handle Value Notification or Indication. */ - SD_BLE_GATTS_SERVICE_CHANGED, /**< Perform a Service Changed Indication to one or more peers. */ - SD_BLE_GATTS_RW_AUTHORIZE_REPLY, /**< Reply to an authorization request for a read or write operation on one or more attributes. */ - SD_BLE_GATTS_SYS_ATTR_SET, /**< Set the persistent system attributes for a connection. */ - SD_BLE_GATTS_SYS_ATTR_GET, /**< Retrieve the persistent system attributes. */ - SD_BLE_GATTS_INITIAL_USER_HANDLE_GET, /**< Retrieve the first valid user handle. */ - SD_BLE_GATTS_ATTR_GET, /**< Retrieve the UUID and/or metadata of an attribute. */ - SD_BLE_GATTS_EXCHANGE_MTU_REPLY /**< Reply to Exchange MTU Request. */ + SD_BLE_GATTS_SERVICE_ADD = BLE_GATTS_SVC_BASE, /**< Add a service. */ + SD_BLE_GATTS_INCLUDE_ADD, /**< Add an included service. */ + SD_BLE_GATTS_CHARACTERISTIC_ADD, /**< Add a characteristic. */ + SD_BLE_GATTS_DESCRIPTOR_ADD, /**< Add a generic attribute. */ + SD_BLE_GATTS_VALUE_SET, /**< Set an attribute value. */ + SD_BLE_GATTS_VALUE_GET, /**< Get an attribute value. */ + SD_BLE_GATTS_HVX, /**< Handle Value Notification or Indication. */ + SD_BLE_GATTS_SERVICE_CHANGED, /**< Perform a Service Changed Indication to one or more peers. */ + SD_BLE_GATTS_RW_AUTHORIZE_REPLY, /**< Reply to an authorization request for a read or write operation on one or more attributes. */ + SD_BLE_GATTS_SYS_ATTR_SET, /**< Set the persistent system attributes for a connection. */ + SD_BLE_GATTS_SYS_ATTR_GET, /**< Retrieve the persistent system attributes. */ + SD_BLE_GATTS_INITIAL_USER_HANDLE_GET, /**< Retrieve the first valid user handle. */ + SD_BLE_GATTS_ATTR_GET, /**< Retrieve the UUID and/or metadata of an attribute. */ + SD_BLE_GATTS_EXCHANGE_MTU_REPLY /**< Reply to Exchange MTU Request. */ }; /** @@ -88,14 +88,14 @@ enum BLE_GATTS_SVCS */ enum BLE_GATTS_EVTS { - BLE_GATTS_EVT_WRITE = BLE_GATTS_EVT_BASE, /**< Write operation performed. \n See @ref ble_gatts_evt_write_t. */ - BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST, /**< Read/Write Authorization request. \n Reply with @ref sd_ble_gatts_rw_authorize_reply. \n See @ref ble_gatts_evt_rw_authorize_request_t. */ - BLE_GATTS_EVT_SYS_ATTR_MISSING, /**< A persistent system attribute access is pending. \n Respond with @ref sd_ble_gatts_sys_attr_set. \n See @ref ble_gatts_evt_sys_attr_missing_t. */ - BLE_GATTS_EVT_HVC, /**< Handle Value Confirmation. \n See @ref ble_gatts_evt_hvc_t. */ - BLE_GATTS_EVT_SC_CONFIRM, /**< Service Changed Confirmation. \n No additional event structure applies. */ - BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST, /**< Exchange MTU Request. \n Reply with @ref sd_ble_gatts_exchange_mtu_reply. \n See @ref ble_gatts_evt_exchange_mtu_request_t. */ - BLE_GATTS_EVT_TIMEOUT, /**< Peer failed to respond to an ATT request in time. \n See @ref ble_gatts_evt_timeout_t. */ - BLE_GATTS_EVT_HVN_TX_COMPLETE /**< Handle Value Notification transmission complete. \n See @ref ble_gatts_evt_hvn_tx_complete_t. */ + BLE_GATTS_EVT_WRITE = BLE_GATTS_EVT_BASE, /**< Write operation performed. \n See @ref ble_gatts_evt_write_t. */ + BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST, /**< Read/Write Authorization request. \n Reply with @ref sd_ble_gatts_rw_authorize_reply. \n See @ref ble_gatts_evt_rw_authorize_request_t. */ + BLE_GATTS_EVT_SYS_ATTR_MISSING, /**< A persistent system attribute access is pending. \n Respond with @ref sd_ble_gatts_sys_attr_set. \n See @ref ble_gatts_evt_sys_attr_missing_t. */ + BLE_GATTS_EVT_HVC, /**< Handle Value Confirmation. \n See @ref ble_gatts_evt_hvc_t. */ + BLE_GATTS_EVT_SC_CONFIRM, /**< Service Changed Confirmation. \n No additional event structure applies. */ + BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST, /**< Exchange MTU Request. \n Reply with @ref sd_ble_gatts_exchange_mtu_reply. \n See @ref ble_gatts_evt_exchange_mtu_request_t. */ + BLE_GATTS_EVT_TIMEOUT, /**< Peer failed to respond to an ATT request in time. \n See @ref ble_gatts_evt_timeout_t. */ + BLE_GATTS_EVT_HVN_TX_COMPLETE /**< Handle Value Notification transmission complete. \n See @ref ble_gatts_evt_hvn_tx_complete_t. */ }; /**@brief GATTS Configuration IDs. @@ -104,8 +104,8 @@ enum BLE_GATTS_EVTS */ enum BLE_GATTS_CFGS { - BLE_GATTS_CFG_SERVICE_CHANGED = BLE_GATTS_CFG_BASE, /**< Service changed configuration. */ - BLE_GATTS_CFG_ATTR_TAB_SIZE, /**< Attribute table size configuration. */ + BLE_GATTS_CFG_SERVICE_CHANGED = BLE_GATTS_CFG_BASE, /**< Service changed configuration. */ + BLE_GATTS_CFG_ATTR_TAB_SIZE, /**< Attribute table size configuration. */ }; /** @} */ @@ -207,31 +207,31 @@ enum BLE_GATTS_CFGS */ typedef struct { - uint8_t hvn_tx_queue_size; /**< Minimum guaranteed number of Handle Value Notifications that can be queued for transmission. + uint8_t hvn_tx_queue_size; /**< Minimum guaranteed number of Handle Value Notifications that can be queued for transmission. The default value is @ref BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT */ } ble_gatts_conn_cfg_t; /**@brief Attribute metadata. */ typedef struct { - ble_gap_conn_sec_mode_t read_perm; /**< Read permissions. */ - ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ - uint8_t vlen :1; /**< Variable length attribute. */ - uint8_t vloc :2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ - uint8_t rd_auth :1; /**< Read authorization and value will be requested from the application on every read operation. */ - uint8_t wr_auth :1; /**< Write authorization will be requested from the application on every Write Request operation (but not Write Command). */ + ble_gap_conn_sec_mode_t read_perm; /**< Read permissions. */ + ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ + uint8_t vlen : 1; /**< Variable length attribute. */ + uint8_t vloc : 2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ + uint8_t rd_auth : 1; /**< Read authorization and value will be requested from the application on every read operation. */ + uint8_t wr_auth : 1; /**< Write authorization will be requested from the application on every Write Request operation (but not Write Command). */ } ble_gatts_attr_md_t; /**@brief GATT Attribute. */ typedef struct { - ble_uuid_t const *p_uuid; /**< Pointer to the attribute UUID. */ - ble_gatts_attr_md_t const *p_attr_md; /**< Pointer to the attribute metadata structure. */ - uint16_t init_len; /**< Initial attribute value length in bytes. */ - uint16_t init_offs; /**< Initial attribute value offset in bytes. If different from zero, the first init_offs bytes of the attribute value will be left uninitialized. */ - uint16_t max_len; /**< Maximum attribute value length in bytes, see @ref BLE_GATTS_ATTR_LENS_MAX for maximum values. */ - uint8_t *p_value; /**< Pointer to the attribute data. Please note that if the @ref BLE_GATTS_VLOC_USER value location is selected in the attribute metadata, this will have to point to a buffer + ble_uuid_t const *p_uuid; /**< Pointer to the attribute UUID. */ + ble_gatts_attr_md_t const *p_attr_md; /**< Pointer to the attribute metadata structure. */ + uint16_t init_len; /**< Initial attribute value length in bytes. */ + uint16_t init_offs; /**< Initial attribute value offset in bytes. If different from zero, the first init_offs bytes of the attribute value will be left uninitialized. */ + uint16_t max_len; /**< Maximum attribute value length in bytes, see @ref BLE_GATTS_ATTR_LENS_MAX for maximum values. */ + uint8_t *p_value; /**< Pointer to the attribute data. Please note that if the @ref BLE_GATTS_VLOC_USER value location is selected in the attribute metadata, this will have to point to a buffer that remains valid through the lifetime of the attribute. This excludes usage of automatic variables that may go out of scope or any other temporary location. The stack may access that memory directly without the application's knowledge. For writable characteristics, this value must not be a location in flash memory.*/ } ble_gatts_attr_t; @@ -239,9 +239,9 @@ typedef struct /**@brief GATT Attribute Value. */ typedef struct { - uint16_t len; /**< Length in bytes to be written or read. Length in bytes written or read after successful return.*/ - uint16_t offset; /**< Attribute value offset. */ - uint8_t *p_value; /**< Pointer to where value is stored or will be stored. + uint16_t len; /**< Length in bytes to be written or read. Length in bytes written or read after successful return.*/ + uint16_t offset; /**< Attribute value offset. */ + uint8_t *p_value; /**< Pointer to where value is stored or will be stored. If value is stored in user memory, only the attribute length is updated when p_value == NULL. Set to NULL when reading to obtain the complete length of the attribute value */ } ble_gatts_value_t; @@ -250,75 +250,75 @@ typedef struct /**@brief GATT Characteristic Presentation Format. */ typedef struct { - uint8_t format; /**< Format of the value, see @ref BLE_GATT_CPF_FORMATS. */ - int8_t exponent; /**< Exponent for integer data types. */ - uint16_t unit; /**< Unit from Bluetooth Assigned Numbers. */ - uint8_t name_space; /**< Namespace from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ - uint16_t desc; /**< Namespace description from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ + uint8_t format; /**< Format of the value, see @ref BLE_GATT_CPF_FORMATS. */ + int8_t exponent; /**< Exponent for integer data types. */ + uint16_t unit; /**< Unit from Bluetooth Assigned Numbers. */ + uint8_t name_space; /**< Namespace from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ + uint16_t desc; /**< Namespace description from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ } ble_gatts_char_pf_t; /**@brief GATT Characteristic metadata. */ typedef struct { - ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ - ble_gatt_char_ext_props_t char_ext_props; /**< Characteristic Extended Properties. */ - uint8_t const *p_char_user_desc; /**< Pointer to a UTF-8 encoded string (non-NULL terminated), NULL if the descriptor is not required. */ - uint16_t char_user_desc_max_size; /**< The maximum size in bytes of the user description descriptor. */ - uint16_t char_user_desc_size; /**< The size of the user description, must be smaller or equal to char_user_desc_max_size. */ - ble_gatts_char_pf_t const *p_char_pf; /**< Pointer to a presentation format structure or NULL if the CPF descriptor is not required. */ - ble_gatts_attr_md_t const *p_user_desc_md; /**< Attribute metadata for the User Description descriptor, or NULL for default values. */ - ble_gatts_attr_md_t const *p_cccd_md; /**< Attribute metadata for the Client Characteristic Configuration Descriptor, or NULL for default values. */ - ble_gatts_attr_md_t const *p_sccd_md; /**< Attribute metadata for the Server Characteristic Configuration Descriptor, or NULL for default values. */ + ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ + ble_gatt_char_ext_props_t char_ext_props; /**< Characteristic Extended Properties. */ + uint8_t const *p_char_user_desc; /**< Pointer to a UTF-8 encoded string (non-NULL terminated), NULL if the descriptor is not required. */ + uint16_t char_user_desc_max_size; /**< The maximum size in bytes of the user description descriptor. */ + uint16_t char_user_desc_size; /**< The size of the user description, must be smaller or equal to char_user_desc_max_size. */ + ble_gatts_char_pf_t const *p_char_pf; /**< Pointer to a presentation format structure or NULL if the CPF descriptor is not required. */ + ble_gatts_attr_md_t const *p_user_desc_md; /**< Attribute metadata for the User Description descriptor, or NULL for default values. */ + ble_gatts_attr_md_t const *p_cccd_md; /**< Attribute metadata for the Client Characteristic Configuration Descriptor, or NULL for default values. */ + ble_gatts_attr_md_t const *p_sccd_md; /**< Attribute metadata for the Server Characteristic Configuration Descriptor, or NULL for default values. */ } ble_gatts_char_md_t; /**@brief GATT Characteristic Definition Handles. */ typedef struct { - uint16_t value_handle; /**< Handle to the characteristic value. */ - uint16_t user_desc_handle; /**< Handle to the User Description descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ - uint16_t cccd_handle; /**< Handle to the Client Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ - uint16_t sccd_handle; /**< Handle to the Server Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ + uint16_t value_handle; /**< Handle to the characteristic value. */ + uint16_t user_desc_handle; /**< Handle to the User Description descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ + uint16_t cccd_handle; /**< Handle to the Client Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ + uint16_t sccd_handle; /**< Handle to the Server Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ } ble_gatts_char_handles_t; /**@brief GATT HVx parameters. */ typedef struct { - uint16_t handle; /**< Characteristic Value Handle. */ - uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ - uint16_t offset; /**< Offset within the attribute value. */ - uint16_t *p_len; /**< Length in bytes to be written, length in bytes written after return. */ - uint8_t const *p_data; /**< Actual data content, use NULL to use the current attribute value. */ + uint16_t handle; /**< Characteristic Value Handle. */ + uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ + uint16_t offset; /**< Offset within the attribute value. */ + uint16_t *p_len; /**< Length in bytes to be written, length in bytes written after return. */ + uint8_t const *p_data; /**< Actual data content, use NULL to use the current attribute value. */ } ble_gatts_hvx_params_t; /**@brief GATT Authorization parameters. */ typedef struct { - uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ - uint8_t update : 1; /**< If set, data supplied in p_data will be used to update the attribute value. + uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ + uint8_t update : 1; /**< If set, data supplied in p_data will be used to update the attribute value. Please note that for @ref BLE_GATTS_AUTHORIZE_TYPE_WRITE operations this bit must always be set, as the data to be written needs to be stored and later provided by the application. */ - uint16_t offset; /**< Offset of the attribute value being updated. */ - uint16_t len; /**< Length in bytes of the value in p_data pointer, see @ref BLE_GATTS_ATTR_LENS_MAX. */ - uint8_t const *p_data; /**< Pointer to new value used to update the attribute value. */ + uint16_t offset; /**< Offset of the attribute value being updated. */ + uint16_t len; /**< Length in bytes of the value in p_data pointer, see @ref BLE_GATTS_ATTR_LENS_MAX. */ + uint8_t const *p_data; /**< Pointer to new value used to update the attribute value. */ } ble_gatts_authorize_params_t; /**@brief GATT Read or Write Authorize Reply parameters. */ typedef struct { - uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ - union { - ble_gatts_authorize_params_t read; /**< Read authorization parameters. */ - ble_gatts_authorize_params_t write; /**< Write authorization parameters. */ - } params; /**< Reply Parameters. */ + uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ + union { + ble_gatts_authorize_params_t read; /**< Read authorization parameters. */ + ble_gatts_authorize_params_t write; /**< Write authorization parameters. */ + } params; /**< Reply Parameters. */ } ble_gatts_rw_authorize_reply_params_t; /**@brief Service Changed Inclusion configuration parameters, set with @ref sd_ble_cfg_set. */ typedef struct { - uint8_t service_changed : 1; /**< If 1, include the Service Changed characteristic in the Attribute Table. Default is @ref BLE_GATTS_SERVICE_CHANGED_DEFAULT. */ + uint8_t service_changed : 1; /**< If 1, include the Service Changed characteristic in the Attribute Table. Default is @ref BLE_GATTS_SERVICE_CHANGED_DEFAULT. */ } ble_gatts_cfg_service_changed_t; /**@brief Attribute table size configuration parameters, set with @ref sd_ble_cfg_set. @@ -330,93 +330,93 @@ typedef struct */ typedef struct { - uint32_t attr_tab_size; /**< Attribute table size. Default is @ref BLE_GATTS_ATTR_TAB_SIZE_DEFAULT, minimum is @ref BLE_GATTS_ATTR_TAB_SIZE_MIN. */ + uint32_t attr_tab_size; /**< Attribute table size. Default is @ref BLE_GATTS_ATTR_TAB_SIZE_DEFAULT, minimum is @ref BLE_GATTS_ATTR_TAB_SIZE_MIN. */ } ble_gatts_cfg_attr_tab_size_t; /**@brief Config structure for GATTS configurations. */ typedef union { - ble_gatts_cfg_service_changed_t service_changed; /**< Include service changed characteristic, cfg_id is @ref BLE_GATTS_CFG_SERVICE_CHANGED. */ - ble_gatts_cfg_attr_tab_size_t attr_tab_size; /**< Attribute table size, cfg_id is @ref BLE_GATTS_CFG_ATTR_TAB_SIZE. */ + ble_gatts_cfg_service_changed_t service_changed; /**< Include service changed characteristic, cfg_id is @ref BLE_GATTS_CFG_SERVICE_CHANGED. */ + ble_gatts_cfg_attr_tab_size_t attr_tab_size; /**< Attribute table size, cfg_id is @ref BLE_GATTS_CFG_ATTR_TAB_SIZE. */ } ble_gatts_cfg_t; /**@brief Event structure for @ref BLE_GATTS_EVT_WRITE. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - ble_uuid_t uuid; /**< Attribute UUID. */ - uint8_t op; /**< Type of write operation, see @ref BLE_GATTS_OPS. */ - uint8_t auth_required; /**< Writing operation deferred due to authorization requirement. Application may use @ref sd_ble_gatts_value_set to finalize the writing operation. */ - uint16_t offset; /**< Offset for the write operation. */ - uint16_t len; /**< Length of the received data. */ - uint8_t data[1]; /**< Received data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t handle; /**< Attribute Handle. */ + ble_uuid_t uuid; /**< Attribute UUID. */ + uint8_t op; /**< Type of write operation, see @ref BLE_GATTS_OPS. */ + uint8_t auth_required; /**< Writing operation deferred due to authorization requirement. Application may use @ref sd_ble_gatts_value_set to finalize the writing operation. */ + uint16_t offset; /**< Offset for the write operation. */ + uint16_t len; /**< Length of the received data. */ + uint8_t data[1]; /**< Received data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gatts_evt_write_t; /**@brief Event substructure for authorized read requests, see @ref ble_gatts_evt_rw_authorize_request_t. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - ble_uuid_t uuid; /**< Attribute UUID. */ - uint16_t offset; /**< Offset for the read operation. */ + uint16_t handle; /**< Attribute Handle. */ + ble_uuid_t uuid; /**< Attribute UUID. */ + uint16_t offset; /**< Offset for the read operation. */ } ble_gatts_evt_read_t; /**@brief Event structure for @ref BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST. */ typedef struct { - uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ - union { - ble_gatts_evt_read_t read; /**< Attribute Read Parameters. */ - ble_gatts_evt_write_t write; /**< Attribute Write Parameters. */ - } request; /**< Request Parameters. */ + uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ + union { + ble_gatts_evt_read_t read; /**< Attribute Read Parameters. */ + ble_gatts_evt_write_t write; /**< Attribute Write Parameters. */ + } request; /**< Request Parameters. */ } ble_gatts_evt_rw_authorize_request_t; /**@brief Event structure for @ref BLE_GATTS_EVT_SYS_ATTR_MISSING. */ typedef struct { - uint8_t hint; /**< Hint (currently unused). */ + uint8_t hint; /**< Hint (currently unused). */ } ble_gatts_evt_sys_attr_missing_t; /**@brief Event structure for @ref BLE_GATTS_EVT_HVC. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ + uint16_t handle; /**< Attribute Handle. */ } ble_gatts_evt_hvc_t; /**@brief Event structure for @ref BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST. */ typedef struct { - uint16_t client_rx_mtu; /**< Client RX MTU size. */ + uint16_t client_rx_mtu; /**< Client RX MTU size. */ } ble_gatts_evt_exchange_mtu_request_t; /**@brief Event structure for @ref BLE_GATTS_EVT_TIMEOUT. */ typedef struct { - uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ + uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ } ble_gatts_evt_timeout_t; /**@brief Event structure for @ref BLE_GATTS_EVT_HVN_TX_COMPLETE. */ typedef struct { - uint8_t count; /**< Number of notification transmissions completed. */ + uint8_t count; /**< Number of notification transmissions completed. */ } ble_gatts_evt_hvn_tx_complete_t; /**@brief GATTS event structure. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which the event occurred. */ - union - { - ble_gatts_evt_write_t write; /**< Write Event Parameters. */ - ble_gatts_evt_rw_authorize_request_t authorize_request; /**< Read or Write Authorize Request Parameters. */ - ble_gatts_evt_sys_attr_missing_t sys_attr_missing; /**< System attributes missing. */ - ble_gatts_evt_hvc_t hvc; /**< Handle Value Confirmation Event Parameters. */ - ble_gatts_evt_exchange_mtu_request_t exchange_mtu_request; /**< Exchange MTU Request Event Parameters. */ - ble_gatts_evt_timeout_t timeout; /**< Timeout Event. */ - ble_gatts_evt_hvn_tx_complete_t hvn_tx_complete; /**< Handle Value Notification transmission complete Event Parameters. */ - } params; /**< Event Parameters. */ + uint16_t conn_handle; /**< Connection Handle on which the event occurred. */ + union + { + ble_gatts_evt_write_t write; /**< Write Event Parameters. */ + ble_gatts_evt_rw_authorize_request_t authorize_request; /**< Read or Write Authorize Request Parameters. */ + ble_gatts_evt_sys_attr_missing_t sys_attr_missing; /**< System attributes missing. */ + ble_gatts_evt_hvc_t hvc; /**< Handle Value Confirmation Event Parameters. */ + ble_gatts_evt_exchange_mtu_request_t exchange_mtu_request; /**< Exchange MTU Request Event Parameters. */ + ble_gatts_evt_timeout_t timeout; /**< Timeout Event. */ + ble_gatts_evt_hvn_tx_complete_t hvn_tx_complete; /**< Handle Value Notification transmission complete Event Parameters. */ + } params; /**< Event Parameters. */ } ble_gatts_evt_t; /** @} */ @@ -443,7 +443,7 @@ typedef struct * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack. * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation. */ -SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type, ble_uuid_t const *p_uuid, uint16_t *p_handle)); +SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type, ble_uuid_t const *p_uuid, uint16_t * p_handle)); /**@brief Add an include declaration to the Attribute Table. @@ -469,7 +469,7 @@ SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation. * @retval ::NRF_ERROR_NOT_FOUND Attribute not found. */ -SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t service_handle, uint16_t inc_srvc_handle, uint16_t *p_include_handle)); +SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t service_handle, uint16_t inc_srvc_handle, uint16_t * p_include_handle)); /**@brief Add a characteristic declaration, a characteristic value declaration and optional characteristic descriptor declarations to the Attribute Table. @@ -498,7 +498,7 @@ SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t ser * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation. * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. */ -SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_add(uint16_t service_handle, ble_gatts_char_md_t const *p_char_md, ble_gatts_attr_t const *p_attr_char_value, ble_gatts_char_handles_t *p_handles)); +SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_add(uint16_t service_handle, ble_gatts_char_md_t const *p_char_md, ble_gatts_attr_t const *p_attr_char_value, ble_gatts_char_handles_t * p_handles)); /**@brief Add a descriptor to the Attribute Table. @@ -521,7 +521,7 @@ SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_ad * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation. * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. */ -SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16_t char_handle, ble_gatts_attr_t const *p_attr, uint16_t *p_handle)); +SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16_t char_handle, ble_gatts_attr_t const *p_attr, uint16_t * p_handle)); /**@brief Set the value of a given attribute. * @@ -544,7 +544,7 @@ SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16 * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied on a system attribute. */ -SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t *p_value)); +SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t * p_value)); /**@brief Get the value of a given attribute. * @@ -568,7 +568,7 @@ SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t conn_ha * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied on a system attribute. * @retval ::BLE_ERROR_GATTS_SYS_ATTR_MISSING System attributes missing, use @ref sd_ble_gatts_sys_attr_set to set them to a known value. */ -SVCALL(SD_BLE_GATTS_VALUE_GET, uint32_t, sd_ble_gatts_value_get(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t *p_value)); +SVCALL(SD_BLE_GATTS_VALUE_GET, uint32_t, sd_ble_gatts_value_get(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t * p_value)); /**@brief Notify or Indicate an attribute value. * @@ -779,7 +779,7 @@ SVCALL(SD_BLE_GATTS_SYS_ATTR_SET, uint32_t, sd_ble_gatts_sys_attr_set(uint16_t c * @retval ::NRF_ERROR_DATA_SIZE The system attribute information did not fit into the provided buffer. * @retval ::NRF_ERROR_NOT_FOUND No system attributes found. */ -SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t conn_handle, uint8_t *p_sys_attr_data, uint16_t *p_len, uint32_t flags)); +SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t conn_handle, uint8_t * p_sys_attr_data, uint16_t * p_len, uint32_t flags)); /**@brief Retrieve the first valid user attribute handle. @@ -789,7 +789,7 @@ SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t c * @retval ::NRF_SUCCESS Successfully retrieved the handle. * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. */ -SVCALL(SD_BLE_GATTS_INITIAL_USER_HANDLE_GET, uint32_t, sd_ble_gatts_initial_user_handle_get(uint16_t *p_handle)); +SVCALL(SD_BLE_GATTS_INITIAL_USER_HANDLE_GET, uint32_t, sd_ble_gatts_initial_user_handle_get(uint16_t * p_handle)); /**@brief Retrieve the attribute UUID and/or metadata. * diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_l2cap.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_l2cap.h index edaf6641f8..d04bec3fbf 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_l2cap.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_l2cap.h @@ -84,31 +84,31 @@ extern "C" { /**@brief L2CAP API SVC numbers. */ enum BLE_L2CAP_SVCS { - SD_BLE_L2CAP_CH_SETUP = BLE_L2CAP_SVC_BASE + 0, /**< Set up an L2CAP channel. */ - SD_BLE_L2CAP_CH_RELEASE = BLE_L2CAP_SVC_BASE + 1, /**< Release an L2CAP channel. */ - SD_BLE_L2CAP_CH_RX = BLE_L2CAP_SVC_BASE + 2, /**< Receive an SDU on an L2CAP channel. */ - SD_BLE_L2CAP_CH_TX = BLE_L2CAP_SVC_BASE + 3, /**< Transmit an SDU on an L2CAP channel. */ - SD_BLE_L2CAP_CH_FLOW_CONTROL = BLE_L2CAP_SVC_BASE + 4, /**< Advanced SDU reception flow control. */ + SD_BLE_L2CAP_CH_SETUP = BLE_L2CAP_SVC_BASE + 0,/**< Set up an L2CAP channel. */ + SD_BLE_L2CAP_CH_RELEASE = BLE_L2CAP_SVC_BASE + 1,/**< Release an L2CAP channel. */ + SD_BLE_L2CAP_CH_RX = BLE_L2CAP_SVC_BASE + 2,/**< Receive an SDU on an L2CAP channel. */ + SD_BLE_L2CAP_CH_TX = BLE_L2CAP_SVC_BASE + 3,/**< Transmit an SDU on an L2CAP channel. */ + SD_BLE_L2CAP_CH_FLOW_CONTROL = BLE_L2CAP_SVC_BASE + 4, /**< Advanced SDU reception flow control. */ }; /**@brief L2CAP Event IDs. */ enum BLE_L2CAP_EVTS { - BLE_L2CAP_EVT_CH_SETUP_REQUEST = BLE_L2CAP_EVT_BASE + 0, /**< L2CAP Channel Setup Request event. + BLE_L2CAP_EVT_CH_SETUP_REQUEST = BLE_L2CAP_EVT_BASE + 0, /**< L2CAP Channel Setup Request event. \n See @ref ble_l2cap_evt_ch_setup_request_t. */ - BLE_L2CAP_EVT_CH_SETUP_REFUSED = BLE_L2CAP_EVT_BASE + 1, /**< L2CAP Channel Setup Refused event. + BLE_L2CAP_EVT_CH_SETUP_REFUSED = BLE_L2CAP_EVT_BASE + 1, /**< L2CAP Channel Setup Refused event. \n See @ref ble_l2cap_evt_ch_setup_refused_t. */ - BLE_L2CAP_EVT_CH_SETUP = BLE_L2CAP_EVT_BASE + 2, /**< L2CAP Channel Setup Completed event. + BLE_L2CAP_EVT_CH_SETUP = BLE_L2CAP_EVT_BASE + 2, /**< L2CAP Channel Setup Completed event. \n See @ref ble_l2cap_evt_ch_setup_t. */ - BLE_L2CAP_EVT_CH_RELEASED = BLE_L2CAP_EVT_BASE + 3, /**< L2CAP Channel Released event. + BLE_L2CAP_EVT_CH_RELEASED = BLE_L2CAP_EVT_BASE + 3, /**< L2CAP Channel Released event. \n No additional event structure applies. */ - BLE_L2CAP_EVT_CH_SDU_BUF_RELEASED = BLE_L2CAP_EVT_BASE + 4, /**< L2CAP Channel SDU data buffer released event. + BLE_L2CAP_EVT_CH_SDU_BUF_RELEASED = BLE_L2CAP_EVT_BASE + 4, /**< L2CAP Channel SDU data buffer released event. \n See @ref ble_l2cap_evt_ch_sdu_buf_released_t. */ - BLE_L2CAP_EVT_CH_CREDIT = BLE_L2CAP_EVT_BASE + 5, /**< L2CAP Channel Credit received. + BLE_L2CAP_EVT_CH_CREDIT = BLE_L2CAP_EVT_BASE + 5, /**< L2CAP Channel Credit received. \n See @ref ble_l2cap_evt_ch_credit_t. */ - BLE_L2CAP_EVT_CH_RX = BLE_L2CAP_EVT_BASE + 6, /**< L2CAP Channel SDU received. + BLE_L2CAP_EVT_CH_RX = BLE_L2CAP_EVT_BASE + 6, /**< L2CAP Channel SDU received. \n See @ref ble_l2cap_evt_ch_rx_t. */ - BLE_L2CAP_EVT_CH_TX = BLE_L2CAP_EVT_BASE + 7, /**< L2CAP Channel SDU transmitted. + BLE_L2CAP_EVT_CH_TX = BLE_L2CAP_EVT_BASE + 7, /**< L2CAP Channel SDU transmitted. \n See @ref ble_l2cap_evt_ch_tx_t. */ }; @@ -136,9 +136,9 @@ enum BLE_L2CAP_EVTS * @{ */ #define BLE_L2CAP_CH_SETUP_REFUSED_SRC_LOCAL (0x01) /**< Local. */ #define BLE_L2CAP_CH_SETUP_REFUSED_SRC_REMOTE (0x02) /**< Remote. */ - /** @} */ +/** @} */ - /** @defgroup BLE_L2CAP_CH_STATUS_CODES L2CAP channel status codes +/** @defgroup BLE_L2CAP_CH_STATUS_CODES L2CAP channel status codes * @{ */ #define BLE_L2CAP_CH_STATUS_CODE_SUCCESS (0x0000) /**< Success. */ #define BLE_L2CAP_CH_STATUS_CODE_LE_PSM_NOT_SUPPORTED (0x0002) /**< LE_PSM not supported. */ @@ -173,17 +173,17 @@ enum BLE_L2CAP_EVTS */ typedef struct { - uint16_t rx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall + uint16_t rx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall be able to receive on L2CAP channels on connections with this configuration. The minimum value is @ref BLE_L2CAP_MPS_MIN. */ - uint16_t tx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall + uint16_t tx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall be able to transmit on L2CAP channels on connections with this configuration. The minimum value is @ref BLE_L2CAP_MPS_MIN. */ - uint8_t rx_queue_size; /**< Number of SDU data buffers that can be queued for reception per + uint8_t rx_queue_size; /**< Number of SDU data buffers that can be queued for reception per L2CAP channel. The minimum value is one. */ - uint8_t tx_queue_size; /**< Number of SDU data buffers that can be queued for transmission + uint8_t tx_queue_size; /**< Number of SDU data buffers that can be queued for transmission per L2CAP channel. The minimum value is one. */ - uint8_t ch_count; /**< Number of L2CAP channels the application can create per connection + uint8_t ch_count; /**< Number of L2CAP channels the application can create per connection with this configuration. The default value is zero, the maximum value is @ref BLE_L2CAP_CH_COUNT_MAX. @note if this parameter is set to zero, all other parameters in @@ -193,14 +193,14 @@ typedef struct /**@brief L2CAP channel RX parameters. */ typedef struct { - uint16_t rx_mtu; /**< The maximum L2CAP SDU size, in bytes, that L2CAP shall be able to + uint16_t rx_mtu; /**< The maximum L2CAP SDU size, in bytes, that L2CAP shall be able to receive on this L2CAP channel. - Must be equal to or greater than @ref BLE_L2CAP_MTU_MIN. */ - uint16_t rx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall be + uint16_t rx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall be able to receive on this L2CAP channel. - Must be equal to or greater than @ref BLE_L2CAP_MPS_MIN. - Must be equal to or less than @ref ble_l2cap_conn_cfg_t::rx_mps. */ - ble_data_t sdu_buf; /**< SDU data buffer for reception. + ble_data_t sdu_buf; /**< SDU data buffer for reception. - If @ref ble_data_t::p_data is non-NULL, initial credits are issued to the peer. - If @ref ble_data_t::p_data is NULL, no initial credits are @@ -210,10 +210,10 @@ typedef struct /**@brief L2CAP channel setup parameters. */ typedef struct { - ble_l2cap_ch_rx_params_t rx_params; /**< L2CAP channel RX parameters. */ - uint16_t le_psm; /**< LE Protocol/Service Multiplexer. Used when requesting + ble_l2cap_ch_rx_params_t rx_params; /**< L2CAP channel RX parameters. */ + uint16_t le_psm; /**< LE Protocol/Service Multiplexer. Used when requesting setup of an L2CAP channel, ignored otherwise. */ - uint16_t status; /**< Status code, see @ref BLE_L2CAP_CH_STATUS_CODES. + uint16_t status; /**< Status code, see @ref BLE_L2CAP_CH_STATUS_CODES. Used when replying to a setup request of an L2CAP channel, ignored otherwise. */ } ble_l2cap_ch_setup_params_t; @@ -221,41 +221,41 @@ typedef struct /**@brief L2CAP channel TX parameters. */ typedef struct { - uint16_t tx_mtu; /**< The maximum L2CAP SDU size, in bytes, that L2CAP is able to + uint16_t tx_mtu; /**< The maximum L2CAP SDU size, in bytes, that L2CAP is able to transmit on this L2CAP channel. */ - uint16_t peer_mps; /**< The maximum L2CAP PDU payload size, in bytes, that the peer is + uint16_t peer_mps; /**< The maximum L2CAP PDU payload size, in bytes, that the peer is able to receive on this L2CAP channel. */ - uint16_t tx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP is able + uint16_t tx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP is able to transmit on this L2CAP channel. This is effective tx_mps, selected by the SoftDevice as MIN( @ref ble_l2cap_ch_tx_params_t::peer_mps, @ref ble_l2cap_conn_cfg_t::tx_mps ) */ - uint16_t credits; /**< Initial credits given by the peer. */ + uint16_t credits; /**< Initial credits given by the peer. */ } ble_l2cap_ch_tx_params_t; /**@brief L2CAP Channel Setup Request event. */ typedef struct { - ble_l2cap_ch_tx_params_t tx_params; /**< L2CAP channel TX parameters. */ - uint16_t le_psm; /**< LE Protocol/Service Multiplexer. */ + ble_l2cap_ch_tx_params_t tx_params; /**< L2CAP channel TX parameters. */ + uint16_t le_psm; /**< LE Protocol/Service Multiplexer. */ } ble_l2cap_evt_ch_setup_request_t; /**@brief L2CAP Channel Setup Refused event. */ typedef struct { - uint8_t source; /**< Source, see @ref BLE_L2CAP_CH_SETUP_REFUSED_SRCS */ - uint16_t status; /**< Status code, see @ref BLE_L2CAP_CH_STATUS_CODES */ + uint8_t source; /**< Source, see @ref BLE_L2CAP_CH_SETUP_REFUSED_SRCS */ + uint16_t status; /**< Status code, see @ref BLE_L2CAP_CH_STATUS_CODES */ } ble_l2cap_evt_ch_setup_refused_t; /**@brief L2CAP Channel Setup Completed event. */ typedef struct { - ble_l2cap_ch_tx_params_t tx_params; /**< L2CAP channel TX parameters. */ + ble_l2cap_ch_tx_params_t tx_params; /**< L2CAP channel TX parameters. */ } ble_l2cap_evt_ch_setup_t; /**@brief L2CAP Channel SDU Data Buffer Released event. */ typedef struct { - ble_data_t sdu_buf; /**< Returned reception or transmission SDU data buffer. The SoftDevice + ble_data_t sdu_buf; /**< Returned reception or transmission SDU data buffer. The SoftDevice returns SDU data buffers supplied by the application, which have not yet been returned previously via a @ref BLE_L2CAP_EVT_CH_RX or @ref BLE_L2CAP_EVT_CH_TX event. */ @@ -264,14 +264,14 @@ typedef struct /**@brief L2CAP Channel Credit received event. */ typedef struct { - uint16_t credits; /**< Additional credits given by the peer. */ + uint16_t credits; /**< Additional credits given by the peer. */ } ble_l2cap_evt_ch_credit_t; /**@brief L2CAP Channel received SDU event. */ typedef struct { - uint16_t sdu_len; /**< Total SDU length, in bytes. */ - ble_data_t sdu_buf; /**< SDU data buffer. + uint16_t sdu_len; /**< Total SDU length, in bytes. */ + ble_data_t sdu_buf; /**< SDU data buffer. @note If there is not enough space in the buffer (sdu_buf.len < sdu_len) then the rest of the SDU will be silently discarded by the SoftDevice. */ @@ -280,25 +280,25 @@ typedef struct /**@brief L2CAP Channel transmitted SDU event. */ typedef struct { - ble_data_t sdu_buf; /**< SDU data buffer. */ + ble_data_t sdu_buf; /**< SDU data buffer. */ } ble_l2cap_evt_ch_tx_t; /**@brief L2CAP event structure. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which the event occured. */ - uint16_t local_cid; /**< Local Channel ID of the L2CAP channel, or + uint16_t conn_handle; /**< Connection Handle on which the event occured. */ + uint16_t local_cid; /**< Local Channel ID of the L2CAP channel, or @ref BLE_L2CAP_CID_INVALID if not present. */ - union - { - ble_l2cap_evt_ch_setup_request_t ch_setup_request; /**< L2CAP Channel Setup Request Event Parameters. */ - ble_l2cap_evt_ch_setup_refused_t ch_setup_refused; /**< L2CAP Channel Setup Refused Event Parameters. */ - ble_l2cap_evt_ch_setup_t ch_setup; /**< L2CAP Channel Setup Completed Event Parameters. */ - ble_l2cap_evt_ch_sdu_buf_released_t ch_sdu_buf_released;/**< L2CAP Channel SDU Data Buffer Released Event Parameters. */ - ble_l2cap_evt_ch_credit_t credit; /**< L2CAP Channel Credit Received Event Parameters. */ - ble_l2cap_evt_ch_rx_t rx; /**< L2CAP Channel SDU Received Event Parameters. */ - ble_l2cap_evt_ch_tx_t tx; /**< L2CAP Channel SDU Transmitted Event Parameters. */ - } params; /**< Event Parameters. */ + union + { + ble_l2cap_evt_ch_setup_request_t ch_setup_request; /**< L2CAP Channel Setup Request Event Parameters. */ + ble_l2cap_evt_ch_setup_refused_t ch_setup_refused; /**< L2CAP Channel Setup Refused Event Parameters. */ + ble_l2cap_evt_ch_setup_t ch_setup; /**< L2CAP Channel Setup Completed Event Parameters. */ + ble_l2cap_evt_ch_sdu_buf_released_t ch_sdu_buf_released;/**< L2CAP Channel SDU Data Buffer Released Event Parameters. */ + ble_l2cap_evt_ch_credit_t credit; /**< L2CAP Channel Credit Received Event Parameters. */ + ble_l2cap_evt_ch_rx_t rx; /**< L2CAP Channel SDU Received Event Parameters. */ + ble_l2cap_evt_ch_tx_t tx; /**< L2CAP Channel SDU Transmitted Event Parameters. */ + } params; /**< Event Parameters. */ } ble_l2cap_evt_t; /** @} */ @@ -346,7 +346,7 @@ typedef struct * @retval ::NRF_ERROR_RESOURCES The limit has been reached for available L2CAP channels, * see @ref ble_l2cap_conn_cfg_t::ch_count. */ -SVCALL(SD_BLE_L2CAP_CH_SETUP, uint32_t, sd_ble_l2cap_ch_setup(uint16_t conn_handle, uint16_t *p_local_cid, ble_l2cap_ch_setup_params_t const *p_params)); +SVCALL(SD_BLE_L2CAP_CH_SETUP, uint32_t, sd_ble_l2cap_ch_setup(uint16_t conn_handle, uint16_t * p_local_cid, ble_l2cap_ch_setup_params_t const *p_params)); /**@brief Release an L2CAP channel. * @@ -492,7 +492,7 @@ SVCALL(SD_BLE_L2CAP_CH_TX, uint32_t, sd_ble_l2cap_ch_tx(uint16_t conn_handle, ui * in progress for an L2CAP channel). * @retval ::NRF_ERROR_NOT_FOUND CID not found. */ -SVCALL(SD_BLE_L2CAP_CH_FLOW_CONTROL, uint32_t, sd_ble_l2cap_ch_flow_control(uint16_t conn_handle, uint16_t local_cid, uint16_t credits, uint16_t *p_credits)); +SVCALL(SD_BLE_L2CAP_CH_FLOW_CONTROL, uint32_t, sd_ble_l2cap_ch_flow_control(uint16_t conn_handle, uint16_t local_cid, uint16_t credits, uint16_t * p_credits)); /** @} */ diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_types.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_types.h index 88c93180c8..3504959135 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_types.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/ble_types.h @@ -155,27 +155,27 @@ extern "C" { /** @} */ /** @brief Set .type and .uuid fields of ble_uuid_struct to specified UUID value. */ -#define BLE_UUID_BLE_ASSIGN(instance, value) do {\ - instance.type = BLE_UUID_TYPE_BLE; \ - instance.uuid = value;} while(0) +#define BLE_UUID_BLE_ASSIGN(instance, value) do { \ + instance.type = BLE_UUID_TYPE_BLE; \ + instance.uuid = value;} while (0) /** @brief Copy type and uuid members from src to dst ble_uuid_t pointer. Both pointers must be valid/non-null. */ -#define BLE_UUID_COPY_PTR(dst, src) do {\ - (dst)->type = (src)->type; \ - (dst)->uuid = (src)->uuid;} while(0) +#define BLE_UUID_COPY_PTR(dst, src) do { \ + (dst)->type = (src)->type; \ + (dst)->uuid = (src)->uuid;} while (0) /** @brief Copy type and uuid members from src to dst ble_uuid_t struct. */ -#define BLE_UUID_COPY_INST(dst, src) do {\ - (dst).type = (src).type; \ - (dst).uuid = (src).uuid;} while(0) +#define BLE_UUID_COPY_INST(dst, src) do { \ + (dst).type = (src).type; \ + (dst).uuid = (src).uuid;} while (0) /** @brief Compare for equality both type and uuid members of two (valid, non-null) ble_uuid_t pointers. */ #define BLE_UUID_EQ(p_uuid1, p_uuid2) \ - (((p_uuid1)->type == (p_uuid2)->type) && ((p_uuid1)->uuid == (p_uuid2)->uuid)) + (((p_uuid1)->type == (p_uuid2)->type) && ((p_uuid1)->uuid == (p_uuid2)->uuid)) /** @brief Compare for difference both type and uuid members of two (valid, non-null) ble_uuid_t pointers. */ #define BLE_UUID_NEQ(p_uuid1, p_uuid2) \ - (((p_uuid1)->type != (p_uuid2)->type) || ((p_uuid1)->uuid != (p_uuid2)->uuid)) + (((p_uuid1)->type != (p_uuid2)->type) || ((p_uuid1)->uuid != (p_uuid2)->uuid)) /** @} */ @@ -185,21 +185,21 @@ extern "C" { /** @brief 128 bit UUID values. */ typedef struct { - uint8_t uuid128[16]; /**< Little-Endian UUID bytes. */ + uint8_t uuid128[16]; /**< Little-Endian UUID bytes. */ } ble_uuid128_t; /** @brief Bluetooth Low Energy UUID type, encapsulates both 16-bit and 128-bit UUIDs. */ typedef struct { - uint16_t uuid; /**< 16-bit UUID value or octets 12-13 of 128-bit UUID. */ - uint8_t type; /**< UUID type, see @ref BLE_UUID_TYPES. If type is @ref BLE_UUID_TYPE_UNKNOWN, the value of uuid is undefined. */ + uint16_t uuid; /**< 16-bit UUID value or octets 12-13 of 128-bit UUID. */ + uint8_t type; /**< UUID type, see @ref BLE_UUID_TYPES. If type is @ref BLE_UUID_TYPE_UNKNOWN, the value of uuid is undefined. */ } ble_uuid_t; /**@brief Data structure. */ typedef struct { - uint8_t *p_data; /**< Pointer to the data buffer provided to/from the application. */ - uint16_t len; /**< Length of the data buffer, in bytes. */ + uint8_t *p_data; /**< Pointer to the data buffer provided to/from the application. */ + uint16_t len; /**< Length of the data buffer, in bytes. */ } ble_data_t; /** @} */ diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf52/nrf_mbr.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf52/nrf_mbr.h index e0c80e278c..1c7f3e1f3b 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf52/nrf_mbr.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf52/nrf_mbr.h @@ -75,19 +75,19 @@ This is the offset where the first byte of the SoftDevice hex file is written.*/ /**@brief nRF Master Boot Record API SVC numbers. */ enum NRF_MBR_SVCS { - SD_MBR_COMMAND = MBR_SVC_BASE, /**< ::sd_mbr_command */ + SD_MBR_COMMAND = MBR_SVC_BASE, /**< ::sd_mbr_command */ }; /**@brief Possible values for ::sd_mbr_command_t.command */ enum NRF_MBR_COMMANDS { - SD_MBR_COMMAND_COPY_BL, /**< Copy a new BootLoader. @see ::sd_mbr_command_copy_bl_t*/ - SD_MBR_COMMAND_COPY_SD, /**< Copy a new SoftDevice. @see ::sd_mbr_command_copy_sd_t*/ - SD_MBR_COMMAND_INIT_SD, /**< Initialize forwarding interrupts to SD, and run reset function in SD. Does not require any parameters in ::sd_mbr_command_t params.*/ - SD_MBR_COMMAND_COMPARE, /**< This command works like memcmp. @see ::sd_mbr_command_compare_t*/ - SD_MBR_COMMAND_VECTOR_TABLE_BASE_SET, /**< Change the address the MBR starts after a reset. @see ::sd_mbr_command_vector_table_base_set_t*/ - SD_MBR_COMMAND_RESERVED, - SD_MBR_COMMAND_IRQ_FORWARD_ADDRESS_SET, /**< Start forwarding all interrupts to this address. @see ::sd_mbr_command_irq_forward_address_set_t*/ + SD_MBR_COMMAND_COPY_BL, /**< Copy a new BootLoader. @see ::sd_mbr_command_copy_bl_t*/ + SD_MBR_COMMAND_COPY_SD, /**< Copy a new SoftDevice. @see ::sd_mbr_command_copy_sd_t*/ + SD_MBR_COMMAND_INIT_SD, /**< Initialize forwarding interrupts to SD, and run reset function in SD. Does not require any parameters in ::sd_mbr_command_t params.*/ + SD_MBR_COMMAND_COMPARE, /**< This command works like memcmp. @see ::sd_mbr_command_compare_t*/ + SD_MBR_COMMAND_VECTOR_TABLE_BASE_SET, /**< Change the address the MBR starts after a reset. @see ::sd_mbr_command_vector_table_base_set_t*/ + SD_MBR_COMMAND_RESERVED, + SD_MBR_COMMAND_IRQ_FORWARD_ADDRESS_SET, /**< Start forwarding all interrupts to this address. @see ::sd_mbr_command_irq_forward_address_set_t*/ }; /** @} */ @@ -108,9 +108,9 @@ enum NRF_MBR_COMMANDS */ typedef struct { - uint32_t *src; /**< Pointer to the source of data to be copied.*/ - uint32_t *dst; /**< Pointer to the destination where the content is to be copied.*/ - uint32_t len; /**< Number of 32 bit words to copy. Must be a multiple of @ref MBR_PAGE_SIZE_IN_WORDS words.*/ + uint32_t *src; /**< Pointer to the source of data to be copied.*/ + uint32_t *dst; /**< Pointer to the destination where the content is to be copied.*/ + uint32_t len; /**< Number of 32 bit words to copy. Must be a multiple of @ref MBR_PAGE_SIZE_IN_WORDS words.*/ } sd_mbr_command_copy_sd_t; @@ -121,9 +121,9 @@ typedef struct */ typedef struct { - uint32_t *ptr1; /**< Pointer to block of memory. */ - uint32_t *ptr2; /**< Pointer to block of memory. */ - uint32_t len; /**< Number of 32 bit words to compare.*/ + uint32_t *ptr1; /**< Pointer to block of memory. */ + uint32_t *ptr2; /**< Pointer to block of memory. */ + uint32_t len; /**< Number of 32 bit words to compare.*/ } sd_mbr_command_compare_t; @@ -147,8 +147,8 @@ typedef struct */ typedef struct { - uint32_t *bl_src; /**< Pointer to the source of the Bootloader to be be copied.*/ - uint32_t bl_len; /**< Number of 32 bit words to copy for BootLoader. */ + uint32_t *bl_src; /**< Pointer to the source of the Bootloader to be be copied.*/ + uint32_t bl_len; /**< Number of 32 bit words to copy for BootLoader. */ } sd_mbr_command_copy_bl_t; /**@brief Change the address the MBR starts after a reset @@ -168,7 +168,7 @@ typedef struct */ typedef struct { - uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/ + uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/ } sd_mbr_command_vector_table_base_set_t; /**@brief Sets the base address of the interrupt vector table for interrupts forwarded from the MBR @@ -180,7 +180,7 @@ typedef struct */ typedef struct { - uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/ + uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/ } sd_mbr_command_irq_forward_address_set_t; /**@brief Input structure containing data used when calling ::sd_mbr_command @@ -191,15 +191,15 @@ typedef struct */ typedef struct { - uint32_t command; /**< Type of command to be issued. See @ref NRF_MBR_COMMANDS. */ - union - { - sd_mbr_command_copy_sd_t copy_sd; /**< Parameters for copy SoftDevice.*/ - sd_mbr_command_compare_t compare; /**< Parameters for verify.*/ - sd_mbr_command_copy_bl_t copy_bl; /**< Parameters for copy BootLoader. Requires parameter page. */ - sd_mbr_command_vector_table_base_set_t base_set; /**< Parameters for vector table base set. Requires parameter page.*/ - sd_mbr_command_irq_forward_address_set_t irq_forward_address_set; /**< Parameters for irq forward address set*/ - } params; /**< Command parameters. */ + uint32_t command; /**< Type of command to be issued. See @ref NRF_MBR_COMMANDS. */ + union + { + sd_mbr_command_copy_sd_t copy_sd; /**< Parameters for copy SoftDevice.*/ + sd_mbr_command_compare_t compare; /**< Parameters for verify.*/ + sd_mbr_command_copy_bl_t copy_bl; /**< Parameters for copy BootLoader. Requires parameter page. */ + sd_mbr_command_vector_table_base_set_t base_set; /**< Parameters for vector table base set. Requires parameter page.*/ + sd_mbr_command_irq_forward_address_set_t irq_forward_address_set; /**< Parameters for irq forward address set*/ + } params; /**< Command parameters. */ } sd_mbr_command_t; /** @} */ @@ -228,7 +228,7 @@ typedef struct * @retval ::NRF_ERROR_NO_MEM if UICR.NRFFW[1] is not set (i.e. is 0xFFFFFFFF). * @retval ::NRF_ERROR_INVALID_PARAM if an invalid command is given. */ -SVCALL(SD_MBR_COMMAND, uint32_t, sd_mbr_command(sd_mbr_command_t* param)); +SVCALL(SD_MBR_COMMAND, uint32_t, sd_mbr_command(sd_mbr_command_t * param)); /** @} */ diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_error.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_error.h index 6badee98e5..7e9bf748d5 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_error.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_error.h @@ -36,7 +36,7 @@ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - /** +/** @defgroup nrf_error SoftDevice Global Error Codes @{ diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_error_sdm.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_error_sdm.h index 530959b9d6..8e43a6102f 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_error_sdm.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_error_sdm.h @@ -36,7 +36,7 @@ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - /** +/** @addtogroup nrf_sdm_api @{ @defgroup nrf_sdm_error SoftDevice Manager Error Codes diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_nvic.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_nvic.h index 1f79cc3c8c..c2fa90f668 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_nvic.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_nvic.h @@ -77,17 +77,17 @@ extern "C" { /**@brief Interrupt priority levels used by the SoftDevice. */ #define __NRF_NVIC_SD_IRQ_PRIOS ((uint8_t)( \ - (1U << 0) /**< Priority level high .*/ \ + (1U << 0) /**< Priority level high .*/ \ | (1U << 1) /**< Priority level medium. */ \ | (1U << 4) /**< Priority level low. */ \ - )) + )) /**@brief Interrupt priority levels available to the application. */ -#define __NRF_NVIC_APP_IRQ_PRIOS ((uint8_t)~__NRF_NVIC_SD_IRQ_PRIOS) +#define __NRF_NVIC_APP_IRQ_PRIOS ((uint8_t) ~__NRF_NVIC_SD_IRQ_PRIOS) /**@brief Interrupts used by the SoftDevice, with IRQn in the range 0-31. */ #define __NRF_NVIC_SD_IRQS_0 ((uint32_t)( \ - (1U << POWER_CLOCK_IRQn) \ + (1U << POWER_CLOCK_IRQn) \ | (1U << RADIO_IRQn) \ | (1U << RTC0_IRQn) \ | (1U << TIMER0_IRQn) \ @@ -97,7 +97,7 @@ extern "C" { | (1U << TEMP_IRQn) \ | (1U << __NRF_NVIC_NVMC_IRQn) \ | (1U << (uint32_t)SWI5_IRQn) \ - )) + )) /**@brief Interrupts used by the SoftDevice, with IRQn in the range 32-63. */ #define __NRF_NVIC_SD_IRQS_1 ((uint32_t)0) @@ -118,8 +118,8 @@ extern "C" { /**@brief Type representing the state struct for the SoftDevice NVIC module. */ typedef struct { - uint32_t volatile __irq_masks[__NRF_NVIC_ISER_COUNT]; /**< IRQs enabled by the application in the NVIC. */ - uint32_t volatile __cr_flag; /**< Non-zero if already in a critical region */ + uint32_t volatile __irq_masks[__NRF_NVIC_ISER_COUNT]; /**< IRQs enabled by the application in the NVIC. */ + uint32_t volatile __cr_flag; /**< Non-zero if already in a critical region */ } nrf_nvic_state_t; /**@brief Variable keeping the state for the SoftDevice NVIC module. This must be declared in an @@ -196,7 +196,7 @@ __STATIC_INLINE uint32_t sd_nvic_DisableIRQ(IRQn_Type IRQn); * @retval ::NRF_SUCCESS The interrupt is available for the application. * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application. */ -__STATIC_INLINE uint32_t sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t * p_pending_irq); +__STATIC_INLINE uint32_t sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t *p_pending_irq); /**@brief Set Pending Interrupt. * @note Corresponds to NVIC_SetPendingIRQ in CMSIS. @@ -248,7 +248,7 @@ __STATIC_INLINE uint32_t sd_nvic_SetPriority(IRQn_Type IRQn, uint32_t priority); * @retval ::NRF_SUCCESS The interrupt priority is returned in p_priority. * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE - IRQn is not available for the application. */ -__STATIC_INLINE uint32_t sd_nvic_GetPriority(IRQn_Type IRQn, uint32_t * p_priority); +__STATIC_INLINE uint32_t sd_nvic_GetPriority(IRQn_Type IRQn, uint32_t *p_priority); /**@brief System Reset. * @note Corresponds to NVIC_SystemReset in CMSIS. @@ -268,7 +268,7 @@ __STATIC_INLINE uint32_t sd_nvic_SystemReset(void); * * @retval ::NRF_SUCCESS */ -__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t * p_is_nested_critical_region); +__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t *p_is_nested_critical_region); /**@brief Exit critical region. * @@ -285,199 +285,150 @@ __STATIC_INLINE uint32_t sd_nvic_critical_region_exit(uint8_t is_nested_critical #ifndef SUPPRESS_INLINE_IMPLEMENTATION -__STATIC_INLINE int __sd_nvic_irq_disable(void) -{ - int pm = __get_PRIMASK(); - __disable_irq(); - return pm; +__STATIC_INLINE int __sd_nvic_irq_disable(void) { + int pm = __get_PRIMASK(); + __disable_irq(); + return pm; } -__STATIC_INLINE void __sd_nvic_irq_enable(void) -{ - __enable_irq(); +__STATIC_INLINE void __sd_nvic_irq_enable(void) { + __enable_irq(); } -__STATIC_INLINE uint32_t __sd_nvic_app_accessible_irq(IRQn_Type IRQn) -{ - if (IRQn < 32) - { - return ((1UL<= (1 << __NVIC_PRIO_BITS)) - || (((1 << priority) & __NRF_NVIC_APP_IRQ_PRIOS) == 0) - ) - { - return 0; - } - return 1; -} - - -__STATIC_INLINE uint32_t sd_nvic_EnableIRQ(IRQn_Type IRQn) -{ - if (!__sd_nvic_app_accessible_irq(IRQn)) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } - if (!__sd_nvic_is_app_accessible_priority(NVIC_GetPriority(IRQn))) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED; - } - - if (nrf_nvic_state.__cr_flag) - { - nrf_nvic_state.__irq_masks[(uint32_t)((int32_t)IRQn) >> 5] |= (uint32_t)(1 << ((uint32_t)((int32_t)IRQn) & (uint32_t)0x1F)); - } - else - { - NVIC_EnableIRQ(IRQn); - } - return NRF_SUCCESS; -} - -__STATIC_INLINE uint32_t sd_nvic_DisableIRQ(IRQn_Type IRQn) -{ - if (!__sd_nvic_app_accessible_irq(IRQn)) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } - - if (nrf_nvic_state.__cr_flag) - { - nrf_nvic_state.__irq_masks[(uint32_t)((int32_t)IRQn) >> 5] &= ~(1UL << ((uint32_t)(IRQn) & 0x1F)); - } - else - { - NVIC_DisableIRQ(IRQn); - } - - return NRF_SUCCESS; -} - -__STATIC_INLINE uint32_t sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t * p_pending_irq) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - *p_pending_irq = NVIC_GetPendingIRQ(IRQn); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } -} - -__STATIC_INLINE uint32_t sd_nvic_SetPendingIRQ(IRQn_Type IRQn) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - NVIC_SetPendingIRQ(IRQn); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } -} - -__STATIC_INLINE uint32_t sd_nvic_ClearPendingIRQ(IRQn_Type IRQn) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - NVIC_ClearPendingIRQ(IRQn); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } -} - -__STATIC_INLINE uint32_t sd_nvic_SetPriority(IRQn_Type IRQn, uint32_t priority) -{ - if (!__sd_nvic_app_accessible_irq(IRQn)) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } - - if (!__sd_nvic_is_app_accessible_priority(priority)) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED; - } - - NVIC_SetPriority(IRQn, (uint32_t)priority); - return NRF_SUCCESS; -} - -__STATIC_INLINE uint32_t sd_nvic_GetPriority(IRQn_Type IRQn, uint32_t * p_priority) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - *p_priority = (NVIC_GetPriority(IRQn) & 0xFF); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } -} - -__STATIC_INLINE uint32_t sd_nvic_SystemReset(void) -{ - NVIC_SystemReset(); - return NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN; -} - -__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t * p_is_nested_critical_region) -{ - int was_masked = __sd_nvic_irq_disable(); - if (!nrf_nvic_state.__cr_flag) - { - nrf_nvic_state.__cr_flag = 1; - nrf_nvic_state.__irq_masks[0] = ( NVIC->ICER[0] & __NRF_NVIC_APP_IRQS_0 ); - NVIC->ICER[0] = __NRF_NVIC_APP_IRQS_0; - nrf_nvic_state.__irq_masks[1] = ( NVIC->ICER[1] & __NRF_NVIC_APP_IRQS_1 ); - NVIC->ICER[1] = __NRF_NVIC_APP_IRQS_1; - *p_is_nested_critical_region = 0; - } - else - { - *p_is_nested_critical_region = 1; - } - if (!was_masked) - { - __sd_nvic_irq_enable(); - } - return NRF_SUCCESS; -} - -__STATIC_INLINE uint32_t sd_nvic_critical_region_exit(uint8_t is_nested_critical_region) -{ - if (nrf_nvic_state.__cr_flag && (is_nested_critical_region == 0)) - { - int was_masked = __sd_nvic_irq_disable(); - NVIC->ISER[0] = nrf_nvic_state.__irq_masks[0]; - NVIC->ISER[1] = nrf_nvic_state.__irq_masks[1]; - nrf_nvic_state.__cr_flag = 0; - if (!was_masked) - { - __sd_nvic_irq_enable(); +__STATIC_INLINE uint32_t __sd_nvic_app_accessible_irq(IRQn_Type IRQn) { + if (IRQn < 32) { + return ((1UL << IRQn) & __NRF_NVIC_APP_IRQS_0) != 0; + } else if (IRQn < 64) { + return ((1UL << (IRQn - 32)) & __NRF_NVIC_APP_IRQS_1) != 0; + } else { + return 1; } - } +} - return NRF_SUCCESS; +__STATIC_INLINE uint32_t __sd_nvic_is_app_accessible_priority(uint32_t priority) { + if ((priority >= (1 << __NVIC_PRIO_BITS)) + || (((1 << priority) & __NRF_NVIC_APP_IRQ_PRIOS) == 0) + ) { + return 0; + } + return 1; +} + + +__STATIC_INLINE uint32_t sd_nvic_EnableIRQ(IRQn_Type IRQn) { + if (!__sd_nvic_app_accessible_irq(IRQn)) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } + if (!__sd_nvic_is_app_accessible_priority(NVIC_GetPriority(IRQn))) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED; + } + + if (nrf_nvic_state.__cr_flag) { + nrf_nvic_state.__irq_masks[(uint32_t)((int32_t)IRQn) >> 5] |= (uint32_t)(1 << ((uint32_t)((int32_t)IRQn) & (uint32_t)0x1F)); + } else { + NVIC_EnableIRQ(IRQn); + } + return NRF_SUCCESS; +} + +__STATIC_INLINE uint32_t sd_nvic_DisableIRQ(IRQn_Type IRQn) { + if (!__sd_nvic_app_accessible_irq(IRQn)) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } + + if (nrf_nvic_state.__cr_flag) { + nrf_nvic_state.__irq_masks[(uint32_t)((int32_t)IRQn) >> 5] &= ~(1UL << ((uint32_t)(IRQn) & 0x1F)); + } else { + NVIC_DisableIRQ(IRQn); + } + + return NRF_SUCCESS; +} + +__STATIC_INLINE uint32_t sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t *p_pending_irq) { + if (__sd_nvic_app_accessible_irq(IRQn)) { + *p_pending_irq = NVIC_GetPendingIRQ(IRQn); + return NRF_SUCCESS; + } else { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } +} + +__STATIC_INLINE uint32_t sd_nvic_SetPendingIRQ(IRQn_Type IRQn) { + if (__sd_nvic_app_accessible_irq(IRQn)) { + NVIC_SetPendingIRQ(IRQn); + return NRF_SUCCESS; + } else { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } +} + +__STATIC_INLINE uint32_t sd_nvic_ClearPendingIRQ(IRQn_Type IRQn) { + if (__sd_nvic_app_accessible_irq(IRQn)) { + NVIC_ClearPendingIRQ(IRQn); + return NRF_SUCCESS; + } else { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } +} + +__STATIC_INLINE uint32_t sd_nvic_SetPriority(IRQn_Type IRQn, uint32_t priority) { + if (!__sd_nvic_app_accessible_irq(IRQn)) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } + + if (!__sd_nvic_is_app_accessible_priority(priority)) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED; + } + + NVIC_SetPriority(IRQn, (uint32_t)priority); + return NRF_SUCCESS; +} + +__STATIC_INLINE uint32_t sd_nvic_GetPriority(IRQn_Type IRQn, uint32_t *p_priority) { + if (__sd_nvic_app_accessible_irq(IRQn)) { + *p_priority = (NVIC_GetPriority(IRQn) & 0xFF); + return NRF_SUCCESS; + } else { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } +} + +__STATIC_INLINE uint32_t sd_nvic_SystemReset(void) { + NVIC_SystemReset(); + return NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN; +} + +__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t *p_is_nested_critical_region) { + int was_masked = __sd_nvic_irq_disable(); + if (!nrf_nvic_state.__cr_flag) { + nrf_nvic_state.__cr_flag = 1; + nrf_nvic_state.__irq_masks[0] = (NVIC->ICER[0] & __NRF_NVIC_APP_IRQS_0); + NVIC->ICER[0] = __NRF_NVIC_APP_IRQS_0; + nrf_nvic_state.__irq_masks[1] = (NVIC->ICER[1] & __NRF_NVIC_APP_IRQS_1); + NVIC->ICER[1] = __NRF_NVIC_APP_IRQS_1; + *p_is_nested_critical_region = 0; + } else { + *p_is_nested_critical_region = 1; + } + if (!was_masked) { + __sd_nvic_irq_enable(); + } + return NRF_SUCCESS; +} + +__STATIC_INLINE uint32_t sd_nvic_critical_region_exit(uint8_t is_nested_critical_region) { + if (nrf_nvic_state.__cr_flag && (is_nested_critical_region == 0)) { + int was_masked = __sd_nvic_irq_disable(); + NVIC->ISER[0] = nrf_nvic_state.__irq_masks[0]; + NVIC->ISER[1] = nrf_nvic_state.__irq_masks[1]; + nrf_nvic_state.__cr_flag = 0; + if (!was_masked) { + __sd_nvic_irq_enable(); + } + } + + return NRF_SUCCESS; } #endif /* SUPPRESS_INLINE_IMPLEMENTATION */ diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_sdm.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_sdm.h index 282e762e00..8a9979af2b 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_sdm.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_sdm.h @@ -130,12 +130,12 @@ the start of the SoftDevice (without MBR)*/ /** @brief Defines a macro for retrieving the actual SoftDevice Information Structure size value * from a given base address. Use @ref MBR_SIZE as the argument when the SoftDevice is * installed just above the MBR (the usual case). */ -#define SD_INFO_STRUCT_SIZE_GET(baseaddr) (*((uint8_t *) ((baseaddr) + SD_INFO_STRUCT_SIZE_OFFSET))) +#define SD_INFO_STRUCT_SIZE_GET(baseaddr) (*((uint8_t *)((baseaddr) + SD_INFO_STRUCT_SIZE_OFFSET))) /** @brief Defines a macro for retrieving the actual SoftDevice size value from a given base * address. Use @ref MBR_SIZE as the argument when the SoftDevice is installed just above * the MBR (the usual case). */ -#define SD_SIZE_GET(baseaddr) (*((uint32_t *) ((baseaddr) + SD_SIZE_OFFSET))) +#define SD_SIZE_GET(baseaddr) (*((uint32_t *)((baseaddr) + SD_SIZE_OFFSET))) /** @brief Defines the amount of flash that is used by the SoftDevice. * Add @ref MBR_SIZE to find the first available flash address when the SoftDevice is installed @@ -146,25 +146,25 @@ the start of the SoftDevice (without MBR)*/ /** @brief Defines a macro for retrieving the actual FWID value from a given base address. Use * @ref MBR_SIZE as the argument when the SoftDevice is installed just above the MBR (the usual * case). */ -#define SD_FWID_GET(baseaddr) (*((uint16_t *) ((baseaddr) + SD_FWID_OFFSET))) +#define SD_FWID_GET(baseaddr) (*((uint16_t *)((baseaddr) + SD_FWID_OFFSET))) /** @brief Defines a macro for retrieving the actual SoftDevice ID from a given base address. Use * @ref MBR_SIZE as the argument when the SoftDevice is installed just above the MBR (the * usual case). */ #define SD_ID_GET(baseaddr) ((SD_INFO_STRUCT_SIZE_GET(baseaddr) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) \ - ? (*((uint32_t *) ((baseaddr) + SD_ID_OFFSET))) : SDM_INFO_FIELD_INVALID) + ? (*((uint32_t *)((baseaddr) + SD_ID_OFFSET))) : SDM_INFO_FIELD_INVALID) /** @brief Defines a macro for retrieving the actual SoftDevice version from a given base address. * Use @ref MBR_SIZE as the argument when the SoftDevice is installed just above the MBR * (the usual case). */ #define SD_VERSION_GET(baseaddr) ((SD_INFO_STRUCT_SIZE_GET(baseaddr) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) \ - ? (*((uint32_t *) ((baseaddr) + SD_VERSION_OFFSET))) : SDM_INFO_FIELD_INVALID) + ? (*((uint32_t *)((baseaddr) + SD_VERSION_OFFSET))) : SDM_INFO_FIELD_INVALID) /** @brief Defines a macro for retrieving the address of SoftDevice unique str based on a given base address. * Use @ref MBR_SIZE as the argument when the SoftDevice is installed just above the MBR * (the usual case). */ #define SD_UNIQUE_STR_ADDR_GET(baseaddr) ((SD_INFO_STRUCT_SIZE_GET(baseaddr) > (SD_UNIQUE_STR_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) \ - ? (((uint8_t *) ((baseaddr) + SD_UNIQUE_STR_OFFSET))) : SDM_INFO_FIELD_INVALID) + ? (((uint8_t *)((baseaddr) + SD_UNIQUE_STR_OFFSET))) : SDM_INFO_FIELD_INVALID) /**@defgroup NRF_FAULT_ID_RANGES Fault ID ranges * @{ */ @@ -174,7 +174,7 @@ the start of the SoftDevice (without MBR)*/ /**@defgroup NRF_FAULT_IDS Fault ID types * @{ */ -#define NRF_FAULT_ID_SD_ASSERT (NRF_FAULT_ID_SD_RANGE_START + 1) /**< SoftDevice assertion. The info parameter is reserved for future used. */ +#define NRF_FAULT_ID_SD_ASSERT (NRF_FAULT_ID_SD_RANGE_START + 1) /**< SoftDevice assertion. The info parameter is reserved for future used. */ #define NRF_FAULT_ID_APP_MEMACC (NRF_FAULT_ID_APP_RANGE_START + 1) /**< Application invalid memory access. The info parameter will contain 0x00000000, in case of SoftDevice RAM access violation. In case of SoftDevice peripheral register violation the info parameter will contain the sub-region number of @@ -190,11 +190,11 @@ the start of the SoftDevice (without MBR)*/ /**@brief nRF SoftDevice Manager API SVC numbers. */ enum NRF_SD_SVCS { - SD_SOFTDEVICE_ENABLE = SDM_SVC_BASE, /**< ::sd_softdevice_enable */ - SD_SOFTDEVICE_DISABLE, /**< ::sd_softdevice_disable */ - SD_SOFTDEVICE_IS_ENABLED, /**< ::sd_softdevice_is_enabled */ - SD_SOFTDEVICE_VECTOR_TABLE_BASE_SET, /**< ::sd_softdevice_vector_table_base_set */ - SVC_SDM_LAST /**< Placeholder for last SDM SVC */ + SD_SOFTDEVICE_ENABLE = SDM_SVC_BASE, /**< ::sd_softdevice_enable */ + SD_SOFTDEVICE_DISABLE, /**< ::sd_softdevice_disable */ + SD_SOFTDEVICE_IS_ENABLED, /**< ::sd_softdevice_is_enabled */ + SD_SOFTDEVICE_VECTOR_TABLE_BASE_SET, /**< ::sd_softdevice_vector_table_base_set */ + SVC_SDM_LAST /**< Placeholder for last SDM SVC */ }; /** @} */ @@ -237,15 +237,15 @@ enum NRF_SD_SVCS /**@brief Type representing LFCLK oscillator source. */ typedef struct { - uint8_t source; /**< LF oscillator clock source, see @ref NRF_CLOCK_LF_SRC. */ - uint8_t rc_ctiv; /**< Only for ::NRF_CLOCK_LF_SRC_RC: Calibration timer interval in 1/4 second + uint8_t source; /**< LF oscillator clock source, see @ref NRF_CLOCK_LF_SRC. */ + uint8_t rc_ctiv; /**< Only for ::NRF_CLOCK_LF_SRC_RC: Calibration timer interval in 1/4 second units (nRF52: 1-32). @note To avoid excessive clock drift, 0.5 degrees Celsius is the maximum temperature change allowed in one calibration timer interval. The interval should be selected to ensure this. @note Must be 0 if source is not ::NRF_CLOCK_LF_SRC_RC. */ - uint8_t rc_temp_ctiv; /**< Only for ::NRF_CLOCK_LF_SRC_RC: How often (in number of calibration + uint8_t rc_temp_ctiv; /**< Only for ::NRF_CLOCK_LF_SRC_RC: How often (in number of calibration intervals) the RC oscillator shall be calibrated if the temperature hasn't changed. 0: Always calibrate even if the temperature hasn't changed. @@ -263,7 +263,7 @@ typedef struct least once every 8 seconds and for temperature changes of 0.5 degrees Celsius every 4 seconds. See the Product Specification for the nRF52 device being used for more information.*/ - uint8_t accuracy; /**< External clock accuracy used in the LL to compute timing + uint8_t accuracy; /**< External clock accuracy used in the LL to compute timing windows, see @ref NRF_CLOCK_LF_ACCURACY.*/ } nrf_clock_lf_cfg_t; @@ -319,7 +319,7 @@ typedef void (*nrf_fault_handler_t)(uint32_t id, uint32_t pc, uint32_t info); * @retval ::NRF_ERROR_SDM_LFCLK_SOURCE_UNKNOWN Unknown low frequency clock source selected. * @retval ::NRF_ERROR_INVALID_PARAM Invalid clock source configuration supplied in p_clock_lf_cfg. */ -SVCALL(SD_SOFTDEVICE_ENABLE, uint32_t, sd_softdevice_enable(nrf_clock_lf_cfg_t const * p_clock_lf_cfg, nrf_fault_handler_t fault_handler)); +SVCALL(SD_SOFTDEVICE_ENABLE, uint32_t, sd_softdevice_enable(nrf_clock_lf_cfg_t const *p_clock_lf_cfg, nrf_fault_handler_t fault_handler)); /**@brief Disables the SoftDevice and by extension the protocol stack. diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_soc.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_soc.h index beb4d3a541..e3790a9f4a 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_soc.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_soc.h @@ -100,7 +100,7 @@ extern "C" { /**@brief Mask of PPI channels reserved by the SoftDevice when the SoftDevice is enabled. */ #define NRF_SOC_SD_PPI_CHANNELS_SD_ENABLED_MSK ((uint32_t)( \ - (1U << 17) \ + (1U << 17) \ | (1U << 18) \ | (1U << 19) \ | (1U << 20) \ @@ -115,7 +115,7 @@ extern "C" { | (1U << 29) \ | (1U << 30) \ | (1U << 31) \ - )) + )) /**@brief Mask of PPI channels available to the application when the SoftDevice is disabled. */ #define NRF_SOC_APP_PPI_CHANNELS_SD_DISABLED_MSK (~NRF_SOC_SD_PPI_CHANNELS_SD_DISABLED_MSK) @@ -128,9 +128,9 @@ extern "C" { /**@brief Mask of PPI groups reserved by the SoftDevice when the SoftDevice is enabled. */ #define NRF_SOC_SD_PPI_GROUPS_SD_ENABLED_MSK ((uint32_t)( \ - (1U << 4) \ + (1U << 4) \ | (1U << 5) \ - )) + )) /**@brief Mask of PPI groups available to the application when the SoftDevice is disabled. */ #define NRF_SOC_APP_PPI_GROUPS_SD_DISABLED_MSK (~NRF_SOC_SD_PPI_GROUPS_SD_DISABLED_MSK) @@ -146,148 +146,148 @@ extern "C" { /**@brief The SVC numbers used by the SVC functions in the SoC library. */ enum NRF_SOC_SVCS { - SD_PPI_CHANNEL_ENABLE_GET = SOC_SVC_BASE, - SD_PPI_CHANNEL_ENABLE_SET = SOC_SVC_BASE + 1, - SD_PPI_CHANNEL_ENABLE_CLR = SOC_SVC_BASE + 2, - SD_PPI_CHANNEL_ASSIGN = SOC_SVC_BASE + 3, - SD_PPI_GROUP_TASK_ENABLE = SOC_SVC_BASE + 4, - SD_PPI_GROUP_TASK_DISABLE = SOC_SVC_BASE + 5, - SD_PPI_GROUP_ASSIGN = SOC_SVC_BASE + 6, - SD_PPI_GROUP_GET = SOC_SVC_BASE + 7, - SD_FLASH_PAGE_ERASE = SOC_SVC_BASE + 8, - SD_FLASH_WRITE = SOC_SVC_BASE + 9, - SD_PROTECTED_REGISTER_WRITE = SOC_SVC_BASE + 11, - SD_MUTEX_NEW = SOC_SVC_BASE_NOT_AVAILABLE, - SD_MUTEX_ACQUIRE = SOC_SVC_BASE_NOT_AVAILABLE + 1, - SD_MUTEX_RELEASE = SOC_SVC_BASE_NOT_AVAILABLE + 2, - SD_RAND_APPLICATION_POOL_CAPACITY_GET = SOC_SVC_BASE_NOT_AVAILABLE + 3, - SD_RAND_APPLICATION_BYTES_AVAILABLE_GET = SOC_SVC_BASE_NOT_AVAILABLE + 4, - SD_RAND_APPLICATION_VECTOR_GET = SOC_SVC_BASE_NOT_AVAILABLE + 5, - SD_POWER_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 6, - SD_POWER_SYSTEM_OFF = SOC_SVC_BASE_NOT_AVAILABLE + 7, - SD_POWER_RESET_REASON_GET = SOC_SVC_BASE_NOT_AVAILABLE + 8, - SD_POWER_RESET_REASON_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 9, - SD_POWER_POF_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 10, - SD_POWER_POF_THRESHOLD_SET = SOC_SVC_BASE_NOT_AVAILABLE + 11, - SD_POWER_POF_THRESHOLDVDDH_SET = SOC_SVC_BASE_NOT_AVAILABLE + 12, - SD_POWER_RAM_POWER_SET = SOC_SVC_BASE_NOT_AVAILABLE + 13, - SD_POWER_RAM_POWER_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 14, - SD_POWER_RAM_POWER_GET = SOC_SVC_BASE_NOT_AVAILABLE + 15, - SD_POWER_GPREGRET_SET = SOC_SVC_BASE_NOT_AVAILABLE + 16, - SD_POWER_GPREGRET_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 17, - SD_POWER_GPREGRET_GET = SOC_SVC_BASE_NOT_AVAILABLE + 18, - SD_POWER_DCDC_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 19, - SD_POWER_DCDC0_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 20, - SD_APP_EVT_WAIT = SOC_SVC_BASE_NOT_AVAILABLE + 21, - SD_CLOCK_HFCLK_REQUEST = SOC_SVC_BASE_NOT_AVAILABLE + 22, - SD_CLOCK_HFCLK_RELEASE = SOC_SVC_BASE_NOT_AVAILABLE + 23, - SD_CLOCK_HFCLK_IS_RUNNING = SOC_SVC_BASE_NOT_AVAILABLE + 24, - SD_RADIO_NOTIFICATION_CFG_SET = SOC_SVC_BASE_NOT_AVAILABLE + 25, - SD_ECB_BLOCK_ENCRYPT = SOC_SVC_BASE_NOT_AVAILABLE + 26, - SD_ECB_BLOCKS_ENCRYPT = SOC_SVC_BASE_NOT_AVAILABLE + 27, - SD_RADIO_SESSION_OPEN = SOC_SVC_BASE_NOT_AVAILABLE + 28, - SD_RADIO_SESSION_CLOSE = SOC_SVC_BASE_NOT_AVAILABLE + 29, - SD_RADIO_REQUEST = SOC_SVC_BASE_NOT_AVAILABLE + 30, - SD_EVT_GET = SOC_SVC_BASE_NOT_AVAILABLE + 31, - SD_TEMP_GET = SOC_SVC_BASE_NOT_AVAILABLE + 32, - SD_POWER_USBPWRRDY_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 33, - SD_POWER_USBDETECTED_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 34, - SD_POWER_USBREMOVED_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 35, - SD_POWER_USBREGSTATUS_GET = SOC_SVC_BASE_NOT_AVAILABLE + 36, - SVC_SOC_LAST = SOC_SVC_BASE_NOT_AVAILABLE + 37 + SD_PPI_CHANNEL_ENABLE_GET = SOC_SVC_BASE, + SD_PPI_CHANNEL_ENABLE_SET = SOC_SVC_BASE + 1, + SD_PPI_CHANNEL_ENABLE_CLR = SOC_SVC_BASE + 2, + SD_PPI_CHANNEL_ASSIGN = SOC_SVC_BASE + 3, + SD_PPI_GROUP_TASK_ENABLE = SOC_SVC_BASE + 4, + SD_PPI_GROUP_TASK_DISABLE = SOC_SVC_BASE + 5, + SD_PPI_GROUP_ASSIGN = SOC_SVC_BASE + 6, + SD_PPI_GROUP_GET = SOC_SVC_BASE + 7, + SD_FLASH_PAGE_ERASE = SOC_SVC_BASE + 8, + SD_FLASH_WRITE = SOC_SVC_BASE + 9, + SD_PROTECTED_REGISTER_WRITE = SOC_SVC_BASE + 11, + SD_MUTEX_NEW = SOC_SVC_BASE_NOT_AVAILABLE, + SD_MUTEX_ACQUIRE = SOC_SVC_BASE_NOT_AVAILABLE + 1, + SD_MUTEX_RELEASE = SOC_SVC_BASE_NOT_AVAILABLE + 2, + SD_RAND_APPLICATION_POOL_CAPACITY_GET = SOC_SVC_BASE_NOT_AVAILABLE + 3, + SD_RAND_APPLICATION_BYTES_AVAILABLE_GET = SOC_SVC_BASE_NOT_AVAILABLE + 4, + SD_RAND_APPLICATION_VECTOR_GET = SOC_SVC_BASE_NOT_AVAILABLE + 5, + SD_POWER_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 6, + SD_POWER_SYSTEM_OFF = SOC_SVC_BASE_NOT_AVAILABLE + 7, + SD_POWER_RESET_REASON_GET = SOC_SVC_BASE_NOT_AVAILABLE + 8, + SD_POWER_RESET_REASON_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 9, + SD_POWER_POF_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 10, + SD_POWER_POF_THRESHOLD_SET = SOC_SVC_BASE_NOT_AVAILABLE + 11, + SD_POWER_POF_THRESHOLDVDDH_SET = SOC_SVC_BASE_NOT_AVAILABLE + 12, + SD_POWER_RAM_POWER_SET = SOC_SVC_BASE_NOT_AVAILABLE + 13, + SD_POWER_RAM_POWER_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 14, + SD_POWER_RAM_POWER_GET = SOC_SVC_BASE_NOT_AVAILABLE + 15, + SD_POWER_GPREGRET_SET = SOC_SVC_BASE_NOT_AVAILABLE + 16, + SD_POWER_GPREGRET_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 17, + SD_POWER_GPREGRET_GET = SOC_SVC_BASE_NOT_AVAILABLE + 18, + SD_POWER_DCDC_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 19, + SD_POWER_DCDC0_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 20, + SD_APP_EVT_WAIT = SOC_SVC_BASE_NOT_AVAILABLE + 21, + SD_CLOCK_HFCLK_REQUEST = SOC_SVC_BASE_NOT_AVAILABLE + 22, + SD_CLOCK_HFCLK_RELEASE = SOC_SVC_BASE_NOT_AVAILABLE + 23, + SD_CLOCK_HFCLK_IS_RUNNING = SOC_SVC_BASE_NOT_AVAILABLE + 24, + SD_RADIO_NOTIFICATION_CFG_SET = SOC_SVC_BASE_NOT_AVAILABLE + 25, + SD_ECB_BLOCK_ENCRYPT = SOC_SVC_BASE_NOT_AVAILABLE + 26, + SD_ECB_BLOCKS_ENCRYPT = SOC_SVC_BASE_NOT_AVAILABLE + 27, + SD_RADIO_SESSION_OPEN = SOC_SVC_BASE_NOT_AVAILABLE + 28, + SD_RADIO_SESSION_CLOSE = SOC_SVC_BASE_NOT_AVAILABLE + 29, + SD_RADIO_REQUEST = SOC_SVC_BASE_NOT_AVAILABLE + 30, + SD_EVT_GET = SOC_SVC_BASE_NOT_AVAILABLE + 31, + SD_TEMP_GET = SOC_SVC_BASE_NOT_AVAILABLE + 32, + SD_POWER_USBPWRRDY_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 33, + SD_POWER_USBDETECTED_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 34, + SD_POWER_USBREMOVED_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 35, + SD_POWER_USBREGSTATUS_GET = SOC_SVC_BASE_NOT_AVAILABLE + 36, + SVC_SOC_LAST = SOC_SVC_BASE_NOT_AVAILABLE + 37 }; /**@brief Possible values of a ::nrf_mutex_t. */ enum NRF_MUTEX_VALUES { - NRF_MUTEX_FREE, - NRF_MUTEX_TAKEN + NRF_MUTEX_FREE, + NRF_MUTEX_TAKEN }; /**@brief Power modes. */ enum NRF_POWER_MODES { - NRF_POWER_MODE_CONSTLAT, /**< Constant latency mode. See power management in the reference manual. */ - NRF_POWER_MODE_LOWPWR /**< Low power mode. See power management in the reference manual. */ + NRF_POWER_MODE_CONSTLAT, /**< Constant latency mode. See power management in the reference manual. */ + NRF_POWER_MODE_LOWPWR /**< Low power mode. See power management in the reference manual. */ }; /**@brief Power failure thresholds */ enum NRF_POWER_THRESHOLDS { - NRF_POWER_THRESHOLD_V17 = 4UL, /**< 1.7 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V18, /**< 1.8 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V19, /**< 1.9 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V20, /**< 2.0 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V21, /**< 2.1 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V22, /**< 2.2 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V23, /**< 2.3 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V24, /**< 2.4 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V25, /**< 2.5 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V26, /**< 2.6 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V27, /**< 2.7 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V28 /**< 2.8 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V17 = 4UL, /**< 1.7 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V18, /**< 1.8 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V19, /**< 1.9 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V20, /**< 2.0 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V21, /**< 2.1 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V22, /**< 2.2 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V23, /**< 2.3 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V24, /**< 2.4 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V25, /**< 2.5 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V26, /**< 2.6 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V27, /**< 2.7 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V28 /**< 2.8 Volts power failure threshold. */ }; /**@brief Power failure thresholds for high voltage */ enum NRF_POWER_THRESHOLDVDDHS { - NRF_POWER_THRESHOLDVDDH_V27, /**< 2.7 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V28, /**< 2.8 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V29, /**< 2.9 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V30, /**< 3.0 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V31, /**< 3.1 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V32, /**< 3.2 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V33, /**< 3.3 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V34, /**< 3.4 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V35, /**< 3.5 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V36, /**< 3.6 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V37, /**< 3.7 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V38, /**< 3.8 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V39, /**< 3.9 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V40, /**< 4.0 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V41, /**< 4.1 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V42 /**< 4.2 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V27, /**< 2.7 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V28, /**< 2.8 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V29, /**< 2.9 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V30, /**< 3.0 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V31, /**< 3.1 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V32, /**< 3.2 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V33, /**< 3.3 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V34, /**< 3.4 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V35, /**< 3.5 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V36, /**< 3.6 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V37, /**< 3.7 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V38, /**< 3.8 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V39, /**< 3.9 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V40, /**< 4.0 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V41, /**< 4.1 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V42 /**< 4.2 Volts power failure threshold. */ }; /**@brief DC/DC converter modes. */ enum NRF_POWER_DCDC_MODES { - NRF_POWER_DCDC_DISABLE, /**< The DCDC is disabled. */ - NRF_POWER_DCDC_ENABLE /**< The DCDC is enabled. */ + NRF_POWER_DCDC_DISABLE, /**< The DCDC is disabled. */ + NRF_POWER_DCDC_ENABLE /**< The DCDC is enabled. */ }; /**@brief Radio notification distances. */ enum NRF_RADIO_NOTIFICATION_DISTANCES { - NRF_RADIO_NOTIFICATION_DISTANCE_NONE = 0, /**< The event does not have a notification. */ - NRF_RADIO_NOTIFICATION_DISTANCE_800US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_1740US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_2680US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_3620US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_4560US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_5500US /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_NONE = 0, /**< The event does not have a notification. */ + NRF_RADIO_NOTIFICATION_DISTANCE_800US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_1740US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_2680US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_3620US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_4560US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_5500US /**< The distance from the active notification to start of radio activity. */ }; /**@brief Radio notification types. */ enum NRF_RADIO_NOTIFICATION_TYPES { - NRF_RADIO_NOTIFICATION_TYPE_NONE = 0, /**< The event does not have a radio notification signal. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_ACTIVE, /**< Using interrupt for notification when the radio will be enabled. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_INACTIVE, /**< Using interrupt for notification when the radio has been disabled. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_BOTH, /**< Using interrupt for notification both when the radio will be enabled and disabled. */ + NRF_RADIO_NOTIFICATION_TYPE_NONE = 0, /**< The event does not have a radio notification signal. */ + NRF_RADIO_NOTIFICATION_TYPE_INT_ON_ACTIVE, /**< Using interrupt for notification when the radio will be enabled. */ + NRF_RADIO_NOTIFICATION_TYPE_INT_ON_INACTIVE, /**< Using interrupt for notification when the radio has been disabled. */ + NRF_RADIO_NOTIFICATION_TYPE_INT_ON_BOTH, /**< Using interrupt for notification both when the radio will be enabled and disabled. */ }; /**@brief The Radio signal callback types. */ enum NRF_RADIO_CALLBACK_SIGNAL_TYPE { - NRF_RADIO_CALLBACK_SIGNAL_TYPE_START, /**< This signal indicates the start of the radio timeslot. */ - NRF_RADIO_CALLBACK_SIGNAL_TYPE_TIMER0, /**< This signal indicates the NRF_TIMER0 interrupt. */ - NRF_RADIO_CALLBACK_SIGNAL_TYPE_RADIO, /**< This signal indicates the NRF_RADIO interrupt. */ - NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_FAILED, /**< This signal indicates extend action failed. */ - NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_SUCCEEDED /**< This signal indicates extend action succeeded. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_START, /**< This signal indicates the start of the radio timeslot. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_TIMER0, /**< This signal indicates the NRF_TIMER0 interrupt. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_RADIO, /**< This signal indicates the NRF_RADIO interrupt. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_FAILED, /**< This signal indicates extend action failed. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_SUCCEEDED /**< This signal indicates extend action succeeded. */ }; /**@brief The actions requested by the signal callback. @@ -297,28 +297,28 @@ enum NRF_RADIO_CALLBACK_SIGNAL_TYPE */ enum NRF_RADIO_SIGNAL_CALLBACK_ACTION { - NRF_RADIO_SIGNAL_CALLBACK_ACTION_NONE, /**< Return without action. */ - NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND, /**< Request an extension of the current + NRF_RADIO_SIGNAL_CALLBACK_ACTION_NONE, /**< Return without action. */ + NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND, /**< Request an extension of the current timeslot. Maximum execution time for this action: @ref NRF_RADIO_MAX_EXTENSION_PROCESSING_TIME_US. This action must be started at least @ref NRF_RADIO_MIN_EXTENSION_MARGIN_US before the end of the timeslot. */ - NRF_RADIO_SIGNAL_CALLBACK_ACTION_END, /**< End the current radio timeslot. */ - NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END /**< Request a new radio timeslot and end the current timeslot. */ + NRF_RADIO_SIGNAL_CALLBACK_ACTION_END, /**< End the current radio timeslot. */ + NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END /**< Request a new radio timeslot and end the current timeslot. */ }; /**@brief Radio timeslot high frequency clock source configuration. */ enum NRF_RADIO_HFCLK_CFG { - NRF_RADIO_HFCLK_CFG_XTAL_GUARANTEED, /**< The SoftDevice will guarantee that the high frequency clock source is the + NRF_RADIO_HFCLK_CFG_XTAL_GUARANTEED, /**< The SoftDevice will guarantee that the high frequency clock source is the external crystal for the whole duration of the timeslot. This should be the preferred option for events that use the radio or require high timing accuracy. @note The SoftDevice will automatically turn on and off the external crystal, at the beginning and end of the timeslot, respectively. The crystal may also intentionally be left running after the timeslot, in cases where it is needed by the SoftDevice shortly after the end of the timeslot. */ - NRF_RADIO_HFCLK_CFG_NO_GUARANTEE /**< This configuration allows for earlier and tighter scheduling of timeslots. + NRF_RADIO_HFCLK_CFG_NO_GUARANTEE /**< This configuration allows for earlier and tighter scheduling of timeslots. The RC oscillator may be the clock source in part or for the whole duration of the timeslot. The RC oscillator's accuracy must therefore be taken into consideration. @note If the application will use the radio peripheral in timeslots with this configuration, @@ -328,33 +328,33 @@ enum NRF_RADIO_HFCLK_CFG /**@brief Radio timeslot priorities. */ enum NRF_RADIO_PRIORITY { - NRF_RADIO_PRIORITY_HIGH, /**< High (equal priority as the normal connection priority of the SoftDevice stack(s)). */ - NRF_RADIO_PRIORITY_NORMAL, /**< Normal (equal priority as the priority of secondary activities of the SoftDevice stack(s)). */ + NRF_RADIO_PRIORITY_HIGH, /**< High (equal priority as the normal connection priority of the SoftDevice stack(s)). */ + NRF_RADIO_PRIORITY_NORMAL, /**< Normal (equal priority as the priority of secondary activities of the SoftDevice stack(s)). */ }; /**@brief Radio timeslot request type. */ enum NRF_RADIO_REQUEST_TYPE { - NRF_RADIO_REQ_TYPE_EARLIEST, /**< Request radio timeslot as early as possible. This should always be used for the first request in a session. */ - NRF_RADIO_REQ_TYPE_NORMAL /**< Normal radio timeslot request. */ + NRF_RADIO_REQ_TYPE_EARLIEST, /**< Request radio timeslot as early as possible. This should always be used for the first request in a session. */ + NRF_RADIO_REQ_TYPE_NORMAL /**< Normal radio timeslot request. */ }; /**@brief SoC Events. */ enum NRF_SOC_EVTS { - NRF_EVT_HFCLKSTARTED, /**< Event indicating that the HFCLK has started. */ - NRF_EVT_POWER_FAILURE_WARNING, /**< Event indicating that a power failure warning has occurred. */ - NRF_EVT_FLASH_OPERATION_SUCCESS, /**< Event indicating that the ongoing flash operation has completed successfully. */ - NRF_EVT_FLASH_OPERATION_ERROR, /**< Event indicating that the ongoing flash operation has timed out with an error. */ - NRF_EVT_RADIO_BLOCKED, /**< Event indicating that a radio timeslot was blocked. */ - NRF_EVT_RADIO_CANCELED, /**< Event indicating that a radio timeslot was canceled by SoftDevice. */ - NRF_EVT_RADIO_SIGNAL_CALLBACK_INVALID_RETURN, /**< Event indicating that a radio timeslot signal callback handler return was invalid. */ - NRF_EVT_RADIO_SESSION_IDLE, /**< Event indicating that a radio timeslot session is idle. */ - NRF_EVT_RADIO_SESSION_CLOSED, /**< Event indicating that a radio timeslot session is closed. */ - NRF_EVT_POWER_USB_POWER_READY, /**< Event indicating that a USB 3.3 V supply is ready. */ - NRF_EVT_POWER_USB_DETECTED, /**< Event indicating that voltage supply is detected on VBUS. */ - NRF_EVT_POWER_USB_REMOVED, /**< Event indicating that voltage supply is removed from VBUS. */ - NRF_EVT_NUMBER_OF_EVTS + NRF_EVT_HFCLKSTARTED, /**< Event indicating that the HFCLK has started. */ + NRF_EVT_POWER_FAILURE_WARNING, /**< Event indicating that a power failure warning has occurred. */ + NRF_EVT_FLASH_OPERATION_SUCCESS, /**< Event indicating that the ongoing flash operation has completed successfully. */ + NRF_EVT_FLASH_OPERATION_ERROR, /**< Event indicating that the ongoing flash operation has timed out with an error. */ + NRF_EVT_RADIO_BLOCKED, /**< Event indicating that a radio timeslot was blocked. */ + NRF_EVT_RADIO_CANCELED, /**< Event indicating that a radio timeslot was canceled by SoftDevice. */ + NRF_EVT_RADIO_SIGNAL_CALLBACK_INVALID_RETURN, /**< Event indicating that a radio timeslot signal callback handler return was invalid. */ + NRF_EVT_RADIO_SESSION_IDLE, /**< Event indicating that a radio timeslot session is idle. */ + NRF_EVT_RADIO_SESSION_CLOSED, /**< Event indicating that a radio timeslot session is closed. */ + NRF_EVT_POWER_USB_POWER_READY, /**< Event indicating that a USB 3.3 V supply is ready. */ + NRF_EVT_POWER_USB_DETECTED, /**< Event indicating that voltage supply is detected on VBUS. */ + NRF_EVT_POWER_USB_REMOVED, /**< Event indicating that voltage supply is removed from VBUS. */ + NRF_EVT_NUMBER_OF_EVTS }; /**@} */ @@ -371,47 +371,47 @@ typedef volatile uint8_t nrf_mutex_t; /**@brief Parameters for a request for a timeslot as early as possible. */ typedef struct { - uint8_t hfclk; /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */ - uint8_t priority; /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */ - uint32_t length_us; /**< The radio timeslot length (in the range 100 to 100,000] microseconds). */ - uint32_t timeout_us; /**< Longest acceptable delay until the start of the requested timeslot (up to @ref NRF_RADIO_EARLIEST_TIMEOUT_MAX_US microseconds). */ + uint8_t hfclk; /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */ + uint8_t priority; /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */ + uint32_t length_us; /**< The radio timeslot length (in the range 100 to 100,000] microseconds). */ + uint32_t timeout_us; /**< Longest acceptable delay until the start of the requested timeslot (up to @ref NRF_RADIO_EARLIEST_TIMEOUT_MAX_US microseconds). */ } nrf_radio_request_earliest_t; /**@brief Parameters for a normal radio timeslot request. */ typedef struct { - uint8_t hfclk; /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */ - uint8_t priority; /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */ - uint32_t distance_us; /**< Distance from the start of the previous radio timeslot (up to @ref NRF_RADIO_DISTANCE_MAX_US microseconds). */ - uint32_t length_us; /**< The radio timeslot length (in the range [100..100,000] microseconds). */ + uint8_t hfclk; /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */ + uint8_t priority; /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */ + uint32_t distance_us; /**< Distance from the start of the previous radio timeslot (up to @ref NRF_RADIO_DISTANCE_MAX_US microseconds). */ + uint32_t length_us; /**< The radio timeslot length (in the range [100..100,000] microseconds). */ } nrf_radio_request_normal_t; /**@brief Radio timeslot request parameters. */ typedef struct { - uint8_t request_type; /**< Type of request, see @ref NRF_RADIO_REQUEST_TYPE. */ - union - { - nrf_radio_request_earliest_t earliest; /**< Parameters for requesting a radio timeslot as early as possible. */ - nrf_radio_request_normal_t normal; /**< Parameters for requesting a normal radio timeslot. */ - } params; /**< Parameter union. */ + uint8_t request_type; /**< Type of request, see @ref NRF_RADIO_REQUEST_TYPE. */ + union + { + nrf_radio_request_earliest_t earliest; /**< Parameters for requesting a radio timeslot as early as possible. */ + nrf_radio_request_normal_t normal; /**< Parameters for requesting a normal radio timeslot. */ + } params; /**< Parameter union. */ } nrf_radio_request_t; /**@brief Return parameters of the radio timeslot signal callback. */ typedef struct { - uint8_t callback_action; /**< The action requested by the application when returning from the signal callback, see @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION. */ - union - { - struct + uint8_t callback_action; /**< The action requested by the application when returning from the signal callback, see @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION. */ + union { - nrf_radio_request_t * p_next; /**< The request parameters for the next radio timeslot. */ - } request; /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END. */ - struct - { - uint32_t length_us; /**< Requested extension of the radio timeslot duration (microseconds) (for minimum time see @ref NRF_RADIO_MINIMUM_TIMESLOT_LENGTH_EXTENSION_TIME_US). */ - } extend; /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND. */ - } params; /**< Parameter union. */ + struct + { + nrf_radio_request_t *p_next; /**< The request parameters for the next radio timeslot. */ + } request; /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END. */ + struct + { + uint32_t length_us; /**< Requested extension of the radio timeslot duration (microseconds) (for minimum time see @ref NRF_RADIO_MINIMUM_TIMESLOT_LENGTH_EXTENSION_TIME_US). */ + } extend; /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND. */ + } params; /**< Parameter union. */ } nrf_radio_signal_callback_return_param_t; /**@brief The radio timeslot signal callback type. @@ -426,7 +426,7 @@ typedef struct * * @return Pointer to structure containing action requested by the application. */ -typedef nrf_radio_signal_callback_return_param_t * (*nrf_radio_signal_callback_t) (uint8_t signal_type); +typedef nrf_radio_signal_callback_return_param_t * (*nrf_radio_signal_callback_t)(uint8_t signal_type); /**@brief AES ECB parameter typedefs */ typedef uint8_t soc_ecb_key_t[SOC_ECB_KEY_LENGTH]; /**< Encryption key type. */ @@ -436,18 +436,18 @@ typedef uint8_t soc_ecb_ciphertext_t[SOC_ECB_CIPHERTEXT_LENGTH]; /**< Ciphertex /**@brief AES ECB data structure */ typedef struct { - soc_ecb_key_t key; /**< Encryption key. */ - soc_ecb_cleartext_t cleartext; /**< Cleartext data. */ - soc_ecb_ciphertext_t ciphertext; /**< Ciphertext data. */ + soc_ecb_key_t key; /**< Encryption key. */ + soc_ecb_cleartext_t cleartext; /**< Cleartext data. */ + soc_ecb_ciphertext_t ciphertext; /**< Ciphertext data. */ } nrf_ecb_hal_data_t; /**@brief AES ECB block. Used to provide multiple blocks in a single call to @ref sd_ecb_blocks_encrypt.*/ typedef struct { - soc_ecb_key_t const * p_key; /**< Pointer to the Encryption key. */ - soc_ecb_cleartext_t const * p_cleartext; /**< Pointer to the Cleartext data. */ - soc_ecb_ciphertext_t * p_ciphertext; /**< Pointer to the Ciphertext data. */ + soc_ecb_key_t const *p_key; /**< Pointer to the Encryption key. */ + soc_ecb_cleartext_t const *p_cleartext; /**< Pointer to the Cleartext data. */ + soc_ecb_ciphertext_t *p_ciphertext; /**< Pointer to the Ciphertext data. */ } nrf_ecb_hal_data_block_t; /**@} */ @@ -667,7 +667,7 @@ SVCALL(SD_POWER_GPREGRET_CLR, uint32_t, sd_power_gpregret_clr(uint32_t gpregret_ * * @retval ::NRF_SUCCESS */ -SVCALL(SD_POWER_GPREGRET_GET, uint32_t, sd_power_gpregret_get(uint32_t gpregret_id, uint32_t *p_gpregret)); +SVCALL(SD_POWER_GPREGRET_GET, uint32_t, sd_power_gpregret_get(uint32_t gpregret_id, uint32_t * p_gpregret)); /**@brief Enable or disable the DC/DC regulator for the regulator stage 1 (REG1). * @@ -784,7 +784,7 @@ SVCALL(SD_PPI_CHANNEL_ENABLE_CLR, uint32_t, sd_ppi_channel_enable_clr(uint32_t c * @retval ::NRF_ERROR_SOC_PPI_INVALID_CHANNEL The channel number is invalid. * @retval ::NRF_SUCCESS */ -SVCALL(SD_PPI_CHANNEL_ASSIGN, uint32_t, sd_ppi_channel_assign(uint8_t channel_num, const volatile void * evt_endpoint, const volatile void * task_endpoint)); +SVCALL(SD_PPI_CHANNEL_ASSIGN, uint32_t, sd_ppi_channel_assign(uint8_t channel_num, const volatile void *evt_endpoint, const volatile void *task_endpoint)); /**@brief Task to enable a channel group. * @@ -945,7 +945,7 @@ SVCALL(SD_TEMP_GET, uint32_t, sd_temp_get(int32_t * p_temp)); * @retval ::NRF_ERROR_FORBIDDEN Tried to write to an address outside the application flash area. * @retval ::NRF_SUCCESS The command was accepted. */ -SVCALL(SD_FLASH_WRITE, uint32_t, sd_flash_write(uint32_t * p_dst, uint32_t const * p_src, uint32_t size)); +SVCALL(SD_FLASH_WRITE, uint32_t, sd_flash_write(uint32_t * p_dst, uint32_t const *p_src, uint32_t size)); /**@brief Flash Erase page @@ -1001,7 +1001,7 @@ SVCALL(SD_FLASH_PAGE_ERASE, uint32_t, sd_flash_page_erase(uint32_t page_number)) * @retval ::NRF_ERROR_INTERNAL If a new session could not be opened due to an internal error. * @retval ::NRF_SUCCESS Otherwise. */ - SVCALL(SD_RADIO_SESSION_OPEN, uint32_t, sd_radio_session_open(nrf_radio_signal_callback_t p_radio_signal_callback)); +SVCALL(SD_RADIO_SESSION_OPEN, uint32_t, sd_radio_session_open(nrf_radio_signal_callback_t p_radio_signal_callback)); /**@brief Closes a session for radio timeslot requests. * @@ -1014,7 +1014,7 @@ SVCALL(SD_FLASH_PAGE_ERASE, uint32_t, sd_flash_page_erase(uint32_t page_number)) * @retval ::NRF_ERROR_BUSY If session is currently being closed. * @retval ::NRF_SUCCESS Otherwise. */ - SVCALL(SD_RADIO_SESSION_CLOSE, uint32_t, sd_radio_session_close(void)); +SVCALL(SD_RADIO_SESSION_CLOSE, uint32_t, sd_radio_session_close(void)); /**@brief Requests a radio timeslot. * @@ -1046,7 +1046,7 @@ SVCALL(SD_FLASH_PAGE_ERASE, uint32_t, sd_flash_page_erase(uint32_t page_number)) * @retval ::NRF_ERROR_INVALID_PARAM If the parameters of p_request are not valid. * @retval ::NRF_SUCCESS Otherwise. */ - SVCALL(SD_RADIO_REQUEST, uint32_t, sd_radio_request(nrf_radio_request_t const * p_request)); +SVCALL(SD_RADIO_REQUEST, uint32_t, sd_radio_request(nrf_radio_request_t const *p_request)); /**@brief Write register protected by the SoftDevice * diff --git a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_svc.h b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_svc.h index 292c692982..e95c298e08 100644 --- a/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_svc.h +++ b/ports/nrf/bluetooth/s140_nrf52_6.1.0/s140_nrf52_6.1.0_API/include/nrf_svc.h @@ -50,33 +50,33 @@ extern "C" { #else #ifndef SVCALL -#if defined (__CC_ARM) +#if defined(__CC_ARM) #define SVCALL(number, return_type, signature) return_type __svc(number) signature -#elif defined (__GNUC__) +#elif defined(__GNUC__) #ifdef __cplusplus #define GCC_CAST_CPP (uint16_t) #else #define GCC_CAST_CPP #endif #define SVCALL(number, return_type, signature) \ - _Pragma("GCC diagnostic push") \ - _Pragma("GCC diagnostic ignored \"-Wreturn-type\"") \ - __attribute__((naked)) \ - __attribute__((unused)) \ - static return_type signature \ - { \ - __asm( \ - "svc %0\n" \ - "bx r14" : : "I" (GCC_CAST_CPP number) : "r0" \ - ); \ - } \ - _Pragma("GCC diagnostic pop") + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wreturn-type\"") \ + __attribute__((naked)) \ + __attribute__((unused)) \ + static return_type signature \ + { \ + __asm( \ + "svc %0\n" \ + "bx r14" : : "I" (GCC_CAST_CPP number) : "r0" \ + ); \ + } \ + _Pragma("GCC diagnostic pop") -#elif defined (__ICCARM__) +#elif defined(__ICCARM__) #define PRAGMA(x) _Pragma(#x) #define SVCALL(number, return_type, signature) \ -PRAGMA(swi_number = (number)) \ - __swi return_type signature; + PRAGMA(swi_number = (number)) \ + __swi return_type signature; #else #define SVCALL(number, return_type, signature) return_type signature #endif diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble.h index d17ac9a596..aa5abd5ef9 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble.h @@ -71,17 +71,17 @@ extern "C" { */ enum BLE_COMMON_SVCS { - SD_BLE_ENABLE = BLE_SVC_BASE, /**< Enable and initialize the BLE stack */ - SD_BLE_EVT_GET, /**< Get an event from the pending events queue. */ - SD_BLE_UUID_VS_ADD, /**< Add a Vendor Specific base UUID. */ - SD_BLE_UUID_DECODE, /**< Decode UUID bytes. */ - SD_BLE_UUID_ENCODE, /**< Encode UUID bytes. */ - SD_BLE_VERSION_GET, /**< Get the local version information (company ID, Link Layer Version, Link Layer Subversion). */ - SD_BLE_USER_MEM_REPLY, /**< User Memory Reply. */ - SD_BLE_OPT_SET, /**< Set a BLE option. */ - SD_BLE_OPT_GET, /**< Get a BLE option. */ - SD_BLE_CFG_SET, /**< Add a configuration to the BLE stack. */ - SD_BLE_UUID_VS_REMOVE, /**< Remove a Vendor Specific base UUID. */ + SD_BLE_ENABLE = BLE_SVC_BASE, /**< Enable and initialize the BLE stack */ + SD_BLE_EVT_GET, /**< Get an event from the pending events queue. */ + SD_BLE_UUID_VS_ADD, /**< Add a Vendor Specific base UUID. */ + SD_BLE_UUID_DECODE, /**< Decode UUID bytes. */ + SD_BLE_UUID_ENCODE, /**< Encode UUID bytes. */ + SD_BLE_VERSION_GET, /**< Get the local version information (company ID, Link Layer Version, Link Layer Subversion). */ + SD_BLE_USER_MEM_REPLY, /**< User Memory Reply. */ + SD_BLE_OPT_SET, /**< Set a BLE option. */ + SD_BLE_OPT_GET, /**< Get a BLE option. */ + SD_BLE_CFG_SET, /**< Add a configuration to the BLE stack. */ + SD_BLE_UUID_VS_REMOVE, /**< Remove a Vendor Specific base UUID. */ }; /** @@ -89,9 +89,9 @@ enum BLE_COMMON_SVCS */ enum BLE_COMMON_EVTS { - BLE_EVT_USER_MEM_REQUEST = BLE_EVT_BASE + 0, /**< User Memory request. See @ref ble_evt_user_mem_request_t + BLE_EVT_USER_MEM_REQUEST = BLE_EVT_BASE + 0, /**< User Memory request. See @ref ble_evt_user_mem_request_t \n Reply with @ref sd_ble_user_mem_reply. */ - BLE_EVT_USER_MEM_RELEASE = BLE_EVT_BASE + 1, /**< User Memory release. See @ref ble_evt_user_mem_release_t */ + BLE_EVT_USER_MEM_RELEASE = BLE_EVT_BASE + 1, /**< User Memory release. See @ref ble_evt_user_mem_release_t */ }; /**@brief BLE Connection Configuration IDs. @@ -113,7 +113,7 @@ enum BLE_CONN_CFGS */ enum BLE_COMMON_CFGS { - BLE_COMMON_CFG_VS_UUID = BLE_CFG_BASE, /**< Vendor specific base UUID configuration */ + BLE_COMMON_CFG_VS_UUID = BLE_CFG_BASE, /**< Vendor specific base UUID configuration */ }; /**@brief Common Option IDs. @@ -121,9 +121,9 @@ enum BLE_COMMON_CFGS */ enum BLE_COMMON_OPTS { - BLE_COMMON_OPT_PA_LNA = BLE_OPT_BASE + 0, /**< PA and LNA options */ - BLE_COMMON_OPT_CONN_EVT_EXT = BLE_OPT_BASE + 1, /**< Extended connection events option */ - BLE_COMMON_OPT_EXTENDED_RC_CAL = BLE_OPT_BASE + 2, /**< Extended RC calibration option */ + BLE_COMMON_OPT_PA_LNA = BLE_OPT_BASE + 0,/**< PA and LNA options */ + BLE_COMMON_OPT_CONN_EVT_EXT = BLE_OPT_BASE + 1,/**< Extended connection events option */ + BLE_COMMON_OPT_EXTENDED_RC_CAL = BLE_OPT_BASE + 2, /**< Extended RC calibration option */ }; /** @} */ @@ -144,8 +144,8 @@ enum BLE_COMMON_OPTS * If that value has not been configured for any connections then @ref BLE_GATT_ATT_MTU_DEFAULT must be used instead. */ #define BLE_EVT_LEN_MAX(ATT_MTU) ( \ - offsetof(ble_evt_t, evt.gattc_evt.params.prim_srvc_disc_rsp.services) + ((ATT_MTU) - 1) / 4 * sizeof(ble_gattc_service_t) \ -) + offsetof(ble_evt_t, evt.gattc_evt.params.prim_srvc_disc_rsp.services) + ((ATT_MTU)-1) / 4 * sizeof(ble_gattc_service_t) \ + ) /** @defgroup BLE_USER_MEM_TYPES User Memory Types * @{ */ @@ -175,53 +175,53 @@ enum BLE_COMMON_OPTS /**@brief User Memory Block. */ typedef struct { - uint8_t *p_mem; /**< Pointer to the start of the user memory block. */ - uint16_t len; /**< Length in bytes of the user memory block. */ + uint8_t *p_mem; /**< Pointer to the start of the user memory block. */ + uint16_t len; /**< Length in bytes of the user memory block. */ } ble_user_mem_block_t; /**@brief Event structure for @ref BLE_EVT_USER_MEM_REQUEST. */ typedef struct { - uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ + uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ } ble_evt_user_mem_request_t; /**@brief Event structure for @ref BLE_EVT_USER_MEM_RELEASE. */ typedef struct { - uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ - ble_user_mem_block_t mem_block; /**< User memory block */ + uint8_t type; /**< User memory type, see @ref BLE_USER_MEM_TYPES. */ + ble_user_mem_block_t mem_block; /**< User memory block */ } ble_evt_user_mem_release_t; /**@brief Event structure for events not associated with a specific function module. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which this event occurred. */ - union - { - ble_evt_user_mem_request_t user_mem_request; /**< User Memory Request Event Parameters. */ - ble_evt_user_mem_release_t user_mem_release; /**< User Memory Release Event Parameters. */ - } params; /**< Event parameter union. */ + uint16_t conn_handle; /**< Connection Handle on which this event occurred. */ + union + { + ble_evt_user_mem_request_t user_mem_request; /**< User Memory Request Event Parameters. */ + ble_evt_user_mem_release_t user_mem_release; /**< User Memory Release Event Parameters. */ + } params; /**< Event parameter union. */ } ble_common_evt_t; /**@brief BLE Event header. */ typedef struct { - uint16_t evt_id; /**< Value from a BLE__EVT series. */ - uint16_t evt_len; /**< Length in octets including this header. */ + uint16_t evt_id; /**< Value from a BLE__EVT series. */ + uint16_t evt_len; /**< Length in octets including this header. */ } ble_evt_hdr_t; /**@brief Common BLE Event type, wrapping the module specific event reports. */ typedef struct { - ble_evt_hdr_t header; /**< Event header. */ - union - { - ble_common_evt_t common_evt; /**< Common Event, evt_id in BLE_EVT_* series. */ - ble_gap_evt_t gap_evt; /**< GAP originated event, evt_id in BLE_GAP_EVT_* series. */ - ble_gattc_evt_t gattc_evt; /**< GATT client originated event, evt_id in BLE_GATTC_EVT* series. */ - ble_gatts_evt_t gatts_evt; /**< GATT server originated event, evt_id in BLE_GATTS_EVT* series. */ - ble_l2cap_evt_t l2cap_evt; /**< L2CAP originated event, evt_id in BLE_L2CAP_EVT* series. */ - } evt; /**< Event union. */ + ble_evt_hdr_t header; /**< Event header. */ + union + { + ble_common_evt_t common_evt; /**< Common Event, evt_id in BLE_EVT_* series. */ + ble_gap_evt_t gap_evt; /**< GAP originated event, evt_id in BLE_GAP_EVT_* series. */ + ble_gattc_evt_t gattc_evt; /**< GATT client originated event, evt_id in BLE_GATTC_EVT* series. */ + ble_gatts_evt_t gatts_evt; /**< GATT server originated event, evt_id in BLE_GATTS_EVT* series. */ + ble_l2cap_evt_t l2cap_evt; /**< L2CAP originated event, evt_id in BLE_L2CAP_EVT* series. */ + } evt; /**< Event union. */ } ble_evt_t; @@ -230,9 +230,9 @@ typedef struct */ typedef struct { - uint8_t version_number; /**< Link Layer Version number. See https://www.bluetooth.org/en-us/specification/assigned-numbers/link-layer for assigned values. */ - uint16_t company_id; /**< Company ID, Nordic Semiconductor's company ID is 89 (0x0059) (https://www.bluetooth.org/apps/content/Default.aspx?doc_id=49708). */ - uint16_t subversion_number; /**< Link Layer Sub Version number, corresponds to the SoftDevice Config ID or Firmware ID (FWID). */ + uint8_t version_number; /**< Link Layer Version number. See https://www.bluetooth.org/en-us/specification/assigned-numbers/link-layer for assigned values. */ + uint16_t company_id; /**< Company ID, Nordic Semiconductor's company ID is 89 (0x0059) (https://www.bluetooth.org/apps/content/Default.aspx?doc_id=49708). */ + uint16_t subversion_number; /**< Link Layer Sub Version number, corresponds to the SoftDevice Config ID or Firmware ID (FWID). */ } ble_version_t; /** @@ -240,9 +240,9 @@ typedef struct */ typedef struct { - uint8_t enable :1; /**< Enable toggling for this amplifier */ - uint8_t active_high :1; /**< Set the pin to be active high */ - uint8_t gpio_pin :6; /**< The GPIO pin to toggle for this amplifier */ + uint8_t enable : 1; /**< Enable toggling for this amplifier */ + uint8_t active_high : 1; /**< Set the pin to be active high */ + uint8_t gpio_pin : 6; /**< The GPIO pin to toggle for this amplifier */ } ble_pa_lna_cfg_t; /** @@ -260,12 +260,12 @@ typedef struct */ typedef struct { - ble_pa_lna_cfg_t pa_cfg; /**< Power Amplifier configuration */ - ble_pa_lna_cfg_t lna_cfg; /**< Low Noise Amplifier configuration */ + ble_pa_lna_cfg_t pa_cfg; /**< Power Amplifier configuration */ + ble_pa_lna_cfg_t lna_cfg; /**< Low Noise Amplifier configuration */ - uint8_t ppi_ch_id_set; /**< PPI channel used for radio pin setting */ - uint8_t ppi_ch_id_clr; /**< PPI channel used for radio pin clearing */ - uint8_t gpiote_ch_id; /**< GPIOTE channel used for radio pin toggling */ + uint8_t ppi_ch_id_set; /**< PPI channel used for radio pin setting */ + uint8_t ppi_ch_id_clr; /**< PPI channel used for radio pin clearing */ + uint8_t gpiote_ch_id; /**< GPIOTE channel used for radio pin toggling */ } ble_common_opt_pa_lna_t; /** @@ -281,7 +281,7 @@ typedef struct */ typedef struct { - uint8_t enable : 1; /**< Enable extended BLE connection events, disabled by default. */ + uint8_t enable : 1; /**< Enable extended BLE connection events, disabled by default. */ } ble_common_opt_conn_evt_ext_t; /** @@ -301,22 +301,22 @@ typedef struct */ typedef struct { - uint8_t enable : 1; /**< Enable extended RC calibration, enabled by default. */ + uint8_t enable : 1; /**< Enable extended RC calibration, enabled by default. */ } ble_common_opt_extended_rc_cal_t; /**@brief Option structure for common options. */ typedef union { - ble_common_opt_pa_lna_t pa_lna; /**< Parameters for controlling PA and LNA pin toggling. */ - ble_common_opt_conn_evt_ext_t conn_evt_ext; /**< Parameters for enabling extended connection events. */ - ble_common_opt_extended_rc_cal_t extended_rc_cal; /**< Parameters for enabling extended RC calibration. */ + ble_common_opt_pa_lna_t pa_lna; /**< Parameters for controlling PA and LNA pin toggling. */ + ble_common_opt_conn_evt_ext_t conn_evt_ext; /**< Parameters for enabling extended connection events. */ + ble_common_opt_extended_rc_cal_t extended_rc_cal; /**< Parameters for enabling extended RC calibration. */ } ble_common_opt_t; /**@brief Common BLE Option type, wrapping the module specific options. */ typedef union { - ble_common_opt_t common_opt; /**< COMMON options, opt_id in @ref BLE_COMMON_OPTS series. */ - ble_gap_opt_t gap_opt; /**< GAP option, opt_id in @ref BLE_GAP_OPTS series. */ + ble_common_opt_t common_opt; /**< COMMON options, opt_id in @ref BLE_COMMON_OPTS series. */ + ble_gap_opt_t gap_opt; /**< GAP option, opt_id in @ref BLE_GAP_OPTS series. */ } ble_opt_t; /**@brief BLE connection configuration type, wrapping the module specific configurations, set with @@ -338,17 +338,17 @@ typedef union */ typedef struct { - uint8_t conn_cfg_tag; /**< The application chosen tag it can use with the + uint8_t conn_cfg_tag; /**< The application chosen tag it can use with the @ref sd_ble_gap_adv_start() and @ref sd_ble_gap_connect() calls to select this configuration when creating a connection. Must be different for all connection configurations added and not @ref BLE_CONN_CFG_TAG_DEFAULT. */ - union { - ble_gap_conn_cfg_t gap_conn_cfg; /**< GAP connection configuration, cfg_id is @ref BLE_CONN_CFG_GAP. */ - ble_gattc_conn_cfg_t gattc_conn_cfg; /**< GATTC connection configuration, cfg_id is @ref BLE_CONN_CFG_GATTC. */ - ble_gatts_conn_cfg_t gatts_conn_cfg; /**< GATTS connection configuration, cfg_id is @ref BLE_CONN_CFG_GATTS. */ - ble_gatt_conn_cfg_t gatt_conn_cfg; /**< GATT connection configuration, cfg_id is @ref BLE_CONN_CFG_GATT. */ - ble_l2cap_conn_cfg_t l2cap_conn_cfg; /**< L2CAP connection configuration, cfg_id is @ref BLE_CONN_CFG_L2CAP. */ - } params; /**< Connection configuration union. */ + union { + ble_gap_conn_cfg_t gap_conn_cfg; /**< GAP connection configuration, cfg_id is @ref BLE_CONN_CFG_GAP. */ + ble_gattc_conn_cfg_t gattc_conn_cfg; /**< GATTC connection configuration, cfg_id is @ref BLE_CONN_CFG_GATTC. */ + ble_gatts_conn_cfg_t gatts_conn_cfg; /**< GATTS connection configuration, cfg_id is @ref BLE_CONN_CFG_GATTS. */ + ble_gatt_conn_cfg_t gatt_conn_cfg; /**< GATT connection configuration, cfg_id is @ref BLE_CONN_CFG_GATT. */ + ble_l2cap_conn_cfg_t l2cap_conn_cfg; /**< L2CAP connection configuration, cfg_id is @ref BLE_CONN_CFG_L2CAP. */ + } params; /**< Connection configuration union. */ } ble_conn_cfg_t; /** @@ -358,7 +358,7 @@ typedef struct */ typedef struct { - uint8_t vs_uuid_count; /**< Number of 128-bit Vendor Specific base UUID bases to allocate memory for. + uint8_t vs_uuid_count; /**< Number of 128-bit Vendor Specific base UUID bases to allocate memory for. Default value is @ref BLE_UUID_VS_COUNT_DEFAULT. Maximum value is @ref BLE_UUID_VS_COUNT_MAX. */ } ble_common_cfg_vs_uuid_t; @@ -366,16 +366,16 @@ typedef struct /**@brief Common BLE Configuration type, wrapping the common configurations. */ typedef union { - ble_common_cfg_vs_uuid_t vs_uuid_cfg; /**< Vendor Specific base UUID configuration, cfg_id is @ref BLE_COMMON_CFG_VS_UUID. */ + ble_common_cfg_vs_uuid_t vs_uuid_cfg; /**< Vendor Specific base UUID configuration, cfg_id is @ref BLE_COMMON_CFG_VS_UUID. */ } ble_common_cfg_t; /**@brief BLE Configuration type, wrapping the module specific configurations. */ typedef union { - ble_conn_cfg_t conn_cfg; /**< Connection specific configurations, cfg_id in @ref BLE_CONN_CFGS series. */ - ble_common_cfg_t common_cfg; /**< Global common configurations, cfg_id in @ref BLE_COMMON_CFGS series. */ - ble_gap_cfg_t gap_cfg; /**< Global GAP configurations, cfg_id in @ref BLE_GAP_CFGS series. */ - ble_gatts_cfg_t gatts_cfg; /**< Global GATTS configuration, cfg_id in @ref BLE_GATTS_CFGS series. */ + ble_conn_cfg_t conn_cfg; /**< Connection specific configurations, cfg_id in @ref BLE_CONN_CFGS series. */ + ble_common_cfg_t common_cfg; /**< Global common configurations, cfg_id in @ref BLE_COMMON_CFGS series. */ + ble_gap_cfg_t gap_cfg; /**< Global GAP configurations, cfg_id in @ref BLE_GAP_CFGS series. */ + ble_gatts_cfg_t gatts_cfg; /**< Global GATTS configuration, cfg_id in @ref BLE_GATTS_CFGS series. */ } ble_cfg_t; /** @} */ @@ -466,7 +466,7 @@ SVCALL(SD_BLE_ENABLE, uint32_t, sd_ble_enable(uint32_t * p_app_ram_base)); * @retval ::NRF_ERROR_NO_MEM The amount of memory assigned to the SoftDevice by app_ram_base is not * large enough to fit this configuration's memory requirement. */ -SVCALL(SD_BLE_CFG_SET, uint32_t, sd_ble_cfg_set(uint32_t cfg_id, ble_cfg_t const * p_cfg, uint32_t app_ram_base)); +SVCALL(SD_BLE_CFG_SET, uint32_t, sd_ble_cfg_set(uint32_t cfg_id, ble_cfg_t const *p_cfg, uint32_t app_ram_base)); /**@brief Get an event from the pending events queue. * @@ -504,7 +504,7 @@ SVCALL(SD_BLE_CFG_SET, uint32_t, sd_ble_cfg_set(uint32_t cfg_id, ble_cfg_t const * @retval ::NRF_ERROR_NOT_FOUND No events ready to be pulled. * @retval ::NRF_ERROR_DATA_SIZE Event ready but could not fit into the supplied buffer. */ -SVCALL(SD_BLE_EVT_GET, uint32_t, sd_ble_evt_get(uint8_t *p_dest, uint16_t *p_len)); +SVCALL(SD_BLE_EVT_GET, uint32_t, sd_ble_evt_get(uint8_t * p_dest, uint16_t * p_len)); /**@brief Add a Vendor Specific base UUID. @@ -533,7 +533,7 @@ SVCALL(SD_BLE_EVT_GET, uint32_t, sd_ble_evt_get(uint8_t *p_dest, uint16_t *p_len * @retval ::NRF_ERROR_INVALID_ADDR If p_vs_uuid or p_uuid_type is NULL or invalid. * @retval ::NRF_ERROR_NO_MEM If there are no more free slots for VS UUIDs. */ -SVCALL(SD_BLE_UUID_VS_ADD, uint32_t, sd_ble_uuid_vs_add(ble_uuid128_t const *p_vs_uuid, uint8_t *p_uuid_type)); +SVCALL(SD_BLE_UUID_VS_ADD, uint32_t, sd_ble_uuid_vs_add(ble_uuid128_t const *p_vs_uuid, uint8_t * p_uuid_type)); /**@brief Remove a Vendor Specific base UUID. @@ -554,7 +554,7 @@ SVCALL(SD_BLE_UUID_VS_ADD, uint32_t, sd_ble_uuid_vs_add(ble_uuid128_t const *p_v * @retval ::NRF_ERROR_INVALID_PARAM If p_uuid_type points to a non-valid UUID type. * @retval ::NRF_ERROR_FORBIDDEN If the Vendor Specific base UUID is in use by the ATT Server. */ -SVCALL(SD_BLE_UUID_VS_REMOVE, uint32_t, sd_ble_uuid_vs_remove(uint8_t *p_uuid_type)); +SVCALL(SD_BLE_UUID_VS_REMOVE, uint32_t, sd_ble_uuid_vs_remove(uint8_t * p_uuid_type)); /** @brief Decode little endian raw UUID bytes (16-bit or 128-bit) into a 24 bit @ref ble_uuid_t structure. @@ -575,7 +575,7 @@ SVCALL(SD_BLE_UUID_VS_REMOVE, uint32_t, sd_ble_uuid_vs_remove(uint8_t *p_uuid_ty * @retval ::NRF_ERROR_INVALID_LENGTH Invalid UUID length. * @retval ::NRF_ERROR_NOT_FOUND For a 128-bit UUID, no match in the populated table of UUIDs. */ -SVCALL(SD_BLE_UUID_DECODE, uint32_t, sd_ble_uuid_decode(uint8_t uuid_le_len, uint8_t const *p_uuid_le, ble_uuid_t *p_uuid)); +SVCALL(SD_BLE_UUID_DECODE, uint32_t, sd_ble_uuid_decode(uint8_t uuid_le_len, uint8_t const *p_uuid_le, ble_uuid_t * p_uuid)); /** @brief Encode a @ref ble_uuid_t structure into little endian raw UUID bytes (16-bit or 128-bit). @@ -590,7 +590,7 @@ SVCALL(SD_BLE_UUID_DECODE, uint32_t, sd_ble_uuid_decode(uint8_t uuid_le_len, uin * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::NRF_ERROR_INVALID_PARAM Invalid UUID type. */ -SVCALL(SD_BLE_UUID_ENCODE, uint32_t, sd_ble_uuid_encode(ble_uuid_t const *p_uuid, uint8_t *p_uuid_le_len, uint8_t *p_uuid_le)); +SVCALL(SD_BLE_UUID_ENCODE, uint32_t, sd_ble_uuid_encode(ble_uuid_t const *p_uuid, uint8_t * p_uuid_le_len, uint8_t * p_uuid_le)); /**@brief Get Version Information. @@ -603,7 +603,7 @@ SVCALL(SD_BLE_UUID_ENCODE, uint32_t, sd_ble_uuid_encode(ble_uuid_t const *p_uuid * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::NRF_ERROR_BUSY The BLE stack is busy (typically doing a locally-initiated disconnection procedure). */ -SVCALL(SD_BLE_VERSION_GET, uint32_t, sd_ble_version_get(ble_version_t *p_version)); +SVCALL(SD_BLE_VERSION_GET, uint32_t, sd_ble_version_get(ble_version_t * p_version)); /**@brief Provide a user memory block. @@ -664,7 +664,7 @@ SVCALL(SD_BLE_OPT_SET, uint32_t, sd_ble_opt_set(uint32_t opt_id, ble_opt_t const * @retval ::NRF_ERROR_NOT_SUPPORTED This option is not supported. * */ -SVCALL(SD_BLE_OPT_GET, uint32_t, sd_ble_opt_get(uint32_t opt_id, ble_opt_t *p_opt)); +SVCALL(SD_BLE_OPT_GET, uint32_t, sd_ble_opt_get(uint32_t opt_id, ble_opt_t * p_opt)); /** @} */ #ifdef __cplusplus diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_err.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_err.h index 1b4820dc3d..64e610a2f2 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_err.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_err.h @@ -62,12 +62,12 @@ extern "C" { /* @defgroup BLE_ERRORS Error Codes * @{ */ -#define BLE_ERROR_NOT_ENABLED (NRF_ERROR_STK_BASE_NUM+0x001) /**< @ref sd_ble_enable has not been called. */ -#define BLE_ERROR_INVALID_CONN_HANDLE (NRF_ERROR_STK_BASE_NUM+0x002) /**< Invalid connection handle. */ -#define BLE_ERROR_INVALID_ATTR_HANDLE (NRF_ERROR_STK_BASE_NUM+0x003) /**< Invalid attribute handle. */ -#define BLE_ERROR_INVALID_ADV_HANDLE (NRF_ERROR_STK_BASE_NUM+0x004) /**< Invalid advertising handle. */ -#define BLE_ERROR_INVALID_ROLE (NRF_ERROR_STK_BASE_NUM+0x005) /**< Invalid role. */ -#define BLE_ERROR_BLOCKED_BY_OTHER_LINKS (NRF_ERROR_STK_BASE_NUM+0x006) /**< The attempt to change link settings failed due to the scheduling of other links. */ +#define BLE_ERROR_NOT_ENABLED (NRF_ERROR_STK_BASE_NUM + 0x001) /**< @ref sd_ble_enable has not been called. */ +#define BLE_ERROR_INVALID_CONN_HANDLE (NRF_ERROR_STK_BASE_NUM + 0x002) /**< Invalid connection handle. */ +#define BLE_ERROR_INVALID_ATTR_HANDLE (NRF_ERROR_STK_BASE_NUM + 0x003) /**< Invalid attribute handle. */ +#define BLE_ERROR_INVALID_ADV_HANDLE (NRF_ERROR_STK_BASE_NUM + 0x004) /**< Invalid advertising handle. */ +#define BLE_ERROR_INVALID_ROLE (NRF_ERROR_STK_BASE_NUM + 0x005) /**< Invalid role. */ +#define BLE_ERROR_BLOCKED_BY_OTHER_LINKS (NRF_ERROR_STK_BASE_NUM + 0x006) /**< The attempt to change link settings failed due to the scheduling of other links. */ /** @} */ @@ -75,10 +75,10 @@ extern "C" { * @brief Assignment of subranges for module specific error codes. * @note For specific error codes, see ble_.h or ble_error_.h. * @{ */ -#define NRF_L2CAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x100) /**< L2CAP specific errors. */ -#define NRF_GAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x200) /**< GAP specific errors. */ -#define NRF_GATTC_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x300) /**< GATT client specific errors. */ -#define NRF_GATTS_ERR_BASE (NRF_ERROR_STK_BASE_NUM+0x400) /**< GATT server specific errors. */ +#define NRF_L2CAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM + 0x100) /**< L2CAP specific errors. */ +#define NRF_GAP_ERR_BASE (NRF_ERROR_STK_BASE_NUM + 0x200) /**< GAP specific errors. */ +#define NRF_GATTC_ERR_BASE (NRF_ERROR_STK_BASE_NUM + 0x300) /**< GATT client specific errors. */ +#define NRF_GATTS_ERR_BASE (NRF_ERROR_STK_BASE_NUM + 0x400) /**< GATT server specific errors. */ /** @} */ #ifdef __cplusplus diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gap.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gap.h index d657fd6c11..3a3ccc4950 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gap.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gap.h @@ -64,49 +64,49 @@ extern "C" { */ enum BLE_GAP_SVCS { - SD_BLE_GAP_ADDR_SET = BLE_GAP_SVC_BASE, /**< Set own Bluetooth Address. */ - SD_BLE_GAP_ADDR_GET = BLE_GAP_SVC_BASE + 1, /**< Get own Bluetooth Address. */ - SD_BLE_GAP_WHITELIST_SET = BLE_GAP_SVC_BASE + 2, /**< Set active whitelist. */ - SD_BLE_GAP_DEVICE_IDENTITIES_SET = BLE_GAP_SVC_BASE + 3, /**< Set device identity list. */ - SD_BLE_GAP_PRIVACY_SET = BLE_GAP_SVC_BASE + 4, /**< Set Privacy settings*/ - SD_BLE_GAP_PRIVACY_GET = BLE_GAP_SVC_BASE + 5, /**< Get Privacy settings*/ - SD_BLE_GAP_ADV_SET_CONFIGURE = BLE_GAP_SVC_BASE + 6, /**< Configure an advertising set. */ - SD_BLE_GAP_ADV_START = BLE_GAP_SVC_BASE + 7, /**< Start Advertising. */ - SD_BLE_GAP_ADV_STOP = BLE_GAP_SVC_BASE + 8, /**< Stop Advertising. */ - SD_BLE_GAP_CONN_PARAM_UPDATE = BLE_GAP_SVC_BASE + 9, /**< Connection Parameter Update. */ - SD_BLE_GAP_DISCONNECT = BLE_GAP_SVC_BASE + 10, /**< Disconnect. */ - SD_BLE_GAP_TX_POWER_SET = BLE_GAP_SVC_BASE + 11, /**< Set TX Power. */ - SD_BLE_GAP_APPEARANCE_SET = BLE_GAP_SVC_BASE + 12, /**< Set Appearance. */ - SD_BLE_GAP_APPEARANCE_GET = BLE_GAP_SVC_BASE + 13, /**< Get Appearance. */ - SD_BLE_GAP_PPCP_SET = BLE_GAP_SVC_BASE + 14, /**< Set PPCP. */ - SD_BLE_GAP_PPCP_GET = BLE_GAP_SVC_BASE + 15, /**< Get PPCP. */ - SD_BLE_GAP_DEVICE_NAME_SET = BLE_GAP_SVC_BASE + 16, /**< Set Device Name. */ - SD_BLE_GAP_DEVICE_NAME_GET = BLE_GAP_SVC_BASE + 17, /**< Get Device Name. */ - SD_BLE_GAP_AUTHENTICATE = BLE_GAP_SVC_BASE + 18, /**< Initiate Pairing/Bonding. */ - SD_BLE_GAP_SEC_PARAMS_REPLY = BLE_GAP_SVC_BASE + 19, /**< Reply with Security Parameters. */ - SD_BLE_GAP_AUTH_KEY_REPLY = BLE_GAP_SVC_BASE + 20, /**< Reply with an authentication key. */ - SD_BLE_GAP_LESC_DHKEY_REPLY = BLE_GAP_SVC_BASE + 21, /**< Reply with an LE Secure Connections DHKey. */ - SD_BLE_GAP_KEYPRESS_NOTIFY = BLE_GAP_SVC_BASE + 22, /**< Notify of a keypress during an authentication procedure. */ - SD_BLE_GAP_LESC_OOB_DATA_GET = BLE_GAP_SVC_BASE + 23, /**< Get the local LE Secure Connections OOB data. */ - SD_BLE_GAP_LESC_OOB_DATA_SET = BLE_GAP_SVC_BASE + 24, /**< Set the remote LE Secure Connections OOB data. */ - SD_BLE_GAP_ENCRYPT = BLE_GAP_SVC_BASE + 25, /**< Initiate encryption procedure. */ - SD_BLE_GAP_SEC_INFO_REPLY = BLE_GAP_SVC_BASE + 26, /**< Reply with Security Information. */ - SD_BLE_GAP_CONN_SEC_GET = BLE_GAP_SVC_BASE + 27, /**< Obtain connection security level. */ - SD_BLE_GAP_RSSI_START = BLE_GAP_SVC_BASE + 28, /**< Start reporting of changes in RSSI. */ - SD_BLE_GAP_RSSI_STOP = BLE_GAP_SVC_BASE + 29, /**< Stop reporting of changes in RSSI. */ - SD_BLE_GAP_SCAN_START = BLE_GAP_SVC_BASE + 30, /**< Start Scanning. */ - SD_BLE_GAP_SCAN_STOP = BLE_GAP_SVC_BASE + 31, /**< Stop Scanning. */ - SD_BLE_GAP_CONNECT = BLE_GAP_SVC_BASE + 32, /**< Connect. */ - SD_BLE_GAP_CONNECT_CANCEL = BLE_GAP_SVC_BASE + 33, /**< Cancel ongoing connection procedure. */ - SD_BLE_GAP_RSSI_GET = BLE_GAP_SVC_BASE + 34, /**< Get the last RSSI sample. */ - SD_BLE_GAP_PHY_UPDATE = BLE_GAP_SVC_BASE + 35, /**< Initiate or respond to a PHY Update Procedure. */ - SD_BLE_GAP_DATA_LENGTH_UPDATE = BLE_GAP_SVC_BASE + 36, /**< Initiate or respond to a Data Length Update Procedure. */ - SD_BLE_GAP_QOS_CHANNEL_SURVEY_START = BLE_GAP_SVC_BASE + 37, /**< Start Quality of Service (QoS) channel survey module. */ - SD_BLE_GAP_QOS_CHANNEL_SURVEY_STOP = BLE_GAP_SVC_BASE + 38, /**< Stop Quality of Service (QoS) channel survey module. */ - SD_BLE_GAP_ADV_ADDR_GET = BLE_GAP_SVC_BASE + 39, /**< Get the Address used on air while Advertising. */ - SD_BLE_GAP_NEXT_CONN_EVT_COUNTER_GET = BLE_GAP_SVC_BASE + 40, /**< Get the next connection event counter. */ - SD_BLE_GAP_CONN_EVT_TRIGGER_START = BLE_GAP_SVC_BASE + 41, /** Start triggering a given task on connection event start. */ - SD_BLE_GAP_CONN_EVT_TRIGGER_STOP = BLE_GAP_SVC_BASE + 42, /** Stop triggering the task configured using @ref sd_ble_gap_conn_evt_trigger_start. */ + SD_BLE_GAP_ADDR_SET = BLE_GAP_SVC_BASE, /**< Set own Bluetooth Address. */ + SD_BLE_GAP_ADDR_GET = BLE_GAP_SVC_BASE + 1, /**< Get own Bluetooth Address. */ + SD_BLE_GAP_WHITELIST_SET = BLE_GAP_SVC_BASE + 2, /**< Set active whitelist. */ + SD_BLE_GAP_DEVICE_IDENTITIES_SET = BLE_GAP_SVC_BASE + 3, /**< Set device identity list. */ + SD_BLE_GAP_PRIVACY_SET = BLE_GAP_SVC_BASE + 4, /**< Set Privacy settings*/ + SD_BLE_GAP_PRIVACY_GET = BLE_GAP_SVC_BASE + 5, /**< Get Privacy settings*/ + SD_BLE_GAP_ADV_SET_CONFIGURE = BLE_GAP_SVC_BASE + 6, /**< Configure an advertising set. */ + SD_BLE_GAP_ADV_START = BLE_GAP_SVC_BASE + 7, /**< Start Advertising. */ + SD_BLE_GAP_ADV_STOP = BLE_GAP_SVC_BASE + 8, /**< Stop Advertising. */ + SD_BLE_GAP_CONN_PARAM_UPDATE = BLE_GAP_SVC_BASE + 9, /**< Connection Parameter Update. */ + SD_BLE_GAP_DISCONNECT = BLE_GAP_SVC_BASE + 10,/**< Disconnect. */ + SD_BLE_GAP_TX_POWER_SET = BLE_GAP_SVC_BASE + 11,/**< Set TX Power. */ + SD_BLE_GAP_APPEARANCE_SET = BLE_GAP_SVC_BASE + 12,/**< Set Appearance. */ + SD_BLE_GAP_APPEARANCE_GET = BLE_GAP_SVC_BASE + 13,/**< Get Appearance. */ + SD_BLE_GAP_PPCP_SET = BLE_GAP_SVC_BASE + 14,/**< Set PPCP. */ + SD_BLE_GAP_PPCP_GET = BLE_GAP_SVC_BASE + 15,/**< Get PPCP. */ + SD_BLE_GAP_DEVICE_NAME_SET = BLE_GAP_SVC_BASE + 16,/**< Set Device Name. */ + SD_BLE_GAP_DEVICE_NAME_GET = BLE_GAP_SVC_BASE + 17,/**< Get Device Name. */ + SD_BLE_GAP_AUTHENTICATE = BLE_GAP_SVC_BASE + 18,/**< Initiate Pairing/Bonding. */ + SD_BLE_GAP_SEC_PARAMS_REPLY = BLE_GAP_SVC_BASE + 19,/**< Reply with Security Parameters. */ + SD_BLE_GAP_AUTH_KEY_REPLY = BLE_GAP_SVC_BASE + 20,/**< Reply with an authentication key. */ + SD_BLE_GAP_LESC_DHKEY_REPLY = BLE_GAP_SVC_BASE + 21,/**< Reply with an LE Secure Connections DHKey. */ + SD_BLE_GAP_KEYPRESS_NOTIFY = BLE_GAP_SVC_BASE + 22,/**< Notify of a keypress during an authentication procedure. */ + SD_BLE_GAP_LESC_OOB_DATA_GET = BLE_GAP_SVC_BASE + 23,/**< Get the local LE Secure Connections OOB data. */ + SD_BLE_GAP_LESC_OOB_DATA_SET = BLE_GAP_SVC_BASE + 24,/**< Set the remote LE Secure Connections OOB data. */ + SD_BLE_GAP_ENCRYPT = BLE_GAP_SVC_BASE + 25,/**< Initiate encryption procedure. */ + SD_BLE_GAP_SEC_INFO_REPLY = BLE_GAP_SVC_BASE + 26,/**< Reply with Security Information. */ + SD_BLE_GAP_CONN_SEC_GET = BLE_GAP_SVC_BASE + 27,/**< Obtain connection security level. */ + SD_BLE_GAP_RSSI_START = BLE_GAP_SVC_BASE + 28,/**< Start reporting of changes in RSSI. */ + SD_BLE_GAP_RSSI_STOP = BLE_GAP_SVC_BASE + 29,/**< Stop reporting of changes in RSSI. */ + SD_BLE_GAP_SCAN_START = BLE_GAP_SVC_BASE + 30,/**< Start Scanning. */ + SD_BLE_GAP_SCAN_STOP = BLE_GAP_SVC_BASE + 31,/**< Stop Scanning. */ + SD_BLE_GAP_CONNECT = BLE_GAP_SVC_BASE + 32,/**< Connect. */ + SD_BLE_GAP_CONNECT_CANCEL = BLE_GAP_SVC_BASE + 33,/**< Cancel ongoing connection procedure. */ + SD_BLE_GAP_RSSI_GET = BLE_GAP_SVC_BASE + 34,/**< Get the last RSSI sample. */ + SD_BLE_GAP_PHY_UPDATE = BLE_GAP_SVC_BASE + 35,/**< Initiate or respond to a PHY Update Procedure. */ + SD_BLE_GAP_DATA_LENGTH_UPDATE = BLE_GAP_SVC_BASE + 36,/**< Initiate or respond to a Data Length Update Procedure. */ + SD_BLE_GAP_QOS_CHANNEL_SURVEY_START = BLE_GAP_SVC_BASE + 37,/**< Start Quality of Service (QoS) channel survey module. */ + SD_BLE_GAP_QOS_CHANNEL_SURVEY_STOP = BLE_GAP_SVC_BASE + 38,/**< Stop Quality of Service (QoS) channel survey module. */ + SD_BLE_GAP_ADV_ADDR_GET = BLE_GAP_SVC_BASE + 39,/**< Get the Address used on air while Advertising. */ + SD_BLE_GAP_NEXT_CONN_EVT_COUNTER_GET = BLE_GAP_SVC_BASE + 40,/**< Get the next connection event counter. */ + SD_BLE_GAP_CONN_EVT_TRIGGER_START = BLE_GAP_SVC_BASE + 41,/** Start triggering a given task on connection event start. */ + SD_BLE_GAP_CONN_EVT_TRIGGER_STOP = BLE_GAP_SVC_BASE + 42,/** Stop triggering the task configured using @ref sd_ble_gap_conn_evt_trigger_start. */ }; /**@brief GAP Event IDs. @@ -114,31 +114,31 @@ enum BLE_GAP_SVCS */ enum BLE_GAP_EVTS { - BLE_GAP_EVT_CONNECTED = BLE_GAP_EVT_BASE, /**< Connected to peer. \n See @ref ble_gap_evt_connected_t */ - BLE_GAP_EVT_DISCONNECTED = BLE_GAP_EVT_BASE + 1, /**< Disconnected from peer. \n See @ref ble_gap_evt_disconnected_t. */ - BLE_GAP_EVT_CONN_PARAM_UPDATE = BLE_GAP_EVT_BASE + 2, /**< Connection Parameters updated. \n See @ref ble_gap_evt_conn_param_update_t. */ - BLE_GAP_EVT_SEC_PARAMS_REQUEST = BLE_GAP_EVT_BASE + 3, /**< Request to provide security parameters. \n Reply with @ref sd_ble_gap_sec_params_reply. \n See @ref ble_gap_evt_sec_params_request_t. */ - BLE_GAP_EVT_SEC_INFO_REQUEST = BLE_GAP_EVT_BASE + 4, /**< Request to provide security information. \n Reply with @ref sd_ble_gap_sec_info_reply. \n See @ref ble_gap_evt_sec_info_request_t. */ - BLE_GAP_EVT_PASSKEY_DISPLAY = BLE_GAP_EVT_BASE + 5, /**< Request to display a passkey to the user. \n In LESC Numeric Comparison, reply with @ref sd_ble_gap_auth_key_reply. \n See @ref ble_gap_evt_passkey_display_t. */ - BLE_GAP_EVT_KEY_PRESSED = BLE_GAP_EVT_BASE + 6, /**< Notification of a keypress on the remote device.\n See @ref ble_gap_evt_key_pressed_t */ - BLE_GAP_EVT_AUTH_KEY_REQUEST = BLE_GAP_EVT_BASE + 7, /**< Request to provide an authentication key. \n Reply with @ref sd_ble_gap_auth_key_reply. \n See @ref ble_gap_evt_auth_key_request_t. */ - BLE_GAP_EVT_LESC_DHKEY_REQUEST = BLE_GAP_EVT_BASE + 8, /**< Request to calculate an LE Secure Connections DHKey. \n Reply with @ref sd_ble_gap_lesc_dhkey_reply. \n See @ref ble_gap_evt_lesc_dhkey_request_t */ - BLE_GAP_EVT_AUTH_STATUS = BLE_GAP_EVT_BASE + 9, /**< Authentication procedure completed with status. \n See @ref ble_gap_evt_auth_status_t. */ - BLE_GAP_EVT_CONN_SEC_UPDATE = BLE_GAP_EVT_BASE + 10, /**< Connection security updated. \n See @ref ble_gap_evt_conn_sec_update_t. */ - BLE_GAP_EVT_TIMEOUT = BLE_GAP_EVT_BASE + 11, /**< Timeout expired. \n See @ref ble_gap_evt_timeout_t. */ - BLE_GAP_EVT_RSSI_CHANGED = BLE_GAP_EVT_BASE + 12, /**< RSSI report. \n See @ref ble_gap_evt_rssi_changed_t. */ - BLE_GAP_EVT_ADV_REPORT = BLE_GAP_EVT_BASE + 13, /**< Advertising report. \n See @ref ble_gap_evt_adv_report_t. */ - BLE_GAP_EVT_SEC_REQUEST = BLE_GAP_EVT_BASE + 14, /**< Security Request. \n Reply with @ref sd_ble_gap_authenticate + BLE_GAP_EVT_CONNECTED = BLE_GAP_EVT_BASE, /**< Connected to peer. \n See @ref ble_gap_evt_connected_t */ + BLE_GAP_EVT_DISCONNECTED = BLE_GAP_EVT_BASE + 1, /**< Disconnected from peer. \n See @ref ble_gap_evt_disconnected_t. */ + BLE_GAP_EVT_CONN_PARAM_UPDATE = BLE_GAP_EVT_BASE + 2, /**< Connection Parameters updated. \n See @ref ble_gap_evt_conn_param_update_t. */ + BLE_GAP_EVT_SEC_PARAMS_REQUEST = BLE_GAP_EVT_BASE + 3, /**< Request to provide security parameters. \n Reply with @ref sd_ble_gap_sec_params_reply. \n See @ref ble_gap_evt_sec_params_request_t. */ + BLE_GAP_EVT_SEC_INFO_REQUEST = BLE_GAP_EVT_BASE + 4, /**< Request to provide security information. \n Reply with @ref sd_ble_gap_sec_info_reply. \n See @ref ble_gap_evt_sec_info_request_t. */ + BLE_GAP_EVT_PASSKEY_DISPLAY = BLE_GAP_EVT_BASE + 5, /**< Request to display a passkey to the user. \n In LESC Numeric Comparison, reply with @ref sd_ble_gap_auth_key_reply. \n See @ref ble_gap_evt_passkey_display_t. */ + BLE_GAP_EVT_KEY_PRESSED = BLE_GAP_EVT_BASE + 6, /**< Notification of a keypress on the remote device.\n See @ref ble_gap_evt_key_pressed_t */ + BLE_GAP_EVT_AUTH_KEY_REQUEST = BLE_GAP_EVT_BASE + 7, /**< Request to provide an authentication key. \n Reply with @ref sd_ble_gap_auth_key_reply. \n See @ref ble_gap_evt_auth_key_request_t. */ + BLE_GAP_EVT_LESC_DHKEY_REQUEST = BLE_GAP_EVT_BASE + 8, /**< Request to calculate an LE Secure Connections DHKey. \n Reply with @ref sd_ble_gap_lesc_dhkey_reply. \n See @ref ble_gap_evt_lesc_dhkey_request_t */ + BLE_GAP_EVT_AUTH_STATUS = BLE_GAP_EVT_BASE + 9, /**< Authentication procedure completed with status. \n See @ref ble_gap_evt_auth_status_t. */ + BLE_GAP_EVT_CONN_SEC_UPDATE = BLE_GAP_EVT_BASE + 10,/**< Connection security updated. \n See @ref ble_gap_evt_conn_sec_update_t. */ + BLE_GAP_EVT_TIMEOUT = BLE_GAP_EVT_BASE + 11,/**< Timeout expired. \n See @ref ble_gap_evt_timeout_t. */ + BLE_GAP_EVT_RSSI_CHANGED = BLE_GAP_EVT_BASE + 12,/**< RSSI report. \n See @ref ble_gap_evt_rssi_changed_t. */ + BLE_GAP_EVT_ADV_REPORT = BLE_GAP_EVT_BASE + 13,/**< Advertising report. \n See @ref ble_gap_evt_adv_report_t. */ + BLE_GAP_EVT_SEC_REQUEST = BLE_GAP_EVT_BASE + 14,/**< Security Request. \n Reply with @ref sd_ble_gap_authenticate \n or with @ref sd_ble_gap_encrypt if required security information is available . \n See @ref ble_gap_evt_sec_request_t. */ - BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 15, /**< Connection Parameter Update Request. \n Reply with @ref sd_ble_gap_conn_param_update. \n See @ref ble_gap_evt_conn_param_update_request_t. */ - BLE_GAP_EVT_SCAN_REQ_REPORT = BLE_GAP_EVT_BASE + 16, /**< Scan request report. \n See @ref ble_gap_evt_scan_req_report_t. */ - BLE_GAP_EVT_PHY_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 17, /**< PHY Update Request. \n Reply with @ref sd_ble_gap_phy_update. \n See @ref ble_gap_evt_phy_update_request_t. */ - BLE_GAP_EVT_PHY_UPDATE = BLE_GAP_EVT_BASE + 18, /**< PHY Update Procedure is complete. \n See @ref ble_gap_evt_phy_update_t. */ - BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 19, /**< Data Length Update Request. \n Reply with @ref sd_ble_gap_data_length_update. \n See @ref ble_gap_evt_data_length_update_request_t. */ - BLE_GAP_EVT_DATA_LENGTH_UPDATE = BLE_GAP_EVT_BASE + 20, /**< LL Data Channel PDU payload length updated. \n See @ref ble_gap_evt_data_length_update_t. */ - BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT = BLE_GAP_EVT_BASE + 21, /**< Channel survey report. \n See @ref ble_gap_evt_qos_channel_survey_report_t. */ - BLE_GAP_EVT_ADV_SET_TERMINATED = BLE_GAP_EVT_BASE + 22, /**< Advertising set terminated. \n See @ref ble_gap_evt_adv_set_terminated_t. */ + BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 15,/**< Connection Parameter Update Request. \n Reply with @ref sd_ble_gap_conn_param_update. \n See @ref ble_gap_evt_conn_param_update_request_t. */ + BLE_GAP_EVT_SCAN_REQ_REPORT = BLE_GAP_EVT_BASE + 16,/**< Scan request report. \n See @ref ble_gap_evt_scan_req_report_t. */ + BLE_GAP_EVT_PHY_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 17,/**< PHY Update Request. \n Reply with @ref sd_ble_gap_phy_update. \n See @ref ble_gap_evt_phy_update_request_t. */ + BLE_GAP_EVT_PHY_UPDATE = BLE_GAP_EVT_BASE + 18,/**< PHY Update Procedure is complete. \n See @ref ble_gap_evt_phy_update_t. */ + BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST = BLE_GAP_EVT_BASE + 19, /**< Data Length Update Request. \n Reply with @ref sd_ble_gap_data_length_update. \n See @ref ble_gap_evt_data_length_update_request_t. */ + BLE_GAP_EVT_DATA_LENGTH_UPDATE = BLE_GAP_EVT_BASE + 20, /**< LL Data Channel PDU payload length updated. \n See @ref ble_gap_evt_data_length_update_t. */ + BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT = BLE_GAP_EVT_BASE + 21, /**< Channel survey report. \n See @ref ble_gap_evt_qos_channel_survey_report_t. */ + BLE_GAP_EVT_ADV_SET_TERMINATED = BLE_GAP_EVT_BASE + 22, /**< Advertising set terminated. \n See @ref ble_gap_evt_adv_set_terminated_t. */ }; /**@brief GAP Option IDs. @@ -146,12 +146,12 @@ enum BLE_GAP_EVTS */ enum BLE_GAP_OPTS { - BLE_GAP_OPT_CH_MAP = BLE_GAP_OPT_BASE, /**< Channel Map. @ref ble_gap_opt_ch_map_t */ - BLE_GAP_OPT_LOCAL_CONN_LATENCY = BLE_GAP_OPT_BASE + 1, /**< Local connection latency. @ref ble_gap_opt_local_conn_latency_t */ - BLE_GAP_OPT_PASSKEY = BLE_GAP_OPT_BASE + 2, /**< Set passkey. @ref ble_gap_opt_passkey_t */ - BLE_GAP_OPT_COMPAT_MODE_1 = BLE_GAP_OPT_BASE + 3, /**< Compatibility mode. @ref ble_gap_opt_compat_mode_1_t */ - BLE_GAP_OPT_AUTH_PAYLOAD_TIMEOUT = BLE_GAP_OPT_BASE + 4, /**< Set Authenticated payload timeout. @ref ble_gap_opt_auth_payload_timeout_t */ - BLE_GAP_OPT_SLAVE_LATENCY_DISABLE = BLE_GAP_OPT_BASE + 5, /**< Disable slave latency. @ref ble_gap_opt_slave_latency_disable_t */ + BLE_GAP_OPT_CH_MAP = BLE_GAP_OPT_BASE, /**< Channel Map. @ref ble_gap_opt_ch_map_t */ + BLE_GAP_OPT_LOCAL_CONN_LATENCY = BLE_GAP_OPT_BASE + 1, /**< Local connection latency. @ref ble_gap_opt_local_conn_latency_t */ + BLE_GAP_OPT_PASSKEY = BLE_GAP_OPT_BASE + 2, /**< Set passkey. @ref ble_gap_opt_passkey_t */ + BLE_GAP_OPT_COMPAT_MODE_1 = BLE_GAP_OPT_BASE + 3, /**< Compatibility mode. @ref ble_gap_opt_compat_mode_1_t */ + BLE_GAP_OPT_AUTH_PAYLOAD_TIMEOUT = BLE_GAP_OPT_BASE + 4, /**< Set Authenticated payload timeout. @ref ble_gap_opt_auth_payload_timeout_t */ + BLE_GAP_OPT_SLAVE_LATENCY_DISABLE = BLE_GAP_OPT_BASE + 5, /**< Disable slave latency. @ref ble_gap_opt_slave_latency_disable_t */ }; /**@brief GAP Configuration IDs. @@ -160,11 +160,11 @@ enum BLE_GAP_OPTS */ enum BLE_GAP_CFGS { - BLE_GAP_CFG_ROLE_COUNT = BLE_GAP_CFG_BASE, /**< Role count configuration. */ - BLE_GAP_CFG_DEVICE_NAME = BLE_GAP_CFG_BASE + 1, /**< Device name configuration. */ - BLE_GAP_CFG_PPCP_INCL_CONFIG = BLE_GAP_CFG_BASE + 2, /**< Peripheral Preferred Connection Parameters characteristic + BLE_GAP_CFG_ROLE_COUNT = BLE_GAP_CFG_BASE, /**< Role count configuration. */ + BLE_GAP_CFG_DEVICE_NAME = BLE_GAP_CFG_BASE + 1,/**< Device name configuration. */ + BLE_GAP_CFG_PPCP_INCL_CONFIG = BLE_GAP_CFG_BASE + 2, /**< Peripheral Preferred Connection Parameters characteristic inclusion configuration. */ - BLE_GAP_CFG_CAR_INCL_CONFIG = BLE_GAP_CFG_BASE + 3, /**< Central Address Resolution characteristic + BLE_GAP_CFG_CAR_INCL_CONFIG = BLE_GAP_CFG_BASE + 3,/**< Central Address Resolution characteristic inclusion configuration. */ }; @@ -172,9 +172,9 @@ enum BLE_GAP_CFGS */ enum BLE_GAP_TX_POWER_ROLES { - BLE_GAP_TX_POWER_ROLE_ADV = 1, /**< Advertiser role. */ - BLE_GAP_TX_POWER_ROLE_SCAN_INIT = 2, /**< Scanner and initiator role. */ - BLE_GAP_TX_POWER_ROLE_CONN = 3, /**< Connection role. */ + BLE_GAP_TX_POWER_ROLE_ADV = 1, /**< Advertiser role. */ + BLE_GAP_TX_POWER_ROLE_SCAN_INIT = 2, /**< Scanner and initiator role. */ + BLE_GAP_TX_POWER_ROLE_CONN = 3, /**< Connection role. */ }; /** @} */ @@ -324,28 +324,28 @@ enum BLE_GAP_TX_POWER_ROLES * @{ */ #define BLE_GAP_ADV_INTERVAL_MIN 0x000020 /**< Minimum Advertising interval in 625 us units, i.e. 20 ms. */ #define BLE_GAP_ADV_INTERVAL_MAX 0x004000 /**< Maximum Advertising interval in 625 us units, i.e. 10.24 s. */ - /**@} */ +/**@} */ /**@defgroup BLE_GAP_SCAN_INTERVALS GAP Scan interval max and min * @{ */ #define BLE_GAP_SCAN_INTERVAL_MIN 0x0004 /**< Minimum Scan interval in 625 us units, i.e. 2.5 ms. */ #define BLE_GAP_SCAN_INTERVAL_MAX 0xFFFF /**< Maximum Scan interval in 625 us units, i.e. 40,959.375 s. */ - /** @} */ +/** @} */ /**@defgroup BLE_GAP_SCAN_WINDOW GAP Scan window max and min * @{ */ #define BLE_GAP_SCAN_WINDOW_MIN 0x0004 /**< Minimum Scan window in 625 us units, i.e. 2.5 ms. */ #define BLE_GAP_SCAN_WINDOW_MAX 0xFFFF /**< Maximum Scan window in 625 us units, i.e. 40,959.375 s. */ - /** @} */ +/** @} */ /**@defgroup BLE_GAP_SCAN_TIMEOUT GAP Scan timeout max and min * @{ */ #define BLE_GAP_SCAN_TIMEOUT_MIN 0x0001 /**< Minimum Scan timeout in 10 ms units, i.e 10 ms. */ #define BLE_GAP_SCAN_TIMEOUT_UNLIMITED 0x0000 /**< Continue to scan forever. */ - /** @} */ +/** @} */ /**@defgroup BLE_GAP_SCAN_BUFFER_SIZE GAP Minimum scanner buffer size * @@ -564,19 +564,19 @@ enum BLE_GAP_TX_POWER_ROLES * See @ref ble_gap_conn_sec_mode_t. * @{ */ /**@brief Set sec_mode pointed to by ptr to have no access rights.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(ptr) do {(ptr)->sm = 0; (ptr)->lv = 0;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_NO_ACCESS(ptr) do {(ptr)->sm = 0; (ptr)->lv = 0;} while (0) /**@brief Set sec_mode pointed to by ptr to require no protection, open link.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_OPEN(ptr) do {(ptr)->sm = 1; (ptr)->lv = 1;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_OPEN(ptr) do {(ptr)->sm = 1; (ptr)->lv = 1;} while (0) /**@brief Set sec_mode pointed to by ptr to require encryption, but no MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 2;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_ENC_NO_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 2;} while (0) /**@brief Set sec_mode pointed to by ptr to require encryption and MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 3;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 3;} while (0) /**@brief Set sec_mode pointed to by ptr to require LESC encryption and MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_LESC_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 4;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_LESC_ENC_WITH_MITM(ptr) do {(ptr)->sm = 1; (ptr)->lv = 4;} while (0) /**@brief Set sec_mode pointed to by ptr to require signing or encryption, no MITM protection needed.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 1;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_NO_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 1;} while (0) /**@brief Set sec_mode pointed to by ptr to require signing or encryption with MITM protection.*/ -#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 2;} while(0) +#define BLE_GAP_CONN_SEC_MODE_SET_SIGNED_WITH_MITM(ptr) do {(ptr)->sm = 2; (ptr)->lv = 2;} while (0) /**@} */ @@ -651,7 +651,7 @@ enum BLE_GAP_TX_POWER_ROLES #define BLE_GAP_QOS_CHANNEL_SURVEY_INTERVAL_CONTINUOUS (0) /**< Continuous channel survey. */ #define BLE_GAP_QOS_CHANNEL_SURVEY_INTERVAL_MIN_US (7500) /**< Minimum channel survey interval in microseconds (7.5 ms). */ #define BLE_GAP_QOS_CHANNEL_SURVEY_INTERVAL_MAX_US (4000000) /**< Maximum channel survey interval in microseconds (4 s). */ - /**@} */ +/**@} */ /** @} */ @@ -683,45 +683,45 @@ enum BLE_GAP_TX_POWER_ROLES /**@brief Advertising event properties. */ typedef struct { - uint8_t type; /**< Advertising type. See @ref BLE_GAP_ADV_TYPES. */ - uint8_t anonymous : 1; /**< Omit advertiser's address from all PDUs. + uint8_t type; /**< Advertising type. See @ref BLE_GAP_ADV_TYPES. */ + uint8_t anonymous : 1;/**< Omit advertiser's address from all PDUs. @note Anonymous advertising is only available for @ref BLE_GAP_ADV_TYPE_EXTENDED_NONCONNECTABLE_NONSCANNABLE_UNDIRECTED and @ref BLE_GAP_ADV_TYPE_EXTENDED_NONCONNECTABLE_NONSCANNABLE_DIRECTED. */ - uint8_t include_tx_power : 1; /**< This feature is not supported on this SoftDevice. */ + uint8_t include_tx_power : 1; /**< This feature is not supported on this SoftDevice. */ } ble_gap_adv_properties_t; /**@brief Advertising report type. */ typedef struct { - uint16_t connectable : 1; /**< Connectable advertising event type. */ - uint16_t scannable : 1; /**< Scannable advertising event type. */ - uint16_t directed : 1; /**< Directed advertising event type. */ - uint16_t scan_response : 1; /**< Received a scan response. */ - uint16_t extended_pdu : 1; /**< Received an extended advertising set. */ - uint16_t status : 2; /**< Data status. See @ref BLE_GAP_ADV_DATA_STATUS. */ - uint16_t reserved : 9; /**< Reserved for future use. */ + uint16_t connectable : 1;/**< Connectable advertising event type. */ + uint16_t scannable : 1;/**< Scannable advertising event type. */ + uint16_t directed : 1;/**< Directed advertising event type. */ + uint16_t scan_response : 1; /**< Received a scan response. */ + uint16_t extended_pdu : 1;/**< Received an extended advertising set. */ + uint16_t status : 2;/**< Data status. See @ref BLE_GAP_ADV_DATA_STATUS. */ + uint16_t reserved : 9;/**< Reserved for future use. */ } ble_gap_adv_report_type_t; /**@brief Advertising Auxiliary Pointer. */ typedef struct { - uint16_t aux_offset; /**< Time offset from the beginning of advertising packet to the auxiliary packet in 100 us units. */ - uint8_t aux_phy; /**< Indicates the PHY on which the auxiliary advertising packet is sent. See @ref BLE_GAP_PHYS. */ + uint16_t aux_offset; /**< Time offset from the beginning of advertising packet to the auxiliary packet in 100 us units. */ + uint8_t aux_phy; /**< Indicates the PHY on which the auxiliary advertising packet is sent. See @ref BLE_GAP_PHYS. */ } ble_gap_aux_pointer_t; /**@brief Bluetooth Low Energy address. */ typedef struct { - uint8_t addr_id_peer : 1; /**< Only valid for peer addresses. + uint8_t addr_id_peer : 1; /**< Only valid for peer addresses. This bit is set by the SoftDevice to indicate whether the address has been resolved from a Resolvable Private Address (when the peer is using privacy). If set to 1, @ref addr and @ref addr_type refer to the identity address of the resolved address. This bit is ignored when a variable of type @ref ble_gap_addr_t is used as input to API functions. */ - uint8_t addr_type : 7; /**< See @ref BLE_GAP_ADDR_TYPES. */ - uint8_t addr[BLE_GAP_ADDR_LEN]; /**< 48-bit address, LSB format. + uint8_t addr_type : 7; /**< See @ref BLE_GAP_ADDR_TYPES. */ + uint8_t addr[BLE_GAP_ADDR_LEN]; /**< 48-bit address, LSB format. @ref addr is not used if @ref addr_type is @ref BLE_GAP_ADDR_TYPE_ANONYMOUS. */ } ble_gap_addr_t; @@ -739,10 +739,10 @@ typedef struct */ typedef struct { - uint16_t min_conn_interval; /**< Minimum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t max_conn_interval; /**< Maximum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t slave_latency; /**< Slave Latency in number of connection events, see @ref BLE_GAP_CP_LIMITS.*/ - uint16_t conn_sup_timeout; /**< Connection Supervision Timeout in 10 ms units, see @ref BLE_GAP_CP_LIMITS.*/ + uint16_t min_conn_interval; /**< Minimum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ + uint16_t max_conn_interval; /**< Maximum Connection Interval in 1.25 ms units, see @ref BLE_GAP_CP_LIMITS.*/ + uint16_t slave_latency; /**< Slave Latency in number of connection events, see @ref BLE_GAP_CP_LIMITS.*/ + uint16_t conn_sup_timeout; /**< Connection Supervision Timeout in 10 ms units, see @ref BLE_GAP_CP_LIMITS.*/ } ble_gap_conn_params_t; @@ -758,8 +758,8 @@ typedef struct */ typedef struct { - uint8_t sm : 4; /**< Security Mode (1 or 2), 0 for no permissions at all. */ - uint8_t lv : 4; /**< Level (1, 2, 3 or 4), 0 for no permissions at all. */ + uint8_t sm : 4; /**< Security Mode (1 or 2), 0 for no permissions at all. */ + uint8_t lv : 4; /**< Level (1, 2, 3 or 4), 0 for no permissions at all. */ } ble_gap_conn_sec_mode_t; @@ -767,14 +767,14 @@ typedef struct /**@brief GAP connection security status.*/ typedef struct { - ble_gap_conn_sec_mode_t sec_mode; /**< Currently active security mode for this connection.*/ - uint8_t encr_key_size; /**< Length of currently active encryption key, 7 to 16 octets (only applicable for bonding procedures). */ + ble_gap_conn_sec_mode_t sec_mode; /**< Currently active security mode for this connection.*/ + uint8_t encr_key_size; /**< Length of currently active encryption key, 7 to 16 octets (only applicable for bonding procedures). */ } ble_gap_conn_sec_t; /**@brief Identity Resolving Key. */ typedef struct { - uint8_t irk[BLE_GAP_SEC_KEY_LEN]; /**< Array containing IRK. */ + uint8_t irk[BLE_GAP_SEC_KEY_LEN]; /**< Array containing IRK. */ } ble_gap_irk_t; @@ -789,8 +789,8 @@ typedef uint8_t ble_gap_ch_mask_t[5]; /**@brief GAP advertising parameters. */ typedef struct { - ble_gap_adv_properties_t properties; /**< The properties of the advertising events. */ - ble_gap_addr_t const *p_peer_addr; /**< Address of a known peer. + ble_gap_adv_properties_t properties; /**< The properties of the advertising events. */ + ble_gap_addr_t const *p_peer_addr; /**< Address of a known peer. @note ble_gap_addr_t::addr_type cannot be @ref BLE_GAP_ADDR_TYPE_ANONYMOUS. - When privacy is enabled and the local device uses @@ -804,16 +804,16 @@ typedef struct in the device identity list, the peer IRK for that device will be used to generate @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE target addresses used in the advertising event PDUs. */ - uint32_t interval; /**< Advertising interval in 625 us units. @sa BLE_GAP_ADV_INTERVALS. + uint32_t interval; /**< Advertising interval in 625 us units. @sa BLE_GAP_ADV_INTERVALS. @note If @ref ble_gap_adv_properties_t::type is set to @ref BLE_GAP_ADV_TYPE_CONNECTABLE_NONSCANNABLE_DIRECTED_HIGH_DUTY_CYCLE advertising, this parameter is ignored. */ - uint16_t duration; /**< Advertising duration in 10 ms units. When timeout is reached, + uint16_t duration; /**< Advertising duration in 10 ms units. When timeout is reached, an event of type @ref BLE_GAP_EVT_ADV_SET_TERMINATED is raised. @sa BLE_GAP_ADV_TIMEOUT_VALUES. @note The SoftDevice will always complete at least one advertising event even if the duration is set too low. */ - uint8_t max_adv_evts; /**< Maximum advertising events that shall be sent prior to disabling + uint8_t max_adv_evts; /**< Maximum advertising events that shall be sent prior to disabling advertising. Setting the value to 0 disables the limitation. When the count of advertising events specified by this parameter (if not 0) is reached, advertising will be automatically stopped @@ -821,17 +821,17 @@ typedef struct @note If @ref ble_gap_adv_properties_t::type is set to @ref BLE_GAP_ADV_TYPE_CONNECTABLE_NONSCANNABLE_DIRECTED_HIGH_DUTY_CYCLE, this parameter is ignored. */ - ble_gap_ch_mask_t channel_mask; /**< Channel mask for primary and secondary advertising channels. + ble_gap_ch_mask_t channel_mask; /**< Channel mask for primary and secondary advertising channels. At least one of the primary channels, that is channel index 37-39, must be used. Masking away secondary advertising channels is not supported. */ - uint8_t filter_policy; /**< Filter Policy. @sa BLE_GAP_ADV_FILTER_POLICIES. */ - uint8_t primary_phy; /**< Indicates the PHY on which the primary advertising channel packets + uint8_t filter_policy; /**< Filter Policy. @sa BLE_GAP_ADV_FILTER_POLICIES. */ + uint8_t primary_phy; /**< Indicates the PHY on which the primary advertising channel packets are transmitted. If set to @ref BLE_GAP_PHY_AUTO, @ref BLE_GAP_PHY_1MBPS will be used. Valid values are @ref BLE_GAP_PHY_1MBPS and @ref BLE_GAP_PHY_CODED. @note The primary_phy shall indicate @ref BLE_GAP_PHY_1MBPS if @ref ble_gap_adv_properties_t::type is not an extended advertising type. */ - uint8_t secondary_phy; /**< Indicates the PHY on which the secondary advertising channel packets + uint8_t secondary_phy; /**< Indicates the PHY on which the secondary advertising channel packets are transmitted. If set to @ref BLE_GAP_PHY_AUTO, @ref BLE_GAP_PHY_1MBPS will be used. Valid values are @@ -841,11 +841,11 @@ typedef struct connection and send AUX_ADV_IND packets on. @note This parameter will be ignored when @ref ble_gap_adv_properties_t::type is not an extended advertising type. */ - uint8_t set_id:4; /**< The advertising set identifier distinguishes this advertising set from other + uint8_t set_id : 4; /**< The advertising set identifier distinguishes this advertising set from other advertising sets transmitted by this and other devices. @note This parameter will be ignored when @ref ble_gap_adv_properties_t::type is not an extended advertising type. */ - uint8_t scan_req_notification:1; /**< Enable scan request notifications for this advertising set. When a + uint8_t scan_req_notification : 1; /**< Enable scan request notifications for this advertising set. When a scan request is received and the scanner address is allowed by the filter policy, @ref BLE_GAP_EVT_SCAN_REQ_REPORT is raised. @note This parameter will be ignored when @@ -866,11 +866,11 @@ typedef struct * To update advertising data while advertising, provide new buffers to @ref sd_ble_gap_adv_set_configure. */ typedef struct { - ble_data_t adv_data; /**< Advertising data. + ble_data_t adv_data; /**< Advertising data. @note Advertising data can only be specified for a @ref ble_gap_adv_properties_t::type that is allowed to contain advertising data. */ - ble_data_t scan_rsp_data; /**< Scan response data. + ble_data_t scan_rsp_data; /**< Scan response data. @note Scan response data can only be specified for a @ref ble_gap_adv_properties_t::type that is scannable. */ @@ -880,11 +880,11 @@ typedef struct /**@brief GAP scanning parameters. */ typedef struct { - uint8_t extended : 1; /**< If 1, the scanner will accept extended advertising packets. + uint8_t extended : 1; /**< If 1, the scanner will accept extended advertising packets. If set to 0, the scanner will not receive advertising packets on secondary advertising channels, and will not be able to receive long advertising PDUs. */ - uint8_t report_incomplete_evts : 1; /**< If 1, events of type @ref ble_gap_evt_adv_report_t may have + uint8_t report_incomplete_evts : 1; /**< If 1, events of type @ref ble_gap_evt_adv_report_t may have @ref ble_gap_adv_report_type_t::status set to @ref BLE_GAP_ADV_DATA_STATUS_INCOMPLETE_MORE_DATA. This parameter is ignored when used with @ref sd_ble_gap_connect @@ -892,13 +892,13 @@ typedef struct advertising event, and is only available for extended scanning, see @ref sd_ble_gap_scan_start. @note This feature is not supported by this SoftDevice. */ - uint8_t active : 1; /**< If 1, perform active scanning by sending scan requests. + uint8_t active : 1; /**< If 1, perform active scanning by sending scan requests. This parameter is ignored when used with @ref sd_ble_gap_connect. */ - uint8_t filter_policy : 2; /**< Scanning filter policy. @sa BLE_GAP_SCAN_FILTER_POLICIES. + uint8_t filter_policy : 2; /**< Scanning filter policy. @sa BLE_GAP_SCAN_FILTER_POLICIES. @note Only @ref BLE_GAP_SCAN_FP_ACCEPT_ALL and @ref BLE_GAP_SCAN_FP_WHITELIST are valid when used with @ref sd_ble_gap_connect */ - uint8_t scan_phys; /**< Bitfield of PHYs to scan on. If set to @ref BLE_GAP_PHY_AUTO, + uint8_t scan_phys; /**< Bitfield of PHYs to scan on. If set to @ref BLE_GAP_PHY_AUTO, scan_phys will default to @ref BLE_GAP_PHY_1MBPS. - If @ref ble_gap_scan_params_t::extended is set to 0, the only supported PHY is @ref BLE_GAP_PHY_1MBPS. @@ -916,13 +916,13 @@ typedef struct PHY will also contain @ref BLE_GAP_PHY_CODED. If the only scan PHY is @ref BLE_GAP_PHY_CODED, the primary scan PHY is @ref BLE_GAP_PHY_CODED only. */ - uint16_t interval; /**< Scan interval in 625 us units. @sa BLE_GAP_SCAN_INTERVALS. */ - uint16_t window; /**< Scan window in 625 us units. @sa BLE_GAP_SCAN_WINDOW. + uint16_t interval; /**< Scan interval in 625 us units. @sa BLE_GAP_SCAN_INTERVALS. */ + uint16_t window; /**< Scan window in 625 us units. @sa BLE_GAP_SCAN_WINDOW. If scan_phys contains both @ref BLE_GAP_PHY_1MBPS and @ref BLE_GAP_PHY_CODED interval shall be larger than or equal to twice the scan window. */ - uint16_t timeout; /**< Scan timeout in 10 ms units. @sa BLE_GAP_SCAN_TIMEOUT. */ - ble_gap_ch_mask_t channel_mask; /**< Channel mask for primary and secondary advertising channels. + uint16_t timeout; /**< Scan timeout in 10 ms units. @sa BLE_GAP_SCAN_TIMEOUT. */ + ble_gap_ch_mask_t channel_mask; /**< Channel mask for primary and secondary advertising channels. At least one of the primary channels, that is channel index 37-39, must be set to 0. Masking away secondary channels is not supported. */ @@ -948,10 +948,10 @@ typedef struct */ typedef struct { - uint8_t privacy_mode; /**< Privacy mode, see @ref BLE_GAP_PRIVACY_MODES. Default is @ref BLE_GAP_PRIVACY_MODE_OFF. */ - uint8_t private_addr_type; /**< The private address type must be either @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE or @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE. */ - uint16_t private_addr_cycle_s; /**< Private address cycle interval in seconds. Providing an address cycle value of 0 will use the default value defined by @ref BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S. */ - ble_gap_irk_t *p_device_irk; /**< When used as input, pointer to IRK structure that will be used as the default IRK. If NULL, the device default IRK will be used. + uint8_t privacy_mode; /**< Privacy mode, see @ref BLE_GAP_PRIVACY_MODES. Default is @ref BLE_GAP_PRIVACY_MODE_OFF. */ + uint8_t private_addr_type; /**< The private address type must be either @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE or @ref BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE. */ + uint16_t private_addr_cycle_s; /**< Private address cycle interval in seconds. Providing an address cycle value of 0 will use the default value defined by @ref BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S. */ + ble_gap_irk_t *p_device_irk; /**< When used as input, pointer to IRK structure that will be used as the default IRK. If NULL, the device default IRK will be used. When used as output, pointer to IRK structure where the current default IRK will be written to. If NULL, this argument is ignored. By default, the default IRK is used to generate random private resolvable addresses for the local device unless instructed otherwise. */ } ble_gap_privacy_params_t; @@ -967,98 +967,98 @@ typedef struct */ typedef struct { - uint8_t tx_phys; /**< Preferred transmit PHYs, see @ref BLE_GAP_PHYS. */ - uint8_t rx_phys; /**< Preferred receive PHYs, see @ref BLE_GAP_PHYS. */ + uint8_t tx_phys; /**< Preferred transmit PHYs, see @ref BLE_GAP_PHYS. */ + uint8_t rx_phys; /**< Preferred receive PHYs, see @ref BLE_GAP_PHYS. */ } ble_gap_phys_t; /** @brief Keys that can be exchanged during a bonding procedure. */ typedef struct { - uint8_t enc : 1; /**< Long Term Key and Master Identification. */ - uint8_t id : 1; /**< Identity Resolving Key and Identity Address Information. */ - uint8_t sign : 1; /**< Connection Signature Resolving Key. */ - uint8_t link : 1; /**< Derive the Link Key from the LTK. */ + uint8_t enc : 1; /**< Long Term Key and Master Identification. */ + uint8_t id : 1; /**< Identity Resolving Key and Identity Address Information. */ + uint8_t sign : 1; /**< Connection Signature Resolving Key. */ + uint8_t link : 1; /**< Derive the Link Key from the LTK. */ } ble_gap_sec_kdist_t; /**@brief GAP security parameters. */ typedef struct { - uint8_t bond : 1; /**< Perform bonding. */ - uint8_t mitm : 1; /**< Enable Man In The Middle protection. */ - uint8_t lesc : 1; /**< Enable LE Secure Connection pairing. */ - uint8_t keypress : 1; /**< Enable generation of keypress notifications. */ - uint8_t io_caps : 3; /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */ - uint8_t oob : 1; /**< The OOB data flag. + uint8_t bond : 1; /**< Perform bonding. */ + uint8_t mitm : 1; /**< Enable Man In The Middle protection. */ + uint8_t lesc : 1; /**< Enable LE Secure Connection pairing. */ + uint8_t keypress : 1; /**< Enable generation of keypress notifications. */ + uint8_t io_caps : 3; /**< IO capabilities, see @ref BLE_GAP_IO_CAPS. */ + uint8_t oob : 1; /**< The OOB data flag. - In LE legacy pairing, this flag is set if a device has out of band authentication data. The OOB method is used if both of the devices have out of band authentication data. - In LE Secure Connections pairing, this flag is set if a device has the peer device's out of band authentication data. The OOB method is used if at least one device has the peer device's OOB data available. */ - uint8_t min_key_size; /**< Minimum encryption key size in octets between 7 and 16. If 0 then not applicable in this instance. */ - uint8_t max_key_size; /**< Maximum encryption key size in octets between min_key_size and 16. */ - ble_gap_sec_kdist_t kdist_own; /**< Key distribution bitmap: keys that the local device will distribute. */ - ble_gap_sec_kdist_t kdist_peer; /**< Key distribution bitmap: keys that the remote device will distribute. */ + uint8_t min_key_size; /**< Minimum encryption key size in octets between 7 and 16. If 0 then not applicable in this instance. */ + uint8_t max_key_size; /**< Maximum encryption key size in octets between min_key_size and 16. */ + ble_gap_sec_kdist_t kdist_own; /**< Key distribution bitmap: keys that the local device will distribute. */ + ble_gap_sec_kdist_t kdist_peer; /**< Key distribution bitmap: keys that the remote device will distribute. */ } ble_gap_sec_params_t; /**@brief GAP Encryption Information. */ typedef struct { - uint8_t ltk[BLE_GAP_SEC_KEY_LEN]; /**< Long Term Key. */ - uint8_t lesc : 1; /**< Key generated using LE Secure Connections. */ - uint8_t auth : 1; /**< Authenticated Key. */ - uint8_t ltk_len : 6; /**< LTK length in octets. */ + uint8_t ltk[BLE_GAP_SEC_KEY_LEN]; /**< Long Term Key. */ + uint8_t lesc : 1; /**< Key generated using LE Secure Connections. */ + uint8_t auth : 1; /**< Authenticated Key. */ + uint8_t ltk_len : 6; /**< LTK length in octets. */ } ble_gap_enc_info_t; /**@brief GAP Master Identification. */ typedef struct { - uint16_t ediv; /**< Encrypted Diversifier. */ - uint8_t rand[BLE_GAP_SEC_RAND_LEN]; /**< Random Number. */ + uint16_t ediv; /**< Encrypted Diversifier. */ + uint8_t rand[BLE_GAP_SEC_RAND_LEN]; /**< Random Number. */ } ble_gap_master_id_t; /**@brief GAP Signing Information. */ typedef struct { - uint8_t csrk[BLE_GAP_SEC_KEY_LEN]; /**< Connection Signature Resolving Key. */ + uint8_t csrk[BLE_GAP_SEC_KEY_LEN]; /**< Connection Signature Resolving Key. */ } ble_gap_sign_info_t; /**@brief GAP LE Secure Connections P-256 Public Key. */ typedef struct { - uint8_t pk[BLE_GAP_LESC_P256_PK_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman P-256 Public Key. Stored in the standard SMP protocol format: {X,Y} both in little-endian. */ + uint8_t pk[BLE_GAP_LESC_P256_PK_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman P-256 Public Key. Stored in the standard SMP protocol format: {X,Y} both in little-endian. */ } ble_gap_lesc_p256_pk_t; /**@brief GAP LE Secure Connections DHKey. */ typedef struct { - uint8_t key[BLE_GAP_LESC_DHKEY_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman Key. Stored in little-endian. */ + uint8_t key[BLE_GAP_LESC_DHKEY_LEN]; /**< LE Secure Connections Elliptic Curve Diffie-Hellman Key. Stored in little-endian. */ } ble_gap_lesc_dhkey_t; /**@brief GAP LE Secure Connections OOB data. */ typedef struct { - ble_gap_addr_t addr; /**< Bluetooth address of the device. */ - uint8_t r[BLE_GAP_SEC_KEY_LEN]; /**< Random Number. */ - uint8_t c[BLE_GAP_SEC_KEY_LEN]; /**< Confirm Value. */ + ble_gap_addr_t addr; /**< Bluetooth address of the device. */ + uint8_t r[BLE_GAP_SEC_KEY_LEN]; /**< Random Number. */ + uint8_t c[BLE_GAP_SEC_KEY_LEN]; /**< Confirm Value. */ } ble_gap_lesc_oob_data_t; /**@brief Event structure for @ref BLE_GAP_EVT_CONNECTED. */ typedef struct { - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 + ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 and the address is the device's identity address. */ - uint8_t role; /**< BLE role for this connection, see @ref BLE_GAP_ROLES */ - ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ - uint8_t adv_handle; /**< Advertising handle in which advertising has ended. + uint8_t role; /**< BLE role for this connection, see @ref BLE_GAP_ROLES */ + ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ + uint8_t adv_handle; /**< Advertising handle in which advertising has ended. This variable is only set if role is set to @ref BLE_GAP_ROLE_PERIPH. */ - ble_gap_adv_data_t adv_data; /**< Advertising buffers corresponding to the terminated + ble_gap_adv_data_t adv_data; /**< Advertising buffers corresponding to the terminated advertising set. The advertising buffers provided in @ref sd_ble_gap_adv_set_configure are now released. This variable is only set if role is set to @ref BLE_GAP_ROLE_PERIPH. */ @@ -1068,53 +1068,53 @@ typedef struct /**@brief Event structure for @ref BLE_GAP_EVT_DISCONNECTED. */ typedef struct { - uint8_t reason; /**< HCI error code, see @ref BLE_HCI_STATUS_CODES. */ + uint8_t reason; /**< HCI error code, see @ref BLE_HCI_STATUS_CODES. */ } ble_gap_evt_disconnected_t; /**@brief Event structure for @ref BLE_GAP_EVT_CONN_PARAM_UPDATE. */ typedef struct { - ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ + ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ } ble_gap_evt_conn_param_update_t; /**@brief Event structure for @ref BLE_GAP_EVT_PHY_UPDATE_REQUEST. */ typedef struct { - ble_gap_phys_t peer_preferred_phys; /**< The PHYs the peer prefers to use. */ + ble_gap_phys_t peer_preferred_phys; /**< The PHYs the peer prefers to use. */ } ble_gap_evt_phy_update_request_t; /**@brief Event Structure for @ref BLE_GAP_EVT_PHY_UPDATE. */ typedef struct { - uint8_t status; /**< Status of the procedure, see @ref BLE_HCI_STATUS_CODES.*/ - uint8_t tx_phy; /**< TX PHY for this connection, see @ref BLE_GAP_PHYS. */ - uint8_t rx_phy; /**< RX PHY for this connection, see @ref BLE_GAP_PHYS. */ + uint8_t status; /**< Status of the procedure, see @ref BLE_HCI_STATUS_CODES.*/ + uint8_t tx_phy; /**< TX PHY for this connection, see @ref BLE_GAP_PHYS. */ + uint8_t rx_phy; /**< RX PHY for this connection, see @ref BLE_GAP_PHYS. */ } ble_gap_evt_phy_update_t; /**@brief Event structure for @ref BLE_GAP_EVT_SEC_PARAMS_REQUEST. */ typedef struct { - ble_gap_sec_params_t peer_params; /**< Initiator Security Parameters. */ + ble_gap_sec_params_t peer_params; /**< Initiator Security Parameters. */ } ble_gap_evt_sec_params_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_SEC_INFO_REQUEST. */ typedef struct { - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. */ - ble_gap_master_id_t master_id; /**< Master Identification for LTK lookup. */ - uint8_t enc_info : 1; /**< If 1, Encryption Information required. */ - uint8_t id_info : 1; /**< If 1, Identity Information required. */ - uint8_t sign_info : 1; /**< If 1, Signing Information required. */ + ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. */ + ble_gap_master_id_t master_id; /**< Master Identification for LTK lookup. */ + uint8_t enc_info : 1; /**< If 1, Encryption Information required. */ + uint8_t id_info : 1; /**< If 1, Identity Information required. */ + uint8_t sign_info : 1; /**< If 1, Signing Information required. */ } ble_gap_evt_sec_info_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_PASSKEY_DISPLAY. */ typedef struct { - uint8_t passkey[BLE_GAP_PASSKEY_LEN]; /**< 6-digit passkey in ASCII ('0'-'9' digits only). */ - uint8_t match_request : 1; /**< If 1 requires the application to report the match using @ref sd_ble_gap_auth_key_reply + uint8_t passkey[BLE_GAP_PASSKEY_LEN]; /**< 6-digit passkey in ASCII ('0'-'9' digits only). */ + uint8_t match_request : 1; /**< If 1 requires the application to report the match using @ref sd_ble_gap_auth_key_reply with either @ref BLE_GAP_AUTH_KEY_TYPE_NONE if there is no match or @ref BLE_GAP_AUTH_KEY_TYPE_PASSKEY if there is a match. */ } ble_gap_evt_passkey_display_t; @@ -1122,22 +1122,22 @@ typedef struct /**@brief Event structure for @ref BLE_GAP_EVT_KEY_PRESSED. */ typedef struct { - uint8_t kp_not; /**< Keypress notification type, see @ref BLE_GAP_KP_NOT_TYPES. */ + uint8_t kp_not; /**< Keypress notification type, see @ref BLE_GAP_KP_NOT_TYPES. */ } ble_gap_evt_key_pressed_t; /**@brief Event structure for @ref BLE_GAP_EVT_AUTH_KEY_REQUEST. */ typedef struct { - uint8_t key_type; /**< See @ref BLE_GAP_AUTH_KEY_TYPES. */ + uint8_t key_type; /**< See @ref BLE_GAP_AUTH_KEY_TYPES. */ } ble_gap_evt_auth_key_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_LESC_DHKEY_REQUEST. */ typedef struct { - ble_gap_lesc_p256_pk_t *p_pk_peer; /**< LE Secure Connections remote P-256 Public Key. This will point to the application-supplied memory + ble_gap_lesc_p256_pk_t *p_pk_peer; /**< LE Secure Connections remote P-256 Public Key. This will point to the application-supplied memory inside the keyset during the call to @ref sd_ble_gap_sec_params_reply. */ - uint8_t oobd_req :1; /**< LESC OOB data required. A call to @ref sd_ble_gap_lesc_oob_data_set is required to complete the procedure. */ + uint8_t oobd_req : 1; /**< LESC OOB data required. A call to @ref sd_ble_gap_lesc_oob_data_set is required to complete the procedure. */ } ble_gap_evt_lesc_dhkey_request_t; @@ -1146,36 +1146,36 @@ typedef struct */ typedef struct { - uint8_t lv1 : 1; /**< If 1: Level 1 is supported. */ - uint8_t lv2 : 1; /**< If 1: Level 2 is supported. */ - uint8_t lv3 : 1; /**< If 1: Level 3 is supported. */ - uint8_t lv4 : 1; /**< If 1: Level 4 is supported. */ + uint8_t lv1 : 1; /**< If 1: Level 1 is supported. */ + uint8_t lv2 : 1; /**< If 1: Level 2 is supported. */ + uint8_t lv3 : 1; /**< If 1: Level 3 is supported. */ + uint8_t lv4 : 1; /**< If 1: Level 4 is supported. */ } ble_gap_sec_levels_t; /**@brief Encryption Key. */ typedef struct { - ble_gap_enc_info_t enc_info; /**< Encryption Information. */ - ble_gap_master_id_t master_id; /**< Master Identification. */ + ble_gap_enc_info_t enc_info; /**< Encryption Information. */ + ble_gap_master_id_t master_id; /**< Master Identification. */ } ble_gap_enc_key_t; /**@brief Identity Key. */ typedef struct { - ble_gap_irk_t id_info; /**< Identity Resolving Key. */ - ble_gap_addr_t id_addr_info; /**< Identity Address. */ + ble_gap_irk_t id_info; /**< Identity Resolving Key. */ + ble_gap_addr_t id_addr_info; /**< Identity Address. */ } ble_gap_id_key_t; /**@brief Security Keys. */ typedef struct { - ble_gap_enc_key_t *p_enc_key; /**< Encryption Key, or NULL. */ - ble_gap_id_key_t *p_id_key; /**< Identity Key, or NULL. */ - ble_gap_sign_info_t *p_sign_key; /**< Signing Key, or NULL. */ - ble_gap_lesc_p256_pk_t *p_pk; /**< LE Secure Connections P-256 Public Key. When in debug mode the application must use the value defined + ble_gap_enc_key_t *p_enc_key; /**< Encryption Key, or NULL. */ + ble_gap_id_key_t *p_id_key; /**< Identity Key, or NULL. */ + ble_gap_sign_info_t *p_sign_key; /**< Signing Key, or NULL. */ + ble_gap_lesc_p256_pk_t *p_pk; /**< LE Secure Connections P-256 Public Key. When in debug mode the application must use the value defined in the Core Bluetooth Specification v4.2 Vol.3, Part H, Section 2.3.5.6.1 */ } ble_gap_sec_keys_t; @@ -1183,80 +1183,80 @@ typedef struct /**@brief Security key set for both local and peer keys. */ typedef struct { - ble_gap_sec_keys_t keys_own; /**< Keys distributed by the local device. For LE Secure Connections the encryption key will be generated locally and will always be stored if bonding. */ - ble_gap_sec_keys_t keys_peer; /**< Keys distributed by the remote device. For LE Secure Connections, p_enc_key must always be NULL. */ + ble_gap_sec_keys_t keys_own; /**< Keys distributed by the local device. For LE Secure Connections the encryption key will be generated locally and will always be stored if bonding. */ + ble_gap_sec_keys_t keys_peer; /**< Keys distributed by the remote device. For LE Secure Connections, p_enc_key must always be NULL. */ } ble_gap_sec_keyset_t; /**@brief Data Length Update Procedure parameters. */ typedef struct { - uint16_t max_tx_octets; /**< Maximum number of payload octets that a Controller supports for transmission of a single Link Layer Data Channel PDU. */ - uint16_t max_rx_octets; /**< Maximum number of payload octets that a Controller supports for reception of a single Link Layer Data Channel PDU. */ - uint16_t max_tx_time_us; /**< Maximum time, in microseconds, that a Controller supports for transmission of a single Link Layer Data Channel PDU. */ - uint16_t max_rx_time_us; /**< Maximum time, in microseconds, that a Controller supports for reception of a single Link Layer Data Channel PDU. */ + uint16_t max_tx_octets; /**< Maximum number of payload octets that a Controller supports for transmission of a single Link Layer Data Channel PDU. */ + uint16_t max_rx_octets; /**< Maximum number of payload octets that a Controller supports for reception of a single Link Layer Data Channel PDU. */ + uint16_t max_tx_time_us; /**< Maximum time, in microseconds, that a Controller supports for transmission of a single Link Layer Data Channel PDU. */ + uint16_t max_rx_time_us; /**< Maximum time, in microseconds, that a Controller supports for reception of a single Link Layer Data Channel PDU. */ } ble_gap_data_length_params_t; /**@brief Data Length Update Procedure local limitation. */ typedef struct { - uint16_t tx_payload_limited_octets; /**< If > 0, the requested TX packet length is too long by this many octets. */ - uint16_t rx_payload_limited_octets; /**< If > 0, the requested RX packet length is too long by this many octets. */ - uint16_t tx_rx_time_limited_us; /**< If > 0, the requested combination of TX and RX packet lengths is too long by this many microseconds. */ + uint16_t tx_payload_limited_octets; /**< If > 0, the requested TX packet length is too long by this many octets. */ + uint16_t rx_payload_limited_octets; /**< If > 0, the requested RX packet length is too long by this many octets. */ + uint16_t tx_rx_time_limited_us; /**< If > 0, the requested combination of TX and RX packet lengths is too long by this many microseconds. */ } ble_gap_data_length_limitation_t; /**@brief Event structure for @ref BLE_GAP_EVT_AUTH_STATUS. */ typedef struct { - uint8_t auth_status; /**< Authentication status, see @ref BLE_GAP_SEC_STATUS. */ - uint8_t error_src : 2; /**< On error, source that caused the failure, see @ref BLE_GAP_SEC_STATUS_SOURCES. */ - uint8_t bonded : 1; /**< Procedure resulted in a bond. */ - uint8_t lesc : 1; /**< Procedure resulted in a LE Secure Connection. */ - ble_gap_sec_levels_t sm1_levels; /**< Levels supported in Security Mode 1. */ - ble_gap_sec_levels_t sm2_levels; /**< Levels supported in Security Mode 2. */ - ble_gap_sec_kdist_t kdist_own; /**< Bitmap stating which keys were exchanged (distributed) by the local device. If bonding with LE Secure Connections, the enc bit will be always set. */ - ble_gap_sec_kdist_t kdist_peer; /**< Bitmap stating which keys were exchanged (distributed) by the remote device. If bonding with LE Secure Connections, the enc bit will never be set. */ + uint8_t auth_status; /**< Authentication status, see @ref BLE_GAP_SEC_STATUS. */ + uint8_t error_src : 2; /**< On error, source that caused the failure, see @ref BLE_GAP_SEC_STATUS_SOURCES. */ + uint8_t bonded : 1; /**< Procedure resulted in a bond. */ + uint8_t lesc : 1; /**< Procedure resulted in a LE Secure Connection. */ + ble_gap_sec_levels_t sm1_levels; /**< Levels supported in Security Mode 1. */ + ble_gap_sec_levels_t sm2_levels; /**< Levels supported in Security Mode 2. */ + ble_gap_sec_kdist_t kdist_own; /**< Bitmap stating which keys were exchanged (distributed) by the local device. If bonding with LE Secure Connections, the enc bit will be always set. */ + ble_gap_sec_kdist_t kdist_peer; /**< Bitmap stating which keys were exchanged (distributed) by the remote device. If bonding with LE Secure Connections, the enc bit will never be set. */ } ble_gap_evt_auth_status_t; /**@brief Event structure for @ref BLE_GAP_EVT_CONN_SEC_UPDATE. */ typedef struct { - ble_gap_conn_sec_t conn_sec; /**< Connection security level. */ + ble_gap_conn_sec_t conn_sec; /**< Connection security level. */ } ble_gap_evt_conn_sec_update_t; /**@brief Event structure for @ref BLE_GAP_EVT_TIMEOUT. */ typedef struct { - uint8_t src; /**< Source of timeout event, see @ref BLE_GAP_TIMEOUT_SOURCES. */ - union - { - ble_data_t adv_report_buffer; /**< If source is set to @ref BLE_GAP_TIMEOUT_SRC_SCAN, the released + uint8_t src; /**< Source of timeout event, see @ref BLE_GAP_TIMEOUT_SOURCES. */ + union + { + ble_data_t adv_report_buffer; /**< If source is set to @ref BLE_GAP_TIMEOUT_SRC_SCAN, the released scan buffer is contained in this field. */ - } params; /**< Event Parameters. */ + } params; /**< Event Parameters. */ } ble_gap_evt_timeout_t; /**@brief Event structure for @ref BLE_GAP_EVT_RSSI_CHANGED. */ typedef struct { - int8_t rssi; /**< Received Signal Strength Indication in dBm. + int8_t rssi; /**< Received Signal Strength Indication in dBm. @note ERRATA-153 and ERRATA-225 require the rssi sample to be compensated based on a temperature measurement. */ - uint8_t ch_index; /**< Data Channel Index on which the Signal Strength is measured (0-36). */ + uint8_t ch_index; /**< Data Channel Index on which the Signal Strength is measured (0-36). */ } ble_gap_evt_rssi_changed_t; /**@brief Event structure for @ref BLE_GAP_EVT_ADV_SET_TERMINATED */ typedef struct { - uint8_t reason; /**< Reason for why the advertising set terminated. See + uint8_t reason; /**< Reason for why the advertising set terminated. See @ref BLE_GAP_EVT_ADV_SET_TERMINATED_REASON. */ - uint8_t adv_handle; /**< Advertising handle in which advertising has ended. */ - uint8_t num_completed_adv_events; /**< If @ref ble_gap_adv_params_t::max_adv_evts was not set to 0, + uint8_t adv_handle; /**< Advertising handle in which advertising has ended. */ + uint8_t num_completed_adv_events; /**< If @ref ble_gap_adv_params_t::max_adv_evts was not set to 0, this field indicates the number of completed advertising events. */ - ble_gap_adv_data_t adv_data; /**< Advertising buffers corresponding to the terminated + ble_gap_adv_data_t adv_data; /**< Advertising buffers corresponding to the terminated advertising set. The advertising buffers provided in @ref sd_ble_gap_adv_set_configure are now released. */ } ble_gap_evt_adv_set_terminated_t; @@ -1271,11 +1271,11 @@ typedef struct */ typedef struct { - ble_gap_adv_report_type_t type; /**< Advertising report type. See @ref ble_gap_adv_report_type_t. */ - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr is resolved: + ble_gap_adv_report_type_t type; /**< Advertising report type. See @ref ble_gap_adv_report_type_t. */ + ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr is resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 and the address is the peer's identity address. */ - ble_gap_addr_t direct_addr; /**< Contains the target address of the advertising event if + ble_gap_addr_t direct_addr; /**< Contains the target address of the advertising event if @ref ble_gap_adv_report_type_t::directed is set to 1. If the SoftDevice was able to resolve the address, @ref ble_gap_addr_t::addr_id_peer is set to 1 and the direct_addr @@ -1284,28 +1284,28 @@ typedef struct and the SoftDevice was unable to resolve it, the application may try to resolve this address to find out if the advertising event was directed to us. */ - uint8_t primary_phy; /**< Indicates the PHY on which the primary advertising packet was received. + uint8_t primary_phy; /**< Indicates the PHY on which the primary advertising packet was received. See @ref BLE_GAP_PHYS. */ - uint8_t secondary_phy; /**< Indicates the PHY on which the secondary advertising packet was received. + uint8_t secondary_phy; /**< Indicates the PHY on which the secondary advertising packet was received. See @ref BLE_GAP_PHYS. This field is set to @ref BLE_GAP_PHY_NOT_SET if no packets were received on a secondary advertising channel. */ - int8_t tx_power; /**< TX Power reported by the advertiser in the last packet header received. + int8_t tx_power; /**< TX Power reported by the advertiser in the last packet header received. This field is set to @ref BLE_GAP_POWER_LEVEL_INVALID if the last received packet did not contain the Tx Power field. @note TX Power is only included in extended advertising packets. */ - int8_t rssi; /**< Received Signal Strength Indication in dBm of the last packet received. + int8_t rssi; /**< Received Signal Strength Indication in dBm of the last packet received. @note ERRATA-153 and ERRATA-225 require the rssi sample to be compensated based on a temperature measurement. */ - uint8_t ch_index; /**< Channel Index on which the last advertising packet is received (0-39). */ - uint8_t set_id; /**< Set ID of the received advertising data. Set ID is not present + uint8_t ch_index; /**< Channel Index on which the last advertising packet is received (0-39). */ + uint8_t set_id; /**< Set ID of the received advertising data. Set ID is not present if set to @ref BLE_GAP_ADV_REPORT_SET_ID_NOT_AVAILABLE. */ - uint16_t data_id:12; /**< The advertising data ID of the received advertising data. Data ID + uint16_t data_id : 12; /**< The advertising data ID of the received advertising data. Data ID is not present if @ref ble_gap_evt_adv_report_t::set_id is set to @ref BLE_GAP_ADV_REPORT_SET_ID_NOT_AVAILABLE. */ - ble_data_t data; /**< Received advertising or scan response data. If + ble_data_t data; /**< Received advertising or scan response data. If @ref ble_gap_adv_report_type_t::status is not set to @ref BLE_GAP_ADV_DATA_STATUS_INCOMPLETE_MORE_DATA, the data buffer provided in @ref sd_ble_gap_scan_start is now released. */ - ble_gap_aux_pointer_t aux_pointer; /**< The offset and PHY of the next advertising packet in this extended advertising + ble_gap_aux_pointer_t aux_pointer; /**< The offset and PHY of the next advertising packet in this extended advertising event. @note This field is only set if @ref ble_gap_adv_report_type_t::status is set to @ref BLE_GAP_ADV_DATA_STATUS_INCOMPLETE_MORE_DATA. */ } ble_gap_evt_adv_report_t; @@ -1314,27 +1314,27 @@ typedef struct /**@brief Event structure for @ref BLE_GAP_EVT_SEC_REQUEST. */ typedef struct { - uint8_t bond : 1; /**< Perform bonding. */ - uint8_t mitm : 1; /**< Man In The Middle protection requested. */ - uint8_t lesc : 1; /**< LE Secure Connections requested. */ - uint8_t keypress : 1; /**< Generation of keypress notifications requested. */ + uint8_t bond : 1; /**< Perform bonding. */ + uint8_t mitm : 1; /**< Man In The Middle protection requested. */ + uint8_t lesc : 1; /**< LE Secure Connections requested. */ + uint8_t keypress : 1; /**< Generation of keypress notifications requested. */ } ble_gap_evt_sec_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST. */ typedef struct { - ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ + ble_gap_conn_params_t conn_params; /**< GAP Connection Parameters. */ } ble_gap_evt_conn_param_update_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_SCAN_REQ_REPORT. */ typedef struct { - uint8_t adv_handle; /**< Advertising handle for the advertising set which received the Scan Request */ - int8_t rssi; /**< Received Signal Strength Indication in dBm. + uint8_t adv_handle; /**< Advertising handle for the advertising set which received the Scan Request */ + int8_t rssi; /**< Received Signal Strength Indication in dBm. @note ERRATA-153 and ERRATA-225 require the rssi sample to be compensated based on a temperature measurement. */ - ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 + ble_gap_addr_t peer_addr; /**< Bluetooth address of the peer device. If the peer_addr resolved: @ref ble_gap_addr_t::addr_id_peer is set to 1 and the address is the device's identity address. */ } ble_gap_evt_scan_req_report_t; @@ -1342,7 +1342,7 @@ typedef struct /**@brief Event structure for @ref BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST. */ typedef struct { - ble_gap_data_length_params_t peer_params; /**< Peer data length parameters. */ + ble_gap_data_length_params_t peer_params; /**< Peer data length parameters. */ } ble_gap_evt_data_length_update_request_t; /**@brief Event structure for @ref BLE_GAP_EVT_DATA_LENGTH_UPDATE. @@ -1351,14 +1351,14 @@ typedef struct */ typedef struct { - ble_gap_data_length_params_t effective_params; /**< The effective data length parameters. */ + ble_gap_data_length_params_t effective_params; /**< The effective data length parameters. */ } ble_gap_evt_data_length_update_t; /**@brief Event structure for @ref BLE_GAP_EVT_QOS_CHANNEL_SURVEY_REPORT. */ typedef struct { - int8_t channel_energy[BLE_GAP_CHANNEL_COUNT]; /**< The measured energy on the Bluetooth Low Energy + int8_t channel_energy[BLE_GAP_CHANNEL_COUNT]; /**< The measured energy on the Bluetooth Low Energy channels, in dBm, indexed by Channel Index. If no measurement is available for the given channel, channel_energy is set to @ref BLE_GAP_POWER_LEVEL_INVALID. */ @@ -1367,33 +1367,33 @@ typedef struct /**@brief GAP event structure. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which event occurred. */ - union /**< union alternative identified by evt_id in enclosing struct. */ - { - ble_gap_evt_connected_t connected; /**< Connected Event Parameters. */ - ble_gap_evt_disconnected_t disconnected; /**< Disconnected Event Parameters. */ - ble_gap_evt_conn_param_update_t conn_param_update; /**< Connection Parameter Update Parameters. */ - ble_gap_evt_sec_params_request_t sec_params_request; /**< Security Parameters Request Event Parameters. */ - ble_gap_evt_sec_info_request_t sec_info_request; /**< Security Information Request Event Parameters. */ - ble_gap_evt_passkey_display_t passkey_display; /**< Passkey Display Event Parameters. */ - ble_gap_evt_key_pressed_t key_pressed; /**< Key Pressed Event Parameters. */ - ble_gap_evt_auth_key_request_t auth_key_request; /**< Authentication Key Request Event Parameters. */ - ble_gap_evt_lesc_dhkey_request_t lesc_dhkey_request; /**< LE Secure Connections DHKey calculation request. */ - ble_gap_evt_auth_status_t auth_status; /**< Authentication Status Event Parameters. */ - ble_gap_evt_conn_sec_update_t conn_sec_update; /**< Connection Security Update Event Parameters. */ - ble_gap_evt_timeout_t timeout; /**< Timeout Event Parameters. */ - ble_gap_evt_rssi_changed_t rssi_changed; /**< RSSI Event Parameters. */ - ble_gap_evt_adv_report_t adv_report; /**< Advertising Report Event Parameters. */ - ble_gap_evt_adv_set_terminated_t adv_set_terminated; /**< Advertising Set Terminated Event Parameters. */ - ble_gap_evt_sec_request_t sec_request; /**< Security Request Event Parameters. */ - ble_gap_evt_conn_param_update_request_t conn_param_update_request; /**< Connection Parameter Update Parameters. */ - ble_gap_evt_scan_req_report_t scan_req_report; /**< Scan Request Report Parameters. */ - ble_gap_evt_phy_update_request_t phy_update_request; /**< PHY Update Request Event Parameters. */ - ble_gap_evt_phy_update_t phy_update; /**< PHY Update Parameters. */ - ble_gap_evt_data_length_update_request_t data_length_update_request; /**< Data Length Update Request Event Parameters. */ - ble_gap_evt_data_length_update_t data_length_update; /**< Data Length Update Event Parameters. */ - ble_gap_evt_qos_channel_survey_report_t qos_channel_survey_report; /**< Quality of Service (QoS) Channel Survey Report Parameters. */ - } params; /**< Event Parameters. */ + uint16_t conn_handle; /**< Connection Handle on which event occurred. */ + union /**< union alternative identified by evt_id in enclosing struct. */ + { + ble_gap_evt_connected_t connected; /**< Connected Event Parameters. */ + ble_gap_evt_disconnected_t disconnected; /**< Disconnected Event Parameters. */ + ble_gap_evt_conn_param_update_t conn_param_update; /**< Connection Parameter Update Parameters. */ + ble_gap_evt_sec_params_request_t sec_params_request; /**< Security Parameters Request Event Parameters. */ + ble_gap_evt_sec_info_request_t sec_info_request; /**< Security Information Request Event Parameters. */ + ble_gap_evt_passkey_display_t passkey_display; /**< Passkey Display Event Parameters. */ + ble_gap_evt_key_pressed_t key_pressed; /**< Key Pressed Event Parameters. */ + ble_gap_evt_auth_key_request_t auth_key_request; /**< Authentication Key Request Event Parameters. */ + ble_gap_evt_lesc_dhkey_request_t lesc_dhkey_request; /**< LE Secure Connections DHKey calculation request. */ + ble_gap_evt_auth_status_t auth_status; /**< Authentication Status Event Parameters. */ + ble_gap_evt_conn_sec_update_t conn_sec_update; /**< Connection Security Update Event Parameters. */ + ble_gap_evt_timeout_t timeout; /**< Timeout Event Parameters. */ + ble_gap_evt_rssi_changed_t rssi_changed; /**< RSSI Event Parameters. */ + ble_gap_evt_adv_report_t adv_report; /**< Advertising Report Event Parameters. */ + ble_gap_evt_adv_set_terminated_t adv_set_terminated; /**< Advertising Set Terminated Event Parameters. */ + ble_gap_evt_sec_request_t sec_request; /**< Security Request Event Parameters. */ + ble_gap_evt_conn_param_update_request_t conn_param_update_request; /**< Connection Parameter Update Parameters. */ + ble_gap_evt_scan_req_report_t scan_req_report; /**< Scan Request Report Parameters. */ + ble_gap_evt_phy_update_request_t phy_update_request; /**< PHY Update Request Event Parameters. */ + ble_gap_evt_phy_update_t phy_update; /**< PHY Update Parameters. */ + ble_gap_evt_data_length_update_request_t data_length_update_request; /**< Data Length Update Request Event Parameters. */ + ble_gap_evt_data_length_update_t data_length_update; /**< Data Length Update Event Parameters. */ + ble_gap_evt_qos_channel_survey_report_t qos_channel_survey_report; /**< Quality of Service (QoS) Channel Survey Report Parameters. */ + } params; /**< Event Parameters. */ } ble_gap_evt_t; @@ -1407,9 +1407,9 @@ typedef struct */ typedef struct { - uint8_t conn_count; /**< The number of concurrent connections the application can create with this configuration. + uint8_t conn_count; /**< The number of concurrent connections the application can create with this configuration. The default and minimum value is @ref BLE_GAP_CONN_COUNT_DEFAULT. */ - uint16_t event_length; /**< The time set aside for this connection on every connection interval in 1.25 ms units. + uint16_t event_length; /**< The time set aside for this connection on every connection interval in 1.25 ms units. The default value is @ref BLE_GAP_EVENT_LENGTH_DEFAULT, the minimum value is @ref BLE_GAP_EVENT_LENGTH_MIN. The event length and the connection interval are the primary parameters for setting the throughput of a connection. @@ -1431,11 +1431,11 @@ typedef struct */ typedef struct { - uint8_t adv_set_count; /**< Maximum number of advertising sets. Default value is @ref BLE_GAP_ADV_SET_COUNT_DEFAULT. */ - uint8_t periph_role_count; /**< Maximum number of connections concurrently acting as a peripheral. Default value is @ref BLE_GAP_ROLE_COUNT_PERIPH_DEFAULT. */ - uint8_t central_role_count; /**< Maximum number of connections concurrently acting as a central. Default value is @ref BLE_GAP_ROLE_COUNT_CENTRAL_DEFAULT. */ - uint8_t central_sec_count; /**< Number of SMP instances shared between all connections acting as a central. Default value is @ref BLE_GAP_ROLE_COUNT_CENTRAL_SEC_DEFAULT. */ - uint8_t qos_channel_survey_role_available:1; /**< If set, the Quality of Service (QoS) channel survey module is available to the + uint8_t adv_set_count; /**< Maximum number of advertising sets. Default value is @ref BLE_GAP_ADV_SET_COUNT_DEFAULT. */ + uint8_t periph_role_count; /**< Maximum number of connections concurrently acting as a peripheral. Default value is @ref BLE_GAP_ROLE_COUNT_PERIPH_DEFAULT. */ + uint8_t central_role_count; /**< Maximum number of connections concurrently acting as a central. Default value is @ref BLE_GAP_ROLE_COUNT_CENTRAL_DEFAULT. */ + uint8_t central_sec_count; /**< Number of SMP instances shared between all connections acting as a central. Default value is @ref BLE_GAP_ROLE_COUNT_CENTRAL_SEC_DEFAULT. */ + uint8_t qos_channel_survey_role_available : 1; /**< If set, the Quality of Service (QoS) channel survey module is available to the application using @ref sd_ble_gap_qos_channel_survey_start. */ } ble_gap_cfg_role_count_t; @@ -1470,18 +1470,18 @@ typedef struct */ typedef struct { - ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ - uint8_t vloc:2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ - uint8_t *p_value; /**< Pointer to where the value (device name) is stored or will be stored. */ - uint16_t current_len; /**< Current length in bytes of the memory pointed to by p_value.*/ - uint16_t max_len; /**< Maximum length in bytes of the memory pointed to by p_value.*/ + ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ + uint8_t vloc : 2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ + uint8_t *p_value; /**< Pointer to where the value (device name) is stored or will be stored. */ + uint16_t current_len; /**< Current length in bytes of the memory pointed to by p_value.*/ + uint16_t max_len; /**< Maximum length in bytes of the memory pointed to by p_value.*/ } ble_gap_cfg_device_name_t; /**@brief Peripheral Preferred Connection Parameters include configuration parameters, set with @ref sd_ble_cfg_set. */ typedef struct { - uint8_t include_cfg; /**< Inclusion configuration of the Peripheral Preferred Connection Parameters characteristic. + uint8_t include_cfg; /**< Inclusion configuration of the Peripheral Preferred Connection Parameters characteristic. See @ref BLE_GAP_CHAR_INCL_CONFIG. Default is @ref BLE_GAP_PPCP_INCL_CONFIG_DEFAULT. */ } ble_gap_cfg_ppcp_incl_cfg_t; @@ -1489,7 +1489,7 @@ typedef struct /**@brief Central Address Resolution include configuration parameters, set with @ref sd_ble_cfg_set. */ typedef struct { - uint8_t include_cfg; /**< Inclusion configuration of the Central Address Resolution characteristic. + uint8_t include_cfg; /**< Inclusion configuration of the Central Address Resolution characteristic. See @ref BLE_GAP_CHAR_INCL_CONFIG. Default is @ref BLE_GAP_CAR_INCL_CONFIG_DEFAULT. */ } ble_gap_cfg_car_incl_cfg_t; @@ -1497,11 +1497,11 @@ typedef struct /**@brief Configuration structure for GAP configurations. */ typedef union { - ble_gap_cfg_role_count_t role_count_cfg; /**< Role count configuration, cfg_id is @ref BLE_GAP_CFG_ROLE_COUNT. */ - ble_gap_cfg_device_name_t device_name_cfg; /**< Device name configuration, cfg_id is @ref BLE_GAP_CFG_DEVICE_NAME. */ - ble_gap_cfg_ppcp_incl_cfg_t ppcp_include_cfg; /**< Peripheral Preferred Connection Parameters characteristic include + ble_gap_cfg_role_count_t role_count_cfg; /**< Role count configuration, cfg_id is @ref BLE_GAP_CFG_ROLE_COUNT. */ + ble_gap_cfg_device_name_t device_name_cfg; /**< Device name configuration, cfg_id is @ref BLE_GAP_CFG_DEVICE_NAME. */ + ble_gap_cfg_ppcp_incl_cfg_t ppcp_include_cfg; /**< Peripheral Preferred Connection Parameters characteristic include configuration, cfg_id is @ref BLE_GAP_CFG_PPCP_INCL_CONFIG. */ - ble_gap_cfg_car_incl_cfg_t car_include_cfg; /**< Central Address Resolution characteristic include configuration, + ble_gap_cfg_car_incl_cfg_t car_include_cfg; /**< Central Address Resolution characteristic include configuration, cfg_id is @ref BLE_GAP_CFG_CAR_INCL_CONFIG. */ } ble_gap_cfg_t; @@ -1531,8 +1531,8 @@ typedef union */ typedef struct { - uint16_t conn_handle; /**< Connection Handle (only applicable for get) */ - uint8_t ch_map[5]; /**< Channel Map (37-bit). */ + uint16_t conn_handle; /**< Connection Handle (only applicable for get) */ + uint8_t ch_map[5]; /**< Channel Map (37-bit). */ } ble_gap_opt_ch_map_t; @@ -1560,9 +1560,9 @@ typedef struct */ typedef struct { - uint16_t conn_handle; /**< Connection Handle */ - uint16_t requested_latency; /**< Requested local connection latency. */ - uint16_t * p_actual_latency; /**< Pointer to storage for the actual local connection latency (can be set to NULL to skip return value). */ + uint16_t conn_handle; /**< Connection Handle */ + uint16_t requested_latency; /**< Requested local connection latency. */ + uint16_t *p_actual_latency; /**< Pointer to storage for the actual local connection latency (can be set to NULL to skip return value). */ } ble_gap_opt_local_conn_latency_t; /**@brief Disable slave latency @@ -1579,8 +1579,8 @@ typedef struct */ typedef struct { - uint16_t conn_handle; /**< Connection Handle */ - uint8_t disable : 1; /**< Set to 1 to disable slave latency. Set to 0 enable it again.*/ + uint16_t conn_handle; /**< Connection Handle */ + uint8_t disable : 1; /**< Set to 1 to disable slave latency. Set to 0 enable it again.*/ } ble_gap_opt_slave_latency_disable_t; /**@brief Passkey Option. @@ -1600,7 +1600,7 @@ typedef struct */ typedef struct { - uint8_t const * p_passkey; /**< Pointer to 6-digit ASCII string (digit 0..9 only, no NULL termination) passkey to be used during pairing. If this is NULL, the SoftDevice will generate a random passkey if required.*/ + uint8_t const *p_passkey; /**< Pointer to 6-digit ASCII string (digit 0..9 only, no NULL termination) passkey to be used during pairing. If this is NULL, the SoftDevice will generate a random passkey if required.*/ } ble_gap_opt_passkey_t; @@ -1621,7 +1621,7 @@ typedef struct */ typedef struct { - uint8_t enable : 1; /**< Enable compatibility mode 1.*/ + uint8_t enable : 1; /**< Enable compatibility mode 1.*/ } ble_gap_opt_compat_mode_1_t; @@ -1646,31 +1646,31 @@ typedef struct */ typedef struct { - uint16_t conn_handle; /**< Connection Handle */ - uint16_t auth_payload_timeout; /**< Requested timeout in 10 ms unit, see @ref BLE_GAP_AUTH_PAYLOAD_TIMEOUT. */ + uint16_t conn_handle; /**< Connection Handle */ + uint16_t auth_payload_timeout; /**< Requested timeout in 10 ms unit, see @ref BLE_GAP_AUTH_PAYLOAD_TIMEOUT. */ } ble_gap_opt_auth_payload_timeout_t; /**@brief Option structure for GAP options. */ typedef union { - ble_gap_opt_ch_map_t ch_map; /**< Parameters for the Channel Map option. */ - ble_gap_opt_local_conn_latency_t local_conn_latency; /**< Parameters for the Local connection latency option */ - ble_gap_opt_passkey_t passkey; /**< Parameters for the Passkey option.*/ - ble_gap_opt_compat_mode_1_t compat_mode_1; /**< Parameters for the compatibility mode 1 option.*/ - ble_gap_opt_auth_payload_timeout_t auth_payload_timeout; /**< Parameters for the authenticated payload timeout option.*/ - ble_gap_opt_slave_latency_disable_t slave_latency_disable; /**< Parameters for the Disable slave latency option */ + ble_gap_opt_ch_map_t ch_map; /**< Parameters for the Channel Map option. */ + ble_gap_opt_local_conn_latency_t local_conn_latency; /**< Parameters for the Local connection latency option */ + ble_gap_opt_passkey_t passkey; /**< Parameters for the Passkey option.*/ + ble_gap_opt_compat_mode_1_t compat_mode_1; /**< Parameters for the compatibility mode 1 option.*/ + ble_gap_opt_auth_payload_timeout_t auth_payload_timeout; /**< Parameters for the authenticated payload timeout option.*/ + ble_gap_opt_slave_latency_disable_t slave_latency_disable; /**< Parameters for the Disable slave latency option */ } ble_gap_opt_t; /**@brief Connection event triggering parameters. */ typedef struct { - uint8_t ppi_ch_id; /**< PPI channel to use. This channel should be regarded as reserved until + uint8_t ppi_ch_id; /**< PPI channel to use. This channel should be regarded as reserved until connection event PPI task triggering is stopped. The PPI channel ID can not be one of the PPI channels reserved by the SoftDevice. See @ref NRF_SOC_SD_PPI_CHANNELS_SD_ENABLED_MSK. */ - uint32_t task_endpoint; /**< Task Endpoint to trigger. */ - uint16_t conn_evt_counter_start; /**< The connection event on which the task triggering should start. */ - uint16_t period_in_events; /**< Trigger period. Valid range is [1, 32767]. + uint32_t task_endpoint; /**< Task Endpoint to trigger. */ + uint16_t conn_evt_counter_start; /**< The connection event on which the task triggering should start. */ + uint16_t period_in_events; /**< Trigger period. Valid range is [1, 32767]. If the device is in slave role and slave latency is enabled, this parameter should be set to a multiple of (slave latency + 1) to ensure low power operation. */ @@ -1721,7 +1721,7 @@ SVCALL(SD_BLE_GAP_ADDR_SET, uint32_t, sd_ble_gap_addr_set(ble_gap_addr_t const * * @retval ::NRF_SUCCESS Address successfully retrieved. * @retval ::NRF_ERROR_INVALID_ADDR Invalid or NULL pointer supplied. */ -SVCALL(SD_BLE_GAP_ADDR_GET, uint32_t, sd_ble_gap_addr_get(ble_gap_addr_t *p_addr)); +SVCALL(SD_BLE_GAP_ADDR_GET, uint32_t, sd_ble_gap_addr_get(ble_gap_addr_t * p_addr)); /**@brief Get the Bluetooth device address used by the advertiser. @@ -1740,7 +1740,7 @@ SVCALL(SD_BLE_GAP_ADDR_GET, uint32_t, sd_ble_gap_addr_get(ble_gap_addr_t *p_addr * @retval ::BLE_ERROR_INVALID_ADV_HANDLE The provided advertising handle was not found. * @retval ::NRF_ERROR_INVALID_STATE The advertising set is currently not advertising. */ -SVCALL(SD_BLE_GAP_ADV_ADDR_GET, uint32_t, sd_ble_gap_adv_addr_get(uint8_t adv_handle, ble_gap_addr_t *p_addr)); +SVCALL(SD_BLE_GAP_ADV_ADDR_GET, uint32_t, sd_ble_gap_adv_addr_get(uint8_t adv_handle, ble_gap_addr_t * p_addr)); /**@brief Set the active whitelist in the SoftDevice. @@ -1766,7 +1766,7 @@ SVCALL(SD_BLE_GAP_ADV_ADDR_GET, uint32_t, sd_ble_gap_adv_addr_get(uint8_t adv_ha * @retval ::NRF_ERROR_DATA_SIZE The given whitelist size is invalid (zero or too large); this can only return when * pp_wl_addrs is not NULL. */ -SVCALL(SD_BLE_GAP_WHITELIST_SET, uint32_t, sd_ble_gap_whitelist_set(ble_gap_addr_t const * const * pp_wl_addrs, uint8_t len)); +SVCALL(SD_BLE_GAP_WHITELIST_SET, uint32_t, sd_ble_gap_whitelist_set(ble_gap_addr_t const *const *pp_wl_addrs, uint8_t len)); /**@brief Set device identity list. @@ -1797,7 +1797,7 @@ SVCALL(SD_BLE_GAP_WHITELIST_SET, uint32_t, sd_ble_gap_whitelist_set(ble_gap_addr * @retval ::NRF_ERROR_DATA_SIZE The given device identity list size invalid (zero or too large); this can * only return when pp_id_keys is not NULL. */ -SVCALL(SD_BLE_GAP_DEVICE_IDENTITIES_SET, uint32_t, sd_ble_gap_device_identities_set(ble_gap_id_key_t const * const * pp_id_keys, ble_gap_irk_t const * const * pp_local_irks, uint8_t len)); +SVCALL(SD_BLE_GAP_DEVICE_IDENTITIES_SET, uint32_t, sd_ble_gap_device_identities_set(ble_gap_id_key_t const *const *pp_id_keys, ble_gap_irk_t const *const *pp_local_irks, uint8_t len)); /**@brief Set privacy settings. @@ -1839,7 +1839,7 @@ SVCALL(SD_BLE_GAP_PRIVACY_SET, uint32_t, sd_ble_gap_privacy_set(ble_gap_privacy_ * @retval ::NRF_ERROR_INVALID_ADDR The pointer given for returning the privacy settings may be NULL or invalid. * Otherwise, the p_device_irk pointer in privacy parameter is an invalid pointer. */ -SVCALL(SD_BLE_GAP_PRIVACY_GET, uint32_t, sd_ble_gap_privacy_get(ble_gap_privacy_params_t *p_privacy_params)); +SVCALL(SD_BLE_GAP_PRIVACY_GET, uint32_t, sd_ble_gap_privacy_get(ble_gap_privacy_params_t * p_privacy_params)); /**@brief Configure an advertising set. Set, clear or update advertising and scan response data. @@ -1886,7 +1886,7 @@ SVCALL(SD_BLE_GAP_PRIVACY_GET, uint32_t, sd_ble_gap_privacy_get(ble_gap_privacy_ * existing advertising handle instead. * @retval ::BLE_ERROR_GAP_UUID_LIST_MISMATCH Invalid UUID list supplied. */ -SVCALL(SD_BLE_GAP_ADV_SET_CONFIGURE, uint32_t, sd_ble_gap_adv_set_configure(uint8_t *p_adv_handle, ble_gap_adv_data_t const *p_adv_data, ble_gap_adv_params_t const *p_adv_params)); +SVCALL(SD_BLE_GAP_ADV_SET_CONFIGURE, uint32_t, sd_ble_gap_adv_set_configure(uint8_t * p_adv_handle, ble_gap_adv_data_t const *p_adv_data, ble_gap_adv_params_t const *p_adv_params)); /**@brief Start advertising (GAP Discoverable, Connectable modes, Broadcast Procedure). @@ -2058,7 +2058,7 @@ SVCALL(SD_BLE_GAP_APPEARANCE_SET, uint32_t, sd_ble_gap_appearance_set(uint16_t a * @retval ::NRF_SUCCESS Appearance value retrieved successfully. * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. */ -SVCALL(SD_BLE_GAP_APPEARANCE_GET, uint32_t, sd_ble_gap_appearance_get(uint16_t *p_appearance)); +SVCALL(SD_BLE_GAP_APPEARANCE_GET, uint32_t, sd_ble_gap_appearance_get(uint16_t * p_appearance)); /**@brief Set GAP Peripheral Preferred Connection Parameters. @@ -2083,7 +2083,7 @@ SVCALL(SD_BLE_GAP_PPCP_SET, uint32_t, sd_ble_gap_ppcp_set(ble_gap_conn_params_t * @retval ::NRF_ERROR_NOT_SUPPORTED The characteristic is not included in the Attribute Table, see @ref ble_gap_cfg_ppcp_incl_cfg_t. */ -SVCALL(SD_BLE_GAP_PPCP_GET, uint32_t, sd_ble_gap_ppcp_get(ble_gap_conn_params_t *p_conn_params)); +SVCALL(SD_BLE_GAP_PPCP_GET, uint32_t, sd_ble_gap_ppcp_get(ble_gap_conn_params_t * p_conn_params)); /**@brief Set GAP device name. @@ -2118,7 +2118,7 @@ SVCALL(SD_BLE_GAP_DEVICE_NAME_SET, uint32_t, sd_ble_gap_device_name_set(ble_gap_ * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied. */ -SVCALL(SD_BLE_GAP_DEVICE_NAME_GET, uint32_t, sd_ble_gap_device_name_get(uint8_t *p_dev_name, uint16_t *p_len)); +SVCALL(SD_BLE_GAP_DEVICE_NAME_GET, uint32_t, sd_ble_gap_device_name_get(uint8_t * p_dev_name, uint16_t * p_len)); /**@brief Initiate the GAP Authentication procedure. @@ -2350,7 +2350,7 @@ SVCALL(SD_BLE_GAP_KEYPRESS_NOTIFY, uint32_t, sd_ble_gap_keypress_notify(uint16_t * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. */ -SVCALL(SD_BLE_GAP_LESC_OOB_DATA_GET, uint32_t, sd_ble_gap_lesc_oob_data_get(uint16_t conn_handle, ble_gap_lesc_p256_pk_t const *p_pk_own, ble_gap_lesc_oob_data_t *p_oobd_own)); +SVCALL(SD_BLE_GAP_LESC_OOB_DATA_GET, uint32_t, sd_ble_gap_lesc_oob_data_get(uint16_t conn_handle, ble_gap_lesc_p256_pk_t const *p_pk_own, ble_gap_lesc_oob_data_t * p_oobd_own)); /**@brief Provide the OOB data sent/received out of band. * @@ -2449,7 +2449,7 @@ SVCALL(SD_BLE_GAP_SEC_INFO_REPLY, uint32_t, sd_ble_gap_sec_info_reply(uint16_t c * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. */ -SVCALL(SD_BLE_GAP_CONN_SEC_GET, uint32_t, sd_ble_gap_conn_sec_get(uint16_t conn_handle, ble_gap_conn_sec_t *p_conn_sec)); +SVCALL(SD_BLE_GAP_CONN_SEC_GET, uint32_t, sd_ble_gap_conn_sec_get(uint16_t conn_handle, ble_gap_conn_sec_t * p_conn_sec)); /**@brief Start reporting the received signal strength to the application. @@ -2516,7 +2516,7 @@ SVCALL(SD_BLE_GAP_RSSI_STOP, uint32_t, sd_ble_gap_rssi_stop(uint16_t conn_handle * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied. * @retval ::NRF_ERROR_INVALID_STATE RSSI reporting is not ongoing. */ -SVCALL(SD_BLE_GAP_RSSI_GET, uint32_t, sd_ble_gap_rssi_get(uint16_t conn_handle, int8_t *p_rssi, uint8_t *p_ch_index)); +SVCALL(SD_BLE_GAP_RSSI_GET, uint32_t, sd_ble_gap_rssi_get(uint16_t conn_handle, int8_t * p_rssi, uint8_t * p_ch_index)); /**@brief Start or continue scanning (GAP Discovery procedure, Observer Procedure). @@ -2569,7 +2569,7 @@ SVCALL(SD_BLE_GAP_RSSI_GET, uint32_t, sd_ble_gap_rssi_get(uint16_t conn_handle, * @retval ::NRF_ERROR_RESOURCES Not enough BLE role slots available. * Stop one or more currently active roles (Central, Peripheral or Broadcaster) and try again */ -SVCALL(SD_BLE_GAP_SCAN_START, uint32_t, sd_ble_gap_scan_start(ble_gap_scan_params_t const *p_scan_params, ble_data_t const * p_adv_report_buffer)); +SVCALL(SD_BLE_GAP_SCAN_START, uint32_t, sd_ble_gap_scan_start(ble_gap_scan_params_t const *p_scan_params, ble_data_t const *p_adv_report_buffer)); /**@brief Stop scanning (GAP Discovery procedure, Observer Procedure). @@ -2737,7 +2737,7 @@ SVCALL(SD_BLE_GAP_PHY_UPDATE, uint32_t, sd_ble_gap_phy_update(uint16_t conn_hand * @retval ::NRF_ERROR_BUSY Peer has already initiated a Data Length Update Procedure. Process the * pending @ref BLE_GAP_EVT_DATA_LENGTH_UPDATE_REQUEST event to respond. */ -SVCALL(SD_BLE_GAP_DATA_LENGTH_UPDATE, uint32_t, sd_ble_gap_data_length_update(uint16_t conn_handle, ble_gap_data_length_params_t const *p_dl_params, ble_gap_data_length_limitation_t *p_dl_limitation)); +SVCALL(SD_BLE_GAP_DATA_LENGTH_UPDATE, uint32_t, sd_ble_gap_data_length_update(uint16_t conn_handle, ble_gap_data_length_params_t const *p_dl_params, ble_gap_data_length_limitation_t * p_dl_limitation)); /**@brief Start the Quality of Service (QoS) channel survey module. * @@ -2825,7 +2825,7 @@ SVCALL(SD_BLE_GAP_NEXT_CONN_EVT_COUNTER_GET, uint32_t, sd_ble_gap_next_conn_evt_ * Use @ref sd_ble_gap_next_conn_evt_counter_get to find a new value to be used as ble_gap_conn_event_trigger_t::conn_evt_counter_start. */ -SVCALL(SD_BLE_GAP_CONN_EVT_TRIGGER_START, uint32_t, sd_ble_gap_conn_evt_trigger_start(uint16_t conn_handle, ble_gap_conn_event_trigger_t const * p_params)); +SVCALL(SD_BLE_GAP_CONN_EVT_TRIGGER_START, uint32_t, sd_ble_gap_conn_evt_trigger_start(uint16_t conn_handle, ble_gap_conn_event_trigger_t const *p_params)); /**@brief Stop triggering the task configured using @ref sd_ble_gap_conn_evt_trigger_start. diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gatt.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gatt.h index c392884418..cb760720e1 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gatt.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gatt.h @@ -189,7 +189,7 @@ extern "C" { */ typedef struct { - uint16_t att_mtu; /**< Maximum size of ATT packet the SoftDevice can send or receive. + uint16_t att_mtu; /**< Maximum size of ATT packet the SoftDevice can send or receive. The default and minimum value is @ref BLE_GATT_ATT_MTU_DEFAULT. @mscs @mmsc{@ref BLE_GATTC_MTU_EXCHANGE} @@ -201,22 +201,22 @@ typedef struct /**@brief GATT Characteristic Properties. */ typedef struct { - /* Standard properties */ - uint8_t broadcast :1; /**< Broadcasting of the value permitted. */ - uint8_t read :1; /**< Reading the value permitted. */ - uint8_t write_wo_resp :1; /**< Writing the value with Write Command permitted. */ - uint8_t write :1; /**< Writing the value with Write Request permitted. */ - uint8_t notify :1; /**< Notification of the value permitted. */ - uint8_t indicate :1; /**< Indications of the value permitted. */ - uint8_t auth_signed_wr :1; /**< Writing the value with Signed Write Command permitted. */ + /* Standard properties */ + uint8_t broadcast : 1;/**< Broadcasting of the value permitted. */ + uint8_t read : 1;/**< Reading the value permitted. */ + uint8_t write_wo_resp : 1;/**< Writing the value with Write Command permitted. */ + uint8_t write : 1;/**< Writing the value with Write Request permitted. */ + uint8_t notify : 1;/**< Notification of the value permitted. */ + uint8_t indicate : 1;/**< Indications of the value permitted. */ + uint8_t auth_signed_wr : 1;/**< Writing the value with Signed Write Command permitted. */ } ble_gatt_char_props_t; /**@brief GATT Characteristic Extended Properties. */ typedef struct { - /* Extended properties */ - uint8_t reliable_wr :1; /**< Writing the value with Queued Write operations permitted. */ - uint8_t wr_aux :1; /**< Writing the Characteristic User Description descriptor permitted. */ + /* Extended properties */ + uint8_t reliable_wr : 1;/**< Writing the value with Queued Write operations permitted. */ + uint8_t wr_aux : 1;/**< Writing the Characteristic User Description descriptor permitted. */ } ble_gatt_char_ext_props_t; /** @} */ diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gattc.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gattc.h index 7fb3920244..c4c8322ca1 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gattc.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gattc.h @@ -64,17 +64,17 @@ extern "C" { /**@brief GATTC API SVC numbers. */ enum BLE_GATTC_SVCS { - SD_BLE_GATTC_PRIMARY_SERVICES_DISCOVER = BLE_GATTC_SVC_BASE, /**< Primary Service Discovery. */ - SD_BLE_GATTC_RELATIONSHIPS_DISCOVER, /**< Relationship Discovery. */ - SD_BLE_GATTC_CHARACTERISTICS_DISCOVER, /**< Characteristic Discovery. */ - SD_BLE_GATTC_DESCRIPTORS_DISCOVER, /**< Characteristic Descriptor Discovery. */ - SD_BLE_GATTC_ATTR_INFO_DISCOVER, /**< Attribute Information Discovery. */ - SD_BLE_GATTC_CHAR_VALUE_BY_UUID_READ, /**< Read Characteristic Value by UUID. */ - SD_BLE_GATTC_READ, /**< Generic read. */ - SD_BLE_GATTC_CHAR_VALUES_READ, /**< Read multiple Characteristic Values. */ - SD_BLE_GATTC_WRITE, /**< Generic write. */ - SD_BLE_GATTC_HV_CONFIRM, /**< Handle Value Confirmation. */ - SD_BLE_GATTC_EXCHANGE_MTU_REQUEST, /**< Exchange MTU Request. */ + SD_BLE_GATTC_PRIMARY_SERVICES_DISCOVER = BLE_GATTC_SVC_BASE, /**< Primary Service Discovery. */ + SD_BLE_GATTC_RELATIONSHIPS_DISCOVER, /**< Relationship Discovery. */ + SD_BLE_GATTC_CHARACTERISTICS_DISCOVER, /**< Characteristic Discovery. */ + SD_BLE_GATTC_DESCRIPTORS_DISCOVER, /**< Characteristic Descriptor Discovery. */ + SD_BLE_GATTC_ATTR_INFO_DISCOVER, /**< Attribute Information Discovery. */ + SD_BLE_GATTC_CHAR_VALUE_BY_UUID_READ, /**< Read Characteristic Value by UUID. */ + SD_BLE_GATTC_READ, /**< Generic read. */ + SD_BLE_GATTC_CHAR_VALUES_READ, /**< Read multiple Characteristic Values. */ + SD_BLE_GATTC_WRITE, /**< Generic write. */ + SD_BLE_GATTC_HV_CONFIRM, /**< Handle Value Confirmation. */ + SD_BLE_GATTC_EXCHANGE_MTU_REQUEST, /**< Exchange MTU Request. */ }; /** @@ -82,19 +82,19 @@ enum BLE_GATTC_SVCS */ enum BLE_GATTC_EVTS { - BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP = BLE_GATTC_EVT_BASE, /**< Primary Service Discovery Response event. \n See @ref ble_gattc_evt_prim_srvc_disc_rsp_t. */ - BLE_GATTC_EVT_REL_DISC_RSP, /**< Relationship Discovery Response event. \n See @ref ble_gattc_evt_rel_disc_rsp_t. */ - BLE_GATTC_EVT_CHAR_DISC_RSP, /**< Characteristic Discovery Response event. \n See @ref ble_gattc_evt_char_disc_rsp_t. */ - BLE_GATTC_EVT_DESC_DISC_RSP, /**< Descriptor Discovery Response event. \n See @ref ble_gattc_evt_desc_disc_rsp_t. */ - BLE_GATTC_EVT_ATTR_INFO_DISC_RSP, /**< Attribute Information Response event. \n See @ref ble_gattc_evt_attr_info_disc_rsp_t. */ - BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP, /**< Read By UUID Response event. \n See @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t. */ - BLE_GATTC_EVT_READ_RSP, /**< Read Response event. \n See @ref ble_gattc_evt_read_rsp_t. */ - BLE_GATTC_EVT_CHAR_VALS_READ_RSP, /**< Read multiple Response event. \n See @ref ble_gattc_evt_char_vals_read_rsp_t. */ - BLE_GATTC_EVT_WRITE_RSP, /**< Write Response event. \n See @ref ble_gattc_evt_write_rsp_t. */ - BLE_GATTC_EVT_HVX, /**< Handle Value Notification or Indication event. \n Confirm indication with @ref sd_ble_gattc_hv_confirm. \n See @ref ble_gattc_evt_hvx_t. */ - BLE_GATTC_EVT_EXCHANGE_MTU_RSP, /**< Exchange MTU Response event. \n See @ref ble_gattc_evt_exchange_mtu_rsp_t. */ - BLE_GATTC_EVT_TIMEOUT, /**< Timeout event. \n See @ref ble_gattc_evt_timeout_t. */ - BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE /**< Write without Response transmission complete. \n See @ref ble_gattc_evt_write_cmd_tx_complete_t. */ + BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP = BLE_GATTC_EVT_BASE, /**< Primary Service Discovery Response event. \n See @ref ble_gattc_evt_prim_srvc_disc_rsp_t. */ + BLE_GATTC_EVT_REL_DISC_RSP, /**< Relationship Discovery Response event. \n See @ref ble_gattc_evt_rel_disc_rsp_t. */ + BLE_GATTC_EVT_CHAR_DISC_RSP, /**< Characteristic Discovery Response event. \n See @ref ble_gattc_evt_char_disc_rsp_t. */ + BLE_GATTC_EVT_DESC_DISC_RSP, /**< Descriptor Discovery Response event. \n See @ref ble_gattc_evt_desc_disc_rsp_t. */ + BLE_GATTC_EVT_ATTR_INFO_DISC_RSP, /**< Attribute Information Response event. \n See @ref ble_gattc_evt_attr_info_disc_rsp_t. */ + BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP, /**< Read By UUID Response event. \n See @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t. */ + BLE_GATTC_EVT_READ_RSP, /**< Read Response event. \n See @ref ble_gattc_evt_read_rsp_t. */ + BLE_GATTC_EVT_CHAR_VALS_READ_RSP, /**< Read multiple Response event. \n See @ref ble_gattc_evt_char_vals_read_rsp_t. */ + BLE_GATTC_EVT_WRITE_RSP, /**< Write Response event. \n See @ref ble_gattc_evt_write_rsp_t. */ + BLE_GATTC_EVT_HVX, /**< Handle Value Notification or Indication event. \n Confirm indication with @ref sd_ble_gattc_hv_confirm. \n See @ref ble_gattc_evt_hvx_t. */ + BLE_GATTC_EVT_EXCHANGE_MTU_RSP, /**< Exchange MTU Response event. \n See @ref ble_gattc_evt_exchange_mtu_rsp_t. */ + BLE_GATTC_EVT_TIMEOUT, /**< Timeout event. \n See @ref ble_gattc_evt_timeout_t. */ + BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE /**< Write without Response transmission complete. \n See @ref ble_gattc_evt_write_cmd_tx_complete_t. */ }; /** @} */ @@ -128,138 +128,138 @@ enum BLE_GATTC_EVTS */ typedef struct { - uint8_t write_cmd_tx_queue_size; /**< The guaranteed minimum number of Write without Response that can be queued for transmission. + uint8_t write_cmd_tx_queue_size; /**< The guaranteed minimum number of Write without Response that can be queued for transmission. The default value is @ref BLE_GATTC_WRITE_CMD_TX_QUEUE_SIZE_DEFAULT */ } ble_gattc_conn_cfg_t; /**@brief Operation Handle Range. */ typedef struct { - uint16_t start_handle; /**< Start Handle. */ - uint16_t end_handle; /**< End Handle. */ + uint16_t start_handle; /**< Start Handle. */ + uint16_t end_handle; /**< End Handle. */ } ble_gattc_handle_range_t; /**@brief GATT service. */ typedef struct { - ble_uuid_t uuid; /**< Service UUID. */ - ble_gattc_handle_range_t handle_range; /**< Service Handle Range. */ + ble_uuid_t uuid; /**< Service UUID. */ + ble_gattc_handle_range_t handle_range; /**< Service Handle Range. */ } ble_gattc_service_t; /**@brief GATT include. */ typedef struct { - uint16_t handle; /**< Include Handle. */ - ble_gattc_service_t included_srvc; /**< Handle of the included service. */ + uint16_t handle; /**< Include Handle. */ + ble_gattc_service_t included_srvc; /**< Handle of the included service. */ } ble_gattc_include_t; /**@brief GATT characteristic. */ typedef struct { - ble_uuid_t uuid; /**< Characteristic UUID. */ - ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ - uint8_t char_ext_props : 1; /**< Extended properties present. */ - uint16_t handle_decl; /**< Handle of the Characteristic Declaration. */ - uint16_t handle_value; /**< Handle of the Characteristic Value. */ + ble_uuid_t uuid; /**< Characteristic UUID. */ + ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ + uint8_t char_ext_props : 1; /**< Extended properties present. */ + uint16_t handle_decl; /**< Handle of the Characteristic Declaration. */ + uint16_t handle_value; /**< Handle of the Characteristic Value. */ } ble_gattc_char_t; /**@brief GATT descriptor. */ typedef struct { - uint16_t handle; /**< Descriptor Handle. */ - ble_uuid_t uuid; /**< Descriptor UUID. */ + uint16_t handle; /**< Descriptor Handle. */ + ble_uuid_t uuid; /**< Descriptor UUID. */ } ble_gattc_desc_t; /**@brief Write Parameters. */ typedef struct { - uint8_t write_op; /**< Write Operation to be performed, see @ref BLE_GATT_WRITE_OPS. */ - uint8_t flags; /**< Flags, see @ref BLE_GATT_EXEC_WRITE_FLAGS. */ - uint16_t handle; /**< Handle to the attribute to be written. */ - uint16_t offset; /**< Offset in bytes. @note For WRITE_CMD and WRITE_REQ, offset must be 0. */ - uint16_t len; /**< Length of data in bytes. */ - uint8_t const *p_value; /**< Pointer to the value data. */ + uint8_t write_op; /**< Write Operation to be performed, see @ref BLE_GATT_WRITE_OPS. */ + uint8_t flags; /**< Flags, see @ref BLE_GATT_EXEC_WRITE_FLAGS. */ + uint16_t handle; /**< Handle to the attribute to be written. */ + uint16_t offset; /**< Offset in bytes. @note For WRITE_CMD and WRITE_REQ, offset must be 0. */ + uint16_t len; /**< Length of data in bytes. */ + uint8_t const *p_value; /**< Pointer to the value data. */ } ble_gattc_write_params_t; /**@brief Attribute Information for 16-bit Attribute UUID. */ typedef struct { - uint16_t handle; /**< Attribute handle. */ - ble_uuid_t uuid; /**< 16-bit Attribute UUID. */ + uint16_t handle; /**< Attribute handle. */ + ble_uuid_t uuid; /**< 16-bit Attribute UUID. */ } ble_gattc_attr_info16_t; /**@brief Attribute Information for 128-bit Attribute UUID. */ typedef struct { - uint16_t handle; /**< Attribute handle. */ - ble_uuid128_t uuid; /**< 128-bit Attribute UUID. */ + uint16_t handle; /**< Attribute handle. */ + ble_uuid128_t uuid; /**< 128-bit Attribute UUID. */ } ble_gattc_attr_info128_t; /**@brief Event structure for @ref BLE_GATTC_EVT_PRIM_SRVC_DISC_RSP. */ typedef struct { - uint16_t count; /**< Service count. */ - ble_gattc_service_t services[1]; /**< Service data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t count; /**< Service count. */ + ble_gattc_service_t services[1]; /**< Service data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_prim_srvc_disc_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_REL_DISC_RSP. */ typedef struct { - uint16_t count; /**< Include count. */ - ble_gattc_include_t includes[1]; /**< Include data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t count; /**< Include count. */ + ble_gattc_include_t includes[1]; /**< Include data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_rel_disc_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_DISC_RSP. */ typedef struct { - uint16_t count; /**< Characteristic count. */ - ble_gattc_char_t chars[1]; /**< Characteristic data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t count; /**< Characteristic count. */ + ble_gattc_char_t chars[1]; /**< Characteristic data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_char_disc_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_DESC_DISC_RSP. */ typedef struct { - uint16_t count; /**< Descriptor count. */ - ble_gattc_desc_t descs[1]; /**< Descriptor data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t count; /**< Descriptor count. */ + ble_gattc_desc_t descs[1]; /**< Descriptor data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_desc_disc_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_ATTR_INFO_DISC_RSP. */ typedef struct { - uint16_t count; /**< Attribute count. */ - uint8_t format; /**< Attribute information format, see @ref BLE_GATTC_ATTR_INFO_FORMAT. */ - union { - ble_gattc_attr_info16_t attr_info16[1]; /**< Attribute information for 16-bit Attribute UUID. + uint16_t count; /**< Attribute count. */ + uint8_t format; /**< Attribute information format, see @ref BLE_GATTC_ATTR_INFO_FORMAT. */ + union { + ble_gattc_attr_info16_t attr_info16[1]; /**< Attribute information for 16-bit Attribute UUID. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ - ble_gattc_attr_info128_t attr_info128[1]; /**< Attribute information for 128-bit Attribute UUID. + ble_gattc_attr_info128_t attr_info128[1]; /**< Attribute information for 128-bit Attribute UUID. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ - } info; /**< Attribute information union. */ + } info; /**< Attribute information union. */ } ble_gattc_evt_attr_info_disc_rsp_t; /**@brief GATT read by UUID handle value pair. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - uint8_t *p_value; /**< Pointer to the Attribute Value, length is available in @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t::value_len. */ + uint16_t handle; /**< Attribute Handle. */ + uint8_t *p_value; /**< Pointer to the Attribute Value, length is available in @ref ble_gattc_evt_char_val_by_uuid_read_rsp_t::value_len. */ } ble_gattc_handle_value_t; /**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_VAL_BY_UUID_READ_RSP. */ typedef struct { - uint16_t count; /**< Handle-Value Pair Count. */ - uint16_t value_len; /**< Length of the value in Handle-Value(s) list. */ - uint8_t handle_value[1]; /**< Handle-Value(s) list. To iterate through the list use @ref sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter. + uint16_t count; /**< Handle-Value Pair Count. */ + uint16_t value_len; /**< Length of the value in Handle-Value(s) list. */ + uint8_t handle_value[1]; /**< Handle-Value(s) list. To iterate through the list use @ref sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_char_val_by_uuid_read_rsp_t; @@ -267,82 +267,82 @@ typedef struct /**@brief Event structure for @ref BLE_GATTC_EVT_READ_RSP. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - uint16_t offset; /**< Offset of the attribute data. */ - uint16_t len; /**< Attribute data length. */ - uint8_t data[1]; /**< Attribute data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t handle; /**< Attribute Handle. */ + uint16_t offset; /**< Offset of the attribute data. */ + uint16_t len; /**< Attribute data length. */ + uint8_t data[1]; /**< Attribute data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_read_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_CHAR_VALS_READ_RSP. */ typedef struct { - uint16_t len; /**< Concatenated Attribute values length. */ - uint8_t values[1]; /**< Attribute values. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t len; /**< Concatenated Attribute values length. */ + uint8_t values[1]; /**< Attribute values. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_char_vals_read_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_WRITE_RSP. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - uint8_t write_op; /**< Type of write operation, see @ref BLE_GATT_WRITE_OPS. */ - uint16_t offset; /**< Data offset. */ - uint16_t len; /**< Data length. */ - uint8_t data[1]; /**< Data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t handle; /**< Attribute Handle. */ + uint8_t write_op; /**< Type of write operation, see @ref BLE_GATT_WRITE_OPS. */ + uint16_t offset; /**< Data offset. */ + uint16_t len; /**< Data length. */ + uint8_t data[1]; /**< Data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_write_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_HVX. */ typedef struct { - uint16_t handle; /**< Handle to which the HVx operation applies. */ - uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ - uint16_t len; /**< Attribute data length. */ - uint8_t data[1]; /**< Attribute data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t handle; /**< Handle to which the HVx operation applies. */ + uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ + uint16_t len; /**< Attribute data length. */ + uint8_t data[1]; /**< Attribute data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gattc_evt_hvx_t; /**@brief Event structure for @ref BLE_GATTC_EVT_EXCHANGE_MTU_RSP. */ typedef struct { - uint16_t server_rx_mtu; /**< Server RX MTU size. */ + uint16_t server_rx_mtu; /**< Server RX MTU size. */ } ble_gattc_evt_exchange_mtu_rsp_t; /**@brief Event structure for @ref BLE_GATTC_EVT_TIMEOUT. */ typedef struct { - uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ + uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ } ble_gattc_evt_timeout_t; /**@brief Event structure for @ref BLE_GATTC_EVT_WRITE_CMD_TX_COMPLETE. */ typedef struct { - uint8_t count; /**< Number of write without response transmissions completed. */ + uint8_t count; /**< Number of write without response transmissions completed. */ } ble_gattc_evt_write_cmd_tx_complete_t; /**@brief GATTC event structure. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which event occurred. */ - uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ - uint16_t error_handle; /**< In case of error: The handle causing the error. In all other cases @ref BLE_GATT_HANDLE_INVALID. */ - union - { - ble_gattc_evt_prim_srvc_disc_rsp_t prim_srvc_disc_rsp; /**< Primary Service Discovery Response Event Parameters. */ - ble_gattc_evt_rel_disc_rsp_t rel_disc_rsp; /**< Relationship Discovery Response Event Parameters. */ - ble_gattc_evt_char_disc_rsp_t char_disc_rsp; /**< Characteristic Discovery Response Event Parameters. */ - ble_gattc_evt_desc_disc_rsp_t desc_disc_rsp; /**< Descriptor Discovery Response Event Parameters. */ - ble_gattc_evt_char_val_by_uuid_read_rsp_t char_val_by_uuid_read_rsp; /**< Characteristic Value Read by UUID Response Event Parameters. */ - ble_gattc_evt_read_rsp_t read_rsp; /**< Read Response Event Parameters. */ - ble_gattc_evt_char_vals_read_rsp_t char_vals_read_rsp; /**< Characteristic Values Read Response Event Parameters. */ - ble_gattc_evt_write_rsp_t write_rsp; /**< Write Response Event Parameters. */ - ble_gattc_evt_hvx_t hvx; /**< Handle Value Notification/Indication Event Parameters. */ - ble_gattc_evt_exchange_mtu_rsp_t exchange_mtu_rsp; /**< Exchange MTU Response Event Parameters. */ - ble_gattc_evt_timeout_t timeout; /**< Timeout Event Parameters. */ - ble_gattc_evt_attr_info_disc_rsp_t attr_info_disc_rsp; /**< Attribute Information Discovery Event Parameters. */ - ble_gattc_evt_write_cmd_tx_complete_t write_cmd_tx_complete; /**< Write without Response transmission complete Event Parameters. */ - } params; /**< Event Parameters. @note Only valid if @ref gatt_status == @ref BLE_GATT_STATUS_SUCCESS. */ + uint16_t conn_handle; /**< Connection Handle on which event occurred. */ + uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ + uint16_t error_handle; /**< In case of error: The handle causing the error. In all other cases @ref BLE_GATT_HANDLE_INVALID. */ + union + { + ble_gattc_evt_prim_srvc_disc_rsp_t prim_srvc_disc_rsp; /**< Primary Service Discovery Response Event Parameters. */ + ble_gattc_evt_rel_disc_rsp_t rel_disc_rsp; /**< Relationship Discovery Response Event Parameters. */ + ble_gattc_evt_char_disc_rsp_t char_disc_rsp; /**< Characteristic Discovery Response Event Parameters. */ + ble_gattc_evt_desc_disc_rsp_t desc_disc_rsp; /**< Descriptor Discovery Response Event Parameters. */ + ble_gattc_evt_char_val_by_uuid_read_rsp_t char_val_by_uuid_read_rsp; /**< Characteristic Value Read by UUID Response Event Parameters. */ + ble_gattc_evt_read_rsp_t read_rsp; /**< Read Response Event Parameters. */ + ble_gattc_evt_char_vals_read_rsp_t char_vals_read_rsp; /**< Characteristic Values Read Response Event Parameters. */ + ble_gattc_evt_write_rsp_t write_rsp; /**< Write Response Event Parameters. */ + ble_gattc_evt_hvx_t hvx; /**< Handle Value Notification/Indication Event Parameters. */ + ble_gattc_evt_exchange_mtu_rsp_t exchange_mtu_rsp; /**< Exchange MTU Response Event Parameters. */ + ble_gattc_evt_timeout_t timeout; /**< Timeout Event Parameters. */ + ble_gattc_evt_attr_info_disc_rsp_t attr_info_disc_rsp; /**< Attribute Information Discovery Event Parameters. */ + ble_gattc_evt_write_cmd_tx_complete_t write_cmd_tx_complete; /**< Write without Response transmission complete Event Parameters. */ + } params; /**< Event Parameters. @note Only valid if @ref gatt_status == @ref BLE_GATT_STATUS_SUCCESS. */ } ble_gattc_evt_t; /** @} */ @@ -621,7 +621,7 @@ SVCALL(SD_BLE_GATTC_HV_CONFIRM, uint32_t, sd_ble_gattc_hv_confirm(uint16_t conn_ * @retval ::NRF_ERROR_BUSY Client procedure already in progress. * @retval ::NRF_ERROR_TIMEOUT There has been a GATT procedure timeout. No new GATT procedure can be performed without reestablishing the connection. */ -SVCALL(SD_BLE_GATTC_ATTR_INFO_DISCOVER, uint32_t, sd_ble_gattc_attr_info_discover(uint16_t conn_handle, ble_gattc_handle_range_t const * p_handle_range)); +SVCALL(SD_BLE_GATTC_ATTR_INFO_DISCOVER, uint32_t, sd_ble_gattc_attr_info_discover(uint16_t conn_handle, ble_gattc_handle_range_t const *p_handle_range)); /**@brief Start an ATT_MTU exchange by sending an Exchange MTU Request to the server. * @@ -685,22 +685,18 @@ __STATIC_INLINE uint32_t sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(ble_gat #ifndef SUPPRESS_INLINE_IMPLEMENTATION -__STATIC_INLINE uint32_t sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(ble_gattc_evt_t *p_gattc_evt, ble_gattc_handle_value_t *p_iter) -{ - uint32_t value_len = p_gattc_evt->params.char_val_by_uuid_read_rsp.value_len; - uint8_t *p_first = p_gattc_evt->params.char_val_by_uuid_read_rsp.handle_value; - uint8_t *p_next = p_iter->p_value ? p_iter->p_value + value_len : p_first; +__STATIC_INLINE uint32_t sd_ble_gattc_evt_char_val_by_uuid_read_rsp_iter(ble_gattc_evt_t *p_gattc_evt, ble_gattc_handle_value_t *p_iter) { + uint32_t value_len = p_gattc_evt->params.char_val_by_uuid_read_rsp.value_len; + uint8_t *p_first = p_gattc_evt->params.char_val_by_uuid_read_rsp.handle_value; + uint8_t *p_next = p_iter->p_value ? p_iter->p_value + value_len : p_first; - if ((p_next - p_first) / (sizeof(uint16_t) + value_len) < p_gattc_evt->params.char_val_by_uuid_read_rsp.count) - { - p_iter->handle = (uint16_t)p_next[1] << 8 | p_next[0]; - p_iter->p_value = p_next + sizeof(uint16_t); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_NOT_FOUND; - } + if ((p_next - p_first) / (sizeof(uint16_t) + value_len) < p_gattc_evt->params.char_val_by_uuid_read_rsp.count) { + p_iter->handle = (uint16_t)p_next[1] << 8 | p_next[0]; + p_iter->p_value = p_next + sizeof(uint16_t); + return NRF_SUCCESS; + } else { + return NRF_ERROR_NOT_FOUND; + } } #endif /* SUPPRESS_INLINE_IMPLEMENTATION */ diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gatts.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gatts.h index 394d8d1897..1a7a51ac1e 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gatts.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_gatts.h @@ -67,20 +67,20 @@ extern "C" { */ enum BLE_GATTS_SVCS { - SD_BLE_GATTS_SERVICE_ADD = BLE_GATTS_SVC_BASE, /**< Add a service. */ - SD_BLE_GATTS_INCLUDE_ADD, /**< Add an included service. */ - SD_BLE_GATTS_CHARACTERISTIC_ADD, /**< Add a characteristic. */ - SD_BLE_GATTS_DESCRIPTOR_ADD, /**< Add a generic attribute. */ - SD_BLE_GATTS_VALUE_SET, /**< Set an attribute value. */ - SD_BLE_GATTS_VALUE_GET, /**< Get an attribute value. */ - SD_BLE_GATTS_HVX, /**< Handle Value Notification or Indication. */ - SD_BLE_GATTS_SERVICE_CHANGED, /**< Perform a Service Changed Indication to one or more peers. */ - SD_BLE_GATTS_RW_AUTHORIZE_REPLY, /**< Reply to an authorization request for a read or write operation on one or more attributes. */ - SD_BLE_GATTS_SYS_ATTR_SET, /**< Set the persistent system attributes for a connection. */ - SD_BLE_GATTS_SYS_ATTR_GET, /**< Retrieve the persistent system attributes. */ - SD_BLE_GATTS_INITIAL_USER_HANDLE_GET, /**< Retrieve the first valid user handle. */ - SD_BLE_GATTS_ATTR_GET, /**< Retrieve the UUID and/or metadata of an attribute. */ - SD_BLE_GATTS_EXCHANGE_MTU_REPLY /**< Reply to Exchange MTU Request. */ + SD_BLE_GATTS_SERVICE_ADD = BLE_GATTS_SVC_BASE, /**< Add a service. */ + SD_BLE_GATTS_INCLUDE_ADD, /**< Add an included service. */ + SD_BLE_GATTS_CHARACTERISTIC_ADD, /**< Add a characteristic. */ + SD_BLE_GATTS_DESCRIPTOR_ADD, /**< Add a generic attribute. */ + SD_BLE_GATTS_VALUE_SET, /**< Set an attribute value. */ + SD_BLE_GATTS_VALUE_GET, /**< Get an attribute value. */ + SD_BLE_GATTS_HVX, /**< Handle Value Notification or Indication. */ + SD_BLE_GATTS_SERVICE_CHANGED, /**< Perform a Service Changed Indication to one or more peers. */ + SD_BLE_GATTS_RW_AUTHORIZE_REPLY, /**< Reply to an authorization request for a read or write operation on one or more attributes. */ + SD_BLE_GATTS_SYS_ATTR_SET, /**< Set the persistent system attributes for a connection. */ + SD_BLE_GATTS_SYS_ATTR_GET, /**< Retrieve the persistent system attributes. */ + SD_BLE_GATTS_INITIAL_USER_HANDLE_GET, /**< Retrieve the first valid user handle. */ + SD_BLE_GATTS_ATTR_GET, /**< Retrieve the UUID and/or metadata of an attribute. */ + SD_BLE_GATTS_EXCHANGE_MTU_REPLY /**< Reply to Exchange MTU Request. */ }; /** @@ -88,14 +88,14 @@ enum BLE_GATTS_SVCS */ enum BLE_GATTS_EVTS { - BLE_GATTS_EVT_WRITE = BLE_GATTS_EVT_BASE, /**< Write operation performed. \n See @ref ble_gatts_evt_write_t. */ - BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST, /**< Read/Write Authorization request. \n Reply with @ref sd_ble_gatts_rw_authorize_reply. \n See @ref ble_gatts_evt_rw_authorize_request_t. */ - BLE_GATTS_EVT_SYS_ATTR_MISSING, /**< A persistent system attribute access is pending. \n Respond with @ref sd_ble_gatts_sys_attr_set. \n See @ref ble_gatts_evt_sys_attr_missing_t. */ - BLE_GATTS_EVT_HVC, /**< Handle Value Confirmation. \n See @ref ble_gatts_evt_hvc_t. */ - BLE_GATTS_EVT_SC_CONFIRM, /**< Service Changed Confirmation. \n No additional event structure applies. */ - BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST, /**< Exchange MTU Request. \n Reply with @ref sd_ble_gatts_exchange_mtu_reply. \n See @ref ble_gatts_evt_exchange_mtu_request_t. */ - BLE_GATTS_EVT_TIMEOUT, /**< Peer failed to respond to an ATT request in time. \n See @ref ble_gatts_evt_timeout_t. */ - BLE_GATTS_EVT_HVN_TX_COMPLETE /**< Handle Value Notification transmission complete. \n See @ref ble_gatts_evt_hvn_tx_complete_t. */ + BLE_GATTS_EVT_WRITE = BLE_GATTS_EVT_BASE, /**< Write operation performed. \n See @ref ble_gatts_evt_write_t. */ + BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST, /**< Read/Write Authorization request. \n Reply with @ref sd_ble_gatts_rw_authorize_reply. \n See @ref ble_gatts_evt_rw_authorize_request_t. */ + BLE_GATTS_EVT_SYS_ATTR_MISSING, /**< A persistent system attribute access is pending. \n Respond with @ref sd_ble_gatts_sys_attr_set. \n See @ref ble_gatts_evt_sys_attr_missing_t. */ + BLE_GATTS_EVT_HVC, /**< Handle Value Confirmation. \n See @ref ble_gatts_evt_hvc_t. */ + BLE_GATTS_EVT_SC_CONFIRM, /**< Service Changed Confirmation. \n No additional event structure applies. */ + BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST, /**< Exchange MTU Request. \n Reply with @ref sd_ble_gatts_exchange_mtu_reply. \n See @ref ble_gatts_evt_exchange_mtu_request_t. */ + BLE_GATTS_EVT_TIMEOUT, /**< Peer failed to respond to an ATT request in time. \n See @ref ble_gatts_evt_timeout_t. */ + BLE_GATTS_EVT_HVN_TX_COMPLETE /**< Handle Value Notification transmission complete. \n See @ref ble_gatts_evt_hvn_tx_complete_t. */ }; /**@brief GATTS Configuration IDs. @@ -104,8 +104,8 @@ enum BLE_GATTS_EVTS */ enum BLE_GATTS_CFGS { - BLE_GATTS_CFG_SERVICE_CHANGED = BLE_GATTS_CFG_BASE, /**< Service changed configuration. */ - BLE_GATTS_CFG_ATTR_TAB_SIZE, /**< Attribute table size configuration. */ + BLE_GATTS_CFG_SERVICE_CHANGED = BLE_GATTS_CFG_BASE, /**< Service changed configuration. */ + BLE_GATTS_CFG_ATTR_TAB_SIZE, /**< Attribute table size configuration. */ }; /** @} */ @@ -207,31 +207,31 @@ enum BLE_GATTS_CFGS */ typedef struct { - uint8_t hvn_tx_queue_size; /**< Minimum guaranteed number of Handle Value Notifications that can be queued for transmission. + uint8_t hvn_tx_queue_size; /**< Minimum guaranteed number of Handle Value Notifications that can be queued for transmission. The default value is @ref BLE_GATTS_HVN_TX_QUEUE_SIZE_DEFAULT */ } ble_gatts_conn_cfg_t; /**@brief Attribute metadata. */ typedef struct { - ble_gap_conn_sec_mode_t read_perm; /**< Read permissions. */ - ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ - uint8_t vlen :1; /**< Variable length attribute. */ - uint8_t vloc :2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ - uint8_t rd_auth :1; /**< Read authorization and value will be requested from the application on every read operation. */ - uint8_t wr_auth :1; /**< Write authorization will be requested from the application on every Write Request operation (but not Write Command). */ + ble_gap_conn_sec_mode_t read_perm; /**< Read permissions. */ + ble_gap_conn_sec_mode_t write_perm; /**< Write permissions. */ + uint8_t vlen : 1; /**< Variable length attribute. */ + uint8_t vloc : 2; /**< Value location, see @ref BLE_GATTS_VLOCS.*/ + uint8_t rd_auth : 1; /**< Read authorization and value will be requested from the application on every read operation. */ + uint8_t wr_auth : 1; /**< Write authorization will be requested from the application on every Write Request operation (but not Write Command). */ } ble_gatts_attr_md_t; /**@brief GATT Attribute. */ typedef struct { - ble_uuid_t const *p_uuid; /**< Pointer to the attribute UUID. */ - ble_gatts_attr_md_t const *p_attr_md; /**< Pointer to the attribute metadata structure. */ - uint16_t init_len; /**< Initial attribute value length in bytes. */ - uint16_t init_offs; /**< Initial attribute value offset in bytes. If different from zero, the first init_offs bytes of the attribute value will be left uninitialized. */ - uint16_t max_len; /**< Maximum attribute value length in bytes, see @ref BLE_GATTS_ATTR_LENS_MAX for maximum values. */ - uint8_t *p_value; /**< Pointer to the attribute data. Please note that if the @ref BLE_GATTS_VLOC_USER value location is selected in the attribute metadata, this will have to point to a buffer + ble_uuid_t const *p_uuid; /**< Pointer to the attribute UUID. */ + ble_gatts_attr_md_t const *p_attr_md; /**< Pointer to the attribute metadata structure. */ + uint16_t init_len; /**< Initial attribute value length in bytes. */ + uint16_t init_offs; /**< Initial attribute value offset in bytes. If different from zero, the first init_offs bytes of the attribute value will be left uninitialized. */ + uint16_t max_len; /**< Maximum attribute value length in bytes, see @ref BLE_GATTS_ATTR_LENS_MAX for maximum values. */ + uint8_t *p_value; /**< Pointer to the attribute data. Please note that if the @ref BLE_GATTS_VLOC_USER value location is selected in the attribute metadata, this will have to point to a buffer that remains valid through the lifetime of the attribute. This excludes usage of automatic variables that may go out of scope or any other temporary location. The stack may access that memory directly without the application's knowledge. For writable characteristics, this value must not be a location in flash memory.*/ } ble_gatts_attr_t; @@ -239,9 +239,9 @@ typedef struct /**@brief GATT Attribute Value. */ typedef struct { - uint16_t len; /**< Length in bytes to be written or read. Length in bytes written or read after successful return.*/ - uint16_t offset; /**< Attribute value offset. */ - uint8_t *p_value; /**< Pointer to where value is stored or will be stored. + uint16_t len; /**< Length in bytes to be written or read. Length in bytes written or read after successful return.*/ + uint16_t offset; /**< Attribute value offset. */ + uint8_t *p_value; /**< Pointer to where value is stored or will be stored. If value is stored in user memory, only the attribute length is updated when p_value == NULL. Set to NULL when reading to obtain the complete length of the attribute value */ } ble_gatts_value_t; @@ -250,75 +250,75 @@ typedef struct /**@brief GATT Characteristic Presentation Format. */ typedef struct { - uint8_t format; /**< Format of the value, see @ref BLE_GATT_CPF_FORMATS. */ - int8_t exponent; /**< Exponent for integer data types. */ - uint16_t unit; /**< Unit from Bluetooth Assigned Numbers. */ - uint8_t name_space; /**< Namespace from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ - uint16_t desc; /**< Namespace description from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ + uint8_t format; /**< Format of the value, see @ref BLE_GATT_CPF_FORMATS. */ + int8_t exponent; /**< Exponent for integer data types. */ + uint16_t unit; /**< Unit from Bluetooth Assigned Numbers. */ + uint8_t name_space; /**< Namespace from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ + uint16_t desc; /**< Namespace description from Bluetooth Assigned Numbers, see @ref BLE_GATT_CPF_NAMESPACES. */ } ble_gatts_char_pf_t; /**@brief GATT Characteristic metadata. */ typedef struct { - ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ - ble_gatt_char_ext_props_t char_ext_props; /**< Characteristic Extended Properties. */ - uint8_t const *p_char_user_desc; /**< Pointer to a UTF-8 encoded string (non-NULL terminated), NULL if the descriptor is not required. */ - uint16_t char_user_desc_max_size; /**< The maximum size in bytes of the user description descriptor. */ - uint16_t char_user_desc_size; /**< The size of the user description, must be smaller or equal to char_user_desc_max_size. */ - ble_gatts_char_pf_t const *p_char_pf; /**< Pointer to a presentation format structure or NULL if the CPF descriptor is not required. */ - ble_gatts_attr_md_t const *p_user_desc_md; /**< Attribute metadata for the User Description descriptor, or NULL for default values. */ - ble_gatts_attr_md_t const *p_cccd_md; /**< Attribute metadata for the Client Characteristic Configuration Descriptor, or NULL for default values. */ - ble_gatts_attr_md_t const *p_sccd_md; /**< Attribute metadata for the Server Characteristic Configuration Descriptor, or NULL for default values. */ + ble_gatt_char_props_t char_props; /**< Characteristic Properties. */ + ble_gatt_char_ext_props_t char_ext_props; /**< Characteristic Extended Properties. */ + uint8_t const *p_char_user_desc; /**< Pointer to a UTF-8 encoded string (non-NULL terminated), NULL if the descriptor is not required. */ + uint16_t char_user_desc_max_size; /**< The maximum size in bytes of the user description descriptor. */ + uint16_t char_user_desc_size; /**< The size of the user description, must be smaller or equal to char_user_desc_max_size. */ + ble_gatts_char_pf_t const *p_char_pf; /**< Pointer to a presentation format structure or NULL if the CPF descriptor is not required. */ + ble_gatts_attr_md_t const *p_user_desc_md; /**< Attribute metadata for the User Description descriptor, or NULL for default values. */ + ble_gatts_attr_md_t const *p_cccd_md; /**< Attribute metadata for the Client Characteristic Configuration Descriptor, or NULL for default values. */ + ble_gatts_attr_md_t const *p_sccd_md; /**< Attribute metadata for the Server Characteristic Configuration Descriptor, or NULL for default values. */ } ble_gatts_char_md_t; /**@brief GATT Characteristic Definition Handles. */ typedef struct { - uint16_t value_handle; /**< Handle to the characteristic value. */ - uint16_t user_desc_handle; /**< Handle to the User Description descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ - uint16_t cccd_handle; /**< Handle to the Client Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ - uint16_t sccd_handle; /**< Handle to the Server Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ + uint16_t value_handle; /**< Handle to the characteristic value. */ + uint16_t user_desc_handle; /**< Handle to the User Description descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ + uint16_t cccd_handle; /**< Handle to the Client Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ + uint16_t sccd_handle; /**< Handle to the Server Characteristic Configuration Descriptor, or @ref BLE_GATT_HANDLE_INVALID if not present. */ } ble_gatts_char_handles_t; /**@brief GATT HVx parameters. */ typedef struct { - uint16_t handle; /**< Characteristic Value Handle. */ - uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ - uint16_t offset; /**< Offset within the attribute value. */ - uint16_t *p_len; /**< Length in bytes to be written, length in bytes written after return. */ - uint8_t const *p_data; /**< Actual data content, use NULL to use the current attribute value. */ + uint16_t handle; /**< Characteristic Value Handle. */ + uint8_t type; /**< Indication or Notification, see @ref BLE_GATT_HVX_TYPES. */ + uint16_t offset; /**< Offset within the attribute value. */ + uint16_t *p_len; /**< Length in bytes to be written, length in bytes written after return. */ + uint8_t const *p_data; /**< Actual data content, use NULL to use the current attribute value. */ } ble_gatts_hvx_params_t; /**@brief GATT Authorization parameters. */ typedef struct { - uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ - uint8_t update : 1; /**< If set, data supplied in p_data will be used to update the attribute value. + uint16_t gatt_status; /**< GATT status code for the operation, see @ref BLE_GATT_STATUS_CODES. */ + uint8_t update : 1; /**< If set, data supplied in p_data will be used to update the attribute value. Please note that for @ref BLE_GATTS_AUTHORIZE_TYPE_WRITE operations this bit must always be set, as the data to be written needs to be stored and later provided by the application. */ - uint16_t offset; /**< Offset of the attribute value being updated. */ - uint16_t len; /**< Length in bytes of the value in p_data pointer, see @ref BLE_GATTS_ATTR_LENS_MAX. */ - uint8_t const *p_data; /**< Pointer to new value used to update the attribute value. */ + uint16_t offset; /**< Offset of the attribute value being updated. */ + uint16_t len; /**< Length in bytes of the value in p_data pointer, see @ref BLE_GATTS_ATTR_LENS_MAX. */ + uint8_t const *p_data; /**< Pointer to new value used to update the attribute value. */ } ble_gatts_authorize_params_t; /**@brief GATT Read or Write Authorize Reply parameters. */ typedef struct { - uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ - union { - ble_gatts_authorize_params_t read; /**< Read authorization parameters. */ - ble_gatts_authorize_params_t write; /**< Write authorization parameters. */ - } params; /**< Reply Parameters. */ + uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ + union { + ble_gatts_authorize_params_t read; /**< Read authorization parameters. */ + ble_gatts_authorize_params_t write; /**< Write authorization parameters. */ + } params; /**< Reply Parameters. */ } ble_gatts_rw_authorize_reply_params_t; /**@brief Service Changed Inclusion configuration parameters, set with @ref sd_ble_cfg_set. */ typedef struct { - uint8_t service_changed : 1; /**< If 1, include the Service Changed characteristic in the Attribute Table. Default is @ref BLE_GATTS_SERVICE_CHANGED_DEFAULT. */ + uint8_t service_changed : 1; /**< If 1, include the Service Changed characteristic in the Attribute Table. Default is @ref BLE_GATTS_SERVICE_CHANGED_DEFAULT. */ } ble_gatts_cfg_service_changed_t; /**@brief Attribute table size configuration parameters, set with @ref sd_ble_cfg_set. @@ -330,93 +330,93 @@ typedef struct */ typedef struct { - uint32_t attr_tab_size; /**< Attribute table size. Default is @ref BLE_GATTS_ATTR_TAB_SIZE_DEFAULT, minimum is @ref BLE_GATTS_ATTR_TAB_SIZE_MIN. */ + uint32_t attr_tab_size; /**< Attribute table size. Default is @ref BLE_GATTS_ATTR_TAB_SIZE_DEFAULT, minimum is @ref BLE_GATTS_ATTR_TAB_SIZE_MIN. */ } ble_gatts_cfg_attr_tab_size_t; /**@brief Config structure for GATTS configurations. */ typedef union { - ble_gatts_cfg_service_changed_t service_changed; /**< Include service changed characteristic, cfg_id is @ref BLE_GATTS_CFG_SERVICE_CHANGED. */ - ble_gatts_cfg_attr_tab_size_t attr_tab_size; /**< Attribute table size, cfg_id is @ref BLE_GATTS_CFG_ATTR_TAB_SIZE. */ + ble_gatts_cfg_service_changed_t service_changed; /**< Include service changed characteristic, cfg_id is @ref BLE_GATTS_CFG_SERVICE_CHANGED. */ + ble_gatts_cfg_attr_tab_size_t attr_tab_size; /**< Attribute table size, cfg_id is @ref BLE_GATTS_CFG_ATTR_TAB_SIZE. */ } ble_gatts_cfg_t; /**@brief Event structure for @ref BLE_GATTS_EVT_WRITE. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - ble_uuid_t uuid; /**< Attribute UUID. */ - uint8_t op; /**< Type of write operation, see @ref BLE_GATTS_OPS. */ - uint8_t auth_required; /**< Writing operation deferred due to authorization requirement. Application may use @ref sd_ble_gatts_value_set to finalize the writing operation. */ - uint16_t offset; /**< Offset for the write operation. */ - uint16_t len; /**< Length of the received data. */ - uint8_t data[1]; /**< Received data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. + uint16_t handle; /**< Attribute Handle. */ + ble_uuid_t uuid; /**< Attribute UUID. */ + uint8_t op; /**< Type of write operation, see @ref BLE_GATTS_OPS. */ + uint8_t auth_required; /**< Writing operation deferred due to authorization requirement. Application may use @ref sd_ble_gatts_value_set to finalize the writing operation. */ + uint16_t offset; /**< Offset for the write operation. */ + uint16_t len; /**< Length of the received data. */ + uint8_t data[1]; /**< Received data. @note This is a variable length array. The size of 1 indicated is only a placeholder for compilation. See @ref sd_ble_evt_get for more information on how to use event structures with variable length array members. */ } ble_gatts_evt_write_t; /**@brief Event substructure for authorized read requests, see @ref ble_gatts_evt_rw_authorize_request_t. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ - ble_uuid_t uuid; /**< Attribute UUID. */ - uint16_t offset; /**< Offset for the read operation. */ + uint16_t handle; /**< Attribute Handle. */ + ble_uuid_t uuid; /**< Attribute UUID. */ + uint16_t offset; /**< Offset for the read operation. */ } ble_gatts_evt_read_t; /**@brief Event structure for @ref BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST. */ typedef struct { - uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ - union { - ble_gatts_evt_read_t read; /**< Attribute Read Parameters. */ - ble_gatts_evt_write_t write; /**< Attribute Write Parameters. */ - } request; /**< Request Parameters. */ + uint8_t type; /**< Type of authorize operation, see @ref BLE_GATTS_AUTHORIZE_TYPES. */ + union { + ble_gatts_evt_read_t read; /**< Attribute Read Parameters. */ + ble_gatts_evt_write_t write; /**< Attribute Write Parameters. */ + } request; /**< Request Parameters. */ } ble_gatts_evt_rw_authorize_request_t; /**@brief Event structure for @ref BLE_GATTS_EVT_SYS_ATTR_MISSING. */ typedef struct { - uint8_t hint; /**< Hint (currently unused). */ + uint8_t hint; /**< Hint (currently unused). */ } ble_gatts_evt_sys_attr_missing_t; /**@brief Event structure for @ref BLE_GATTS_EVT_HVC. */ typedef struct { - uint16_t handle; /**< Attribute Handle. */ + uint16_t handle; /**< Attribute Handle. */ } ble_gatts_evt_hvc_t; /**@brief Event structure for @ref BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST. */ typedef struct { - uint16_t client_rx_mtu; /**< Client RX MTU size. */ + uint16_t client_rx_mtu; /**< Client RX MTU size. */ } ble_gatts_evt_exchange_mtu_request_t; /**@brief Event structure for @ref BLE_GATTS_EVT_TIMEOUT. */ typedef struct { - uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ + uint8_t src; /**< Timeout source, see @ref BLE_GATT_TIMEOUT_SOURCES. */ } ble_gatts_evt_timeout_t; /**@brief Event structure for @ref BLE_GATTS_EVT_HVN_TX_COMPLETE. */ typedef struct { - uint8_t count; /**< Number of notification transmissions completed. */ + uint8_t count; /**< Number of notification transmissions completed. */ } ble_gatts_evt_hvn_tx_complete_t; /**@brief GATTS event structure. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which the event occurred. */ - union - { - ble_gatts_evt_write_t write; /**< Write Event Parameters. */ - ble_gatts_evt_rw_authorize_request_t authorize_request; /**< Read or Write Authorize Request Parameters. */ - ble_gatts_evt_sys_attr_missing_t sys_attr_missing; /**< System attributes missing. */ - ble_gatts_evt_hvc_t hvc; /**< Handle Value Confirmation Event Parameters. */ - ble_gatts_evt_exchange_mtu_request_t exchange_mtu_request; /**< Exchange MTU Request Event Parameters. */ - ble_gatts_evt_timeout_t timeout; /**< Timeout Event. */ - ble_gatts_evt_hvn_tx_complete_t hvn_tx_complete; /**< Handle Value Notification transmission complete Event Parameters. */ - } params; /**< Event Parameters. */ + uint16_t conn_handle; /**< Connection Handle on which the event occurred. */ + union + { + ble_gatts_evt_write_t write; /**< Write Event Parameters. */ + ble_gatts_evt_rw_authorize_request_t authorize_request; /**< Read or Write Authorize Request Parameters. */ + ble_gatts_evt_sys_attr_missing_t sys_attr_missing; /**< System attributes missing. */ + ble_gatts_evt_hvc_t hvc; /**< Handle Value Confirmation Event Parameters. */ + ble_gatts_evt_exchange_mtu_request_t exchange_mtu_request; /**< Exchange MTU Request Event Parameters. */ + ble_gatts_evt_timeout_t timeout; /**< Timeout Event. */ + ble_gatts_evt_hvn_tx_complete_t hvn_tx_complete; /**< Handle Value Notification transmission complete Event Parameters. */ + } params; /**< Event Parameters. */ } ble_gatts_evt_t; /** @} */ @@ -443,7 +443,7 @@ typedef struct * @retval ::NRF_ERROR_FORBIDDEN Forbidden value supplied, certain UUIDs are reserved for the stack. * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation. */ -SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type, ble_uuid_t const *p_uuid, uint16_t *p_handle)); +SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type, ble_uuid_t const *p_uuid, uint16_t * p_handle)); /**@brief Add an include declaration to the Attribute Table. @@ -469,7 +469,7 @@ SVCALL(SD_BLE_GATTS_SERVICE_ADD, uint32_t, sd_ble_gatts_service_add(uint8_t type * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation. * @retval ::NRF_ERROR_NOT_FOUND Attribute not found. */ -SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t service_handle, uint16_t inc_srvc_handle, uint16_t *p_include_handle)); +SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t service_handle, uint16_t inc_srvc_handle, uint16_t * p_include_handle)); /**@brief Add a characteristic declaration, a characteristic value declaration and optional characteristic descriptor declarations to the Attribute Table. @@ -498,7 +498,7 @@ SVCALL(SD_BLE_GATTS_INCLUDE_ADD, uint32_t, sd_ble_gatts_include_add(uint16_t ser * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation. * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. */ -SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_add(uint16_t service_handle, ble_gatts_char_md_t const *p_char_md, ble_gatts_attr_t const *p_attr_char_value, ble_gatts_char_handles_t *p_handles)); +SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_add(uint16_t service_handle, ble_gatts_char_md_t const *p_char_md, ble_gatts_attr_t const *p_attr_char_value, ble_gatts_char_handles_t * p_handles)); /**@brief Add a descriptor to the Attribute Table. @@ -521,7 +521,7 @@ SVCALL(SD_BLE_GATTS_CHARACTERISTIC_ADD, uint32_t, sd_ble_gatts_characteristic_ad * @retval ::NRF_ERROR_NO_MEM Not enough memory to complete operation. * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. */ -SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16_t char_handle, ble_gatts_attr_t const *p_attr, uint16_t *p_handle)); +SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16_t char_handle, ble_gatts_attr_t const *p_attr, uint16_t * p_handle)); /**@brief Set the value of a given attribute. * @@ -544,7 +544,7 @@ SVCALL(SD_BLE_GATTS_DESCRIPTOR_ADD, uint32_t, sd_ble_gatts_descriptor_add(uint16 * @retval ::NRF_ERROR_DATA_SIZE Invalid data size(s) supplied, attribute lengths are restricted by @ref BLE_GATTS_ATTR_LENS_MAX. * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied on a system attribute. */ -SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t *p_value)); +SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t * p_value)); /**@brief Get the value of a given attribute. * @@ -568,7 +568,7 @@ SVCALL(SD_BLE_GATTS_VALUE_SET, uint32_t, sd_ble_gatts_value_set(uint16_t conn_ha * @retval ::BLE_ERROR_INVALID_CONN_HANDLE Invalid connection handle supplied on a system attribute. * @retval ::BLE_ERROR_GATTS_SYS_ATTR_MISSING System attributes missing, use @ref sd_ble_gatts_sys_attr_set to set them to a known value. */ -SVCALL(SD_BLE_GATTS_VALUE_GET, uint32_t, sd_ble_gatts_value_get(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t *p_value)); +SVCALL(SD_BLE_GATTS_VALUE_GET, uint32_t, sd_ble_gatts_value_get(uint16_t conn_handle, uint16_t handle, ble_gatts_value_t * p_value)); /**@brief Notify or Indicate an attribute value. * @@ -779,7 +779,7 @@ SVCALL(SD_BLE_GATTS_SYS_ATTR_SET, uint32_t, sd_ble_gatts_sys_attr_set(uint16_t c * @retval ::NRF_ERROR_DATA_SIZE The system attribute information did not fit into the provided buffer. * @retval ::NRF_ERROR_NOT_FOUND No system attributes found. */ -SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t conn_handle, uint8_t *p_sys_attr_data, uint16_t *p_len, uint32_t flags)); +SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t conn_handle, uint8_t * p_sys_attr_data, uint16_t * p_len, uint32_t flags)); /**@brief Retrieve the first valid user attribute handle. @@ -789,7 +789,7 @@ SVCALL(SD_BLE_GATTS_SYS_ATTR_GET, uint32_t, sd_ble_gatts_sys_attr_get(uint16_t c * @retval ::NRF_SUCCESS Successfully retrieved the handle. * @retval ::NRF_ERROR_INVALID_ADDR Invalid pointer supplied. */ -SVCALL(SD_BLE_GATTS_INITIAL_USER_HANDLE_GET, uint32_t, sd_ble_gatts_initial_user_handle_get(uint16_t *p_handle)); +SVCALL(SD_BLE_GATTS_INITIAL_USER_HANDLE_GET, uint32_t, sd_ble_gatts_initial_user_handle_get(uint16_t * p_handle)); /**@brief Retrieve the attribute UUID and/or metadata. * diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_l2cap.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_l2cap.h index 7587350cf9..933f398b57 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_l2cap.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_l2cap.h @@ -84,32 +84,32 @@ extern "C" { /**@brief L2CAP API SVC numbers. */ enum BLE_L2CAP_SVCS { - SD_BLE_L2CAP_CH_SETUP = BLE_L2CAP_SVC_BASE + 0, /**< Set up an L2CAP channel. */ - SD_BLE_L2CAP_CH_RELEASE = BLE_L2CAP_SVC_BASE + 1, /**< Release an L2CAP channel. */ - SD_BLE_L2CAP_CH_RX = BLE_L2CAP_SVC_BASE + 2, /**< Receive an SDU on an L2CAP channel. */ - SD_BLE_L2CAP_CH_TX = BLE_L2CAP_SVC_BASE + 3, /**< Transmit an SDU on an L2CAP channel. */ - SD_BLE_L2CAP_CH_FLOW_CONTROL = BLE_L2CAP_SVC_BASE + 4, /**< Advanced SDU reception flow control. */ + SD_BLE_L2CAP_CH_SETUP = BLE_L2CAP_SVC_BASE + 0,/**< Set up an L2CAP channel. */ + SD_BLE_L2CAP_CH_RELEASE = BLE_L2CAP_SVC_BASE + 1,/**< Release an L2CAP channel. */ + SD_BLE_L2CAP_CH_RX = BLE_L2CAP_SVC_BASE + 2,/**< Receive an SDU on an L2CAP channel. */ + SD_BLE_L2CAP_CH_TX = BLE_L2CAP_SVC_BASE + 3,/**< Transmit an SDU on an L2CAP channel. */ + SD_BLE_L2CAP_CH_FLOW_CONTROL = BLE_L2CAP_SVC_BASE + 4, /**< Advanced SDU reception flow control. */ }; /**@brief L2CAP Event IDs. */ enum BLE_L2CAP_EVTS { - BLE_L2CAP_EVT_CH_SETUP_REQUEST = BLE_L2CAP_EVT_BASE + 0, /**< L2CAP Channel Setup Request event. + BLE_L2CAP_EVT_CH_SETUP_REQUEST = BLE_L2CAP_EVT_BASE + 0, /**< L2CAP Channel Setup Request event. \n Reply with @ref sd_ble_l2cap_ch_setup. \n See @ref ble_l2cap_evt_ch_setup_request_t. */ - BLE_L2CAP_EVT_CH_SETUP_REFUSED = BLE_L2CAP_EVT_BASE + 1, /**< L2CAP Channel Setup Refused event. + BLE_L2CAP_EVT_CH_SETUP_REFUSED = BLE_L2CAP_EVT_BASE + 1, /**< L2CAP Channel Setup Refused event. \n See @ref ble_l2cap_evt_ch_setup_refused_t. */ - BLE_L2CAP_EVT_CH_SETUP = BLE_L2CAP_EVT_BASE + 2, /**< L2CAP Channel Setup Completed event. + BLE_L2CAP_EVT_CH_SETUP = BLE_L2CAP_EVT_BASE + 2, /**< L2CAP Channel Setup Completed event. \n See @ref ble_l2cap_evt_ch_setup_t. */ - BLE_L2CAP_EVT_CH_RELEASED = BLE_L2CAP_EVT_BASE + 3, /**< L2CAP Channel Released event. + BLE_L2CAP_EVT_CH_RELEASED = BLE_L2CAP_EVT_BASE + 3, /**< L2CAP Channel Released event. \n No additional event structure applies. */ - BLE_L2CAP_EVT_CH_SDU_BUF_RELEASED = BLE_L2CAP_EVT_BASE + 4, /**< L2CAP Channel SDU data buffer released event. + BLE_L2CAP_EVT_CH_SDU_BUF_RELEASED = BLE_L2CAP_EVT_BASE + 4, /**< L2CAP Channel SDU data buffer released event. \n See @ref ble_l2cap_evt_ch_sdu_buf_released_t. */ - BLE_L2CAP_EVT_CH_CREDIT = BLE_L2CAP_EVT_BASE + 5, /**< L2CAP Channel Credit received. + BLE_L2CAP_EVT_CH_CREDIT = BLE_L2CAP_EVT_BASE + 5, /**< L2CAP Channel Credit received. \n See @ref ble_l2cap_evt_ch_credit_t. */ - BLE_L2CAP_EVT_CH_RX = BLE_L2CAP_EVT_BASE + 6, /**< L2CAP Channel SDU received. + BLE_L2CAP_EVT_CH_RX = BLE_L2CAP_EVT_BASE + 6, /**< L2CAP Channel SDU received. \n See @ref ble_l2cap_evt_ch_rx_t. */ - BLE_L2CAP_EVT_CH_TX = BLE_L2CAP_EVT_BASE + 7, /**< L2CAP Channel SDU transmitted. + BLE_L2CAP_EVT_CH_TX = BLE_L2CAP_EVT_BASE + 7, /**< L2CAP Channel SDU transmitted. \n See @ref ble_l2cap_evt_ch_tx_t. */ }; @@ -137,9 +137,9 @@ enum BLE_L2CAP_EVTS * @{ */ #define BLE_L2CAP_CH_SETUP_REFUSED_SRC_LOCAL (0x01) /**< Local. */ #define BLE_L2CAP_CH_SETUP_REFUSED_SRC_REMOTE (0x02) /**< Remote. */ - /** @} */ +/** @} */ - /** @defgroup BLE_L2CAP_CH_STATUS_CODES L2CAP channel status codes +/** @defgroup BLE_L2CAP_CH_STATUS_CODES L2CAP channel status codes * @{ */ #define BLE_L2CAP_CH_STATUS_CODE_SUCCESS (0x0000) /**< Success. */ #define BLE_L2CAP_CH_STATUS_CODE_LE_PSM_NOT_SUPPORTED (0x0002) /**< LE_PSM not supported. */ @@ -174,17 +174,17 @@ enum BLE_L2CAP_EVTS */ typedef struct { - uint16_t rx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall + uint16_t rx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall be able to receive on L2CAP channels on connections with this configuration. The minimum value is @ref BLE_L2CAP_MPS_MIN. */ - uint16_t tx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall + uint16_t tx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall be able to transmit on L2CAP channels on connections with this configuration. The minimum value is @ref BLE_L2CAP_MPS_MIN. */ - uint8_t rx_queue_size; /**< Number of SDU data buffers that can be queued for reception per + uint8_t rx_queue_size; /**< Number of SDU data buffers that can be queued for reception per L2CAP channel. The minimum value is one. */ - uint8_t tx_queue_size; /**< Number of SDU data buffers that can be queued for transmission + uint8_t tx_queue_size; /**< Number of SDU data buffers that can be queued for transmission per L2CAP channel. The minimum value is one. */ - uint8_t ch_count; /**< Number of L2CAP channels the application can create per connection + uint8_t ch_count; /**< Number of L2CAP channels the application can create per connection with this configuration. The default value is zero, the maximum value is @ref BLE_L2CAP_CH_COUNT_MAX. @note if this parameter is set to zero, all other parameters in @@ -194,14 +194,14 @@ typedef struct /**@brief L2CAP channel RX parameters. */ typedef struct { - uint16_t rx_mtu; /**< The maximum L2CAP SDU size, in bytes, that L2CAP shall be able to + uint16_t rx_mtu; /**< The maximum L2CAP SDU size, in bytes, that L2CAP shall be able to receive on this L2CAP channel. - Must be equal to or greater than @ref BLE_L2CAP_MTU_MIN. */ - uint16_t rx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall be + uint16_t rx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP shall be able to receive on this L2CAP channel. - Must be equal to or greater than @ref BLE_L2CAP_MPS_MIN. - Must be equal to or less than @ref ble_l2cap_conn_cfg_t::rx_mps. */ - ble_data_t sdu_buf; /**< SDU data buffer for reception. + ble_data_t sdu_buf; /**< SDU data buffer for reception. - If @ref ble_data_t::p_data is non-NULL, initial credits are issued to the peer. - If @ref ble_data_t::p_data is NULL, no initial credits are @@ -211,10 +211,10 @@ typedef struct /**@brief L2CAP channel setup parameters. */ typedef struct { - ble_l2cap_ch_rx_params_t rx_params; /**< L2CAP channel RX parameters. */ - uint16_t le_psm; /**< LE Protocol/Service Multiplexer. Used when requesting + ble_l2cap_ch_rx_params_t rx_params; /**< L2CAP channel RX parameters. */ + uint16_t le_psm; /**< LE Protocol/Service Multiplexer. Used when requesting setup of an L2CAP channel, ignored otherwise. */ - uint16_t status; /**< Status code, see @ref BLE_L2CAP_CH_STATUS_CODES. + uint16_t status; /**< Status code, see @ref BLE_L2CAP_CH_STATUS_CODES. Used when replying to a setup request of an L2CAP channel, ignored otherwise. */ } ble_l2cap_ch_setup_params_t; @@ -222,41 +222,41 @@ typedef struct /**@brief L2CAP channel TX parameters. */ typedef struct { - uint16_t tx_mtu; /**< The maximum L2CAP SDU size, in bytes, that L2CAP is able to + uint16_t tx_mtu; /**< The maximum L2CAP SDU size, in bytes, that L2CAP is able to transmit on this L2CAP channel. */ - uint16_t peer_mps; /**< The maximum L2CAP PDU payload size, in bytes, that the peer is + uint16_t peer_mps; /**< The maximum L2CAP PDU payload size, in bytes, that the peer is able to receive on this L2CAP channel. */ - uint16_t tx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP is able + uint16_t tx_mps; /**< The maximum L2CAP PDU payload size, in bytes, that L2CAP is able to transmit on this L2CAP channel. This is effective tx_mps, selected by the SoftDevice as MIN( @ref ble_l2cap_ch_tx_params_t::peer_mps, @ref ble_l2cap_conn_cfg_t::tx_mps ) */ - uint16_t credits; /**< Initial credits given by the peer. */ + uint16_t credits; /**< Initial credits given by the peer. */ } ble_l2cap_ch_tx_params_t; /**@brief L2CAP Channel Setup Request event. */ typedef struct { - ble_l2cap_ch_tx_params_t tx_params; /**< L2CAP channel TX parameters. */ - uint16_t le_psm; /**< LE Protocol/Service Multiplexer. */ + ble_l2cap_ch_tx_params_t tx_params; /**< L2CAP channel TX parameters. */ + uint16_t le_psm; /**< LE Protocol/Service Multiplexer. */ } ble_l2cap_evt_ch_setup_request_t; /**@brief L2CAP Channel Setup Refused event. */ typedef struct { - uint8_t source; /**< Source, see @ref BLE_L2CAP_CH_SETUP_REFUSED_SRCS */ - uint16_t status; /**< Status code, see @ref BLE_L2CAP_CH_STATUS_CODES */ + uint8_t source; /**< Source, see @ref BLE_L2CAP_CH_SETUP_REFUSED_SRCS */ + uint16_t status; /**< Status code, see @ref BLE_L2CAP_CH_STATUS_CODES */ } ble_l2cap_evt_ch_setup_refused_t; /**@brief L2CAP Channel Setup Completed event. */ typedef struct { - ble_l2cap_ch_tx_params_t tx_params; /**< L2CAP channel TX parameters. */ + ble_l2cap_ch_tx_params_t tx_params; /**< L2CAP channel TX parameters. */ } ble_l2cap_evt_ch_setup_t; /**@brief L2CAP Channel SDU Data Buffer Released event. */ typedef struct { - ble_data_t sdu_buf; /**< Returned reception or transmission SDU data buffer. The SoftDevice + ble_data_t sdu_buf; /**< Returned reception or transmission SDU data buffer. The SoftDevice returns SDU data buffers supplied by the application, which have not yet been returned previously via a @ref BLE_L2CAP_EVT_CH_RX or @ref BLE_L2CAP_EVT_CH_TX event. */ @@ -265,14 +265,14 @@ typedef struct /**@brief L2CAP Channel Credit received event. */ typedef struct { - uint16_t credits; /**< Additional credits given by the peer. */ + uint16_t credits; /**< Additional credits given by the peer. */ } ble_l2cap_evt_ch_credit_t; /**@brief L2CAP Channel received SDU event. */ typedef struct { - uint16_t sdu_len; /**< Total SDU length, in bytes. */ - ble_data_t sdu_buf; /**< SDU data buffer. + uint16_t sdu_len; /**< Total SDU length, in bytes. */ + ble_data_t sdu_buf; /**< SDU data buffer. @note If there is not enough space in the buffer (sdu_buf.len < sdu_len) then the rest of the SDU will be silently discarded by the SoftDevice. */ @@ -281,25 +281,25 @@ typedef struct /**@brief L2CAP Channel transmitted SDU event. */ typedef struct { - ble_data_t sdu_buf; /**< SDU data buffer. */ + ble_data_t sdu_buf; /**< SDU data buffer. */ } ble_l2cap_evt_ch_tx_t; /**@brief L2CAP event structure. */ typedef struct { - uint16_t conn_handle; /**< Connection Handle on which the event occured. */ - uint16_t local_cid; /**< Local Channel ID of the L2CAP channel, or + uint16_t conn_handle; /**< Connection Handle on which the event occured. */ + uint16_t local_cid; /**< Local Channel ID of the L2CAP channel, or @ref BLE_L2CAP_CID_INVALID if not present. */ - union - { - ble_l2cap_evt_ch_setup_request_t ch_setup_request; /**< L2CAP Channel Setup Request Event Parameters. */ - ble_l2cap_evt_ch_setup_refused_t ch_setup_refused; /**< L2CAP Channel Setup Refused Event Parameters. */ - ble_l2cap_evt_ch_setup_t ch_setup; /**< L2CAP Channel Setup Completed Event Parameters. */ - ble_l2cap_evt_ch_sdu_buf_released_t ch_sdu_buf_released;/**< L2CAP Channel SDU Data Buffer Released Event Parameters. */ - ble_l2cap_evt_ch_credit_t credit; /**< L2CAP Channel Credit Received Event Parameters. */ - ble_l2cap_evt_ch_rx_t rx; /**< L2CAP Channel SDU Received Event Parameters. */ - ble_l2cap_evt_ch_tx_t tx; /**< L2CAP Channel SDU Transmitted Event Parameters. */ - } params; /**< Event Parameters. */ + union + { + ble_l2cap_evt_ch_setup_request_t ch_setup_request; /**< L2CAP Channel Setup Request Event Parameters. */ + ble_l2cap_evt_ch_setup_refused_t ch_setup_refused; /**< L2CAP Channel Setup Refused Event Parameters. */ + ble_l2cap_evt_ch_setup_t ch_setup; /**< L2CAP Channel Setup Completed Event Parameters. */ + ble_l2cap_evt_ch_sdu_buf_released_t ch_sdu_buf_released;/**< L2CAP Channel SDU Data Buffer Released Event Parameters. */ + ble_l2cap_evt_ch_credit_t credit; /**< L2CAP Channel Credit Received Event Parameters. */ + ble_l2cap_evt_ch_rx_t rx; /**< L2CAP Channel SDU Received Event Parameters. */ + ble_l2cap_evt_ch_tx_t tx; /**< L2CAP Channel SDU Transmitted Event Parameters. */ + } params; /**< Event Parameters. */ } ble_l2cap_evt_t; /** @} */ @@ -347,7 +347,7 @@ typedef struct * @retval ::NRF_ERROR_RESOURCES The limit has been reached for available L2CAP channels, * see @ref ble_l2cap_conn_cfg_t::ch_count. */ -SVCALL(SD_BLE_L2CAP_CH_SETUP, uint32_t, sd_ble_l2cap_ch_setup(uint16_t conn_handle, uint16_t *p_local_cid, ble_l2cap_ch_setup_params_t const *p_params)); +SVCALL(SD_BLE_L2CAP_CH_SETUP, uint32_t, sd_ble_l2cap_ch_setup(uint16_t conn_handle, uint16_t * p_local_cid, ble_l2cap_ch_setup_params_t const *p_params)); /**@brief Release an L2CAP channel. * @@ -493,7 +493,7 @@ SVCALL(SD_BLE_L2CAP_CH_TX, uint32_t, sd_ble_l2cap_ch_tx(uint16_t conn_handle, ui * in progress for an L2CAP channel). * @retval ::NRF_ERROR_NOT_FOUND CID not found. */ -SVCALL(SD_BLE_L2CAP_CH_FLOW_CONTROL, uint32_t, sd_ble_l2cap_ch_flow_control(uint16_t conn_handle, uint16_t local_cid, uint16_t credits, uint16_t *p_credits)); +SVCALL(SD_BLE_L2CAP_CH_FLOW_CONTROL, uint32_t, sd_ble_l2cap_ch_flow_control(uint16_t conn_handle, uint16_t local_cid, uint16_t credits, uint16_t * p_credits)); /** @} */ diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_types.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_types.h index 88c93180c8..3504959135 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_types.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/ble_types.h @@ -155,27 +155,27 @@ extern "C" { /** @} */ /** @brief Set .type and .uuid fields of ble_uuid_struct to specified UUID value. */ -#define BLE_UUID_BLE_ASSIGN(instance, value) do {\ - instance.type = BLE_UUID_TYPE_BLE; \ - instance.uuid = value;} while(0) +#define BLE_UUID_BLE_ASSIGN(instance, value) do { \ + instance.type = BLE_UUID_TYPE_BLE; \ + instance.uuid = value;} while (0) /** @brief Copy type and uuid members from src to dst ble_uuid_t pointer. Both pointers must be valid/non-null. */ -#define BLE_UUID_COPY_PTR(dst, src) do {\ - (dst)->type = (src)->type; \ - (dst)->uuid = (src)->uuid;} while(0) +#define BLE_UUID_COPY_PTR(dst, src) do { \ + (dst)->type = (src)->type; \ + (dst)->uuid = (src)->uuid;} while (0) /** @brief Copy type and uuid members from src to dst ble_uuid_t struct. */ -#define BLE_UUID_COPY_INST(dst, src) do {\ - (dst).type = (src).type; \ - (dst).uuid = (src).uuid;} while(0) +#define BLE_UUID_COPY_INST(dst, src) do { \ + (dst).type = (src).type; \ + (dst).uuid = (src).uuid;} while (0) /** @brief Compare for equality both type and uuid members of two (valid, non-null) ble_uuid_t pointers. */ #define BLE_UUID_EQ(p_uuid1, p_uuid2) \ - (((p_uuid1)->type == (p_uuid2)->type) && ((p_uuid1)->uuid == (p_uuid2)->uuid)) + (((p_uuid1)->type == (p_uuid2)->type) && ((p_uuid1)->uuid == (p_uuid2)->uuid)) /** @brief Compare for difference both type and uuid members of two (valid, non-null) ble_uuid_t pointers. */ #define BLE_UUID_NEQ(p_uuid1, p_uuid2) \ - (((p_uuid1)->type != (p_uuid2)->type) || ((p_uuid1)->uuid != (p_uuid2)->uuid)) + (((p_uuid1)->type != (p_uuid2)->type) || ((p_uuid1)->uuid != (p_uuid2)->uuid)) /** @} */ @@ -185,21 +185,21 @@ extern "C" { /** @brief 128 bit UUID values. */ typedef struct { - uint8_t uuid128[16]; /**< Little-Endian UUID bytes. */ + uint8_t uuid128[16]; /**< Little-Endian UUID bytes. */ } ble_uuid128_t; /** @brief Bluetooth Low Energy UUID type, encapsulates both 16-bit and 128-bit UUIDs. */ typedef struct { - uint16_t uuid; /**< 16-bit UUID value or octets 12-13 of 128-bit UUID. */ - uint8_t type; /**< UUID type, see @ref BLE_UUID_TYPES. If type is @ref BLE_UUID_TYPE_UNKNOWN, the value of uuid is undefined. */ + uint16_t uuid; /**< 16-bit UUID value or octets 12-13 of 128-bit UUID. */ + uint8_t type; /**< UUID type, see @ref BLE_UUID_TYPES. If type is @ref BLE_UUID_TYPE_UNKNOWN, the value of uuid is undefined. */ } ble_uuid_t; /**@brief Data structure. */ typedef struct { - uint8_t *p_data; /**< Pointer to the data buffer provided to/from the application. */ - uint16_t len; /**< Length of the data buffer, in bytes. */ + uint8_t *p_data; /**< Pointer to the data buffer provided to/from the application. */ + uint16_t len; /**< Length of the data buffer, in bytes. */ } ble_data_t; /** @} */ diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf52/nrf_mbr.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf52/nrf_mbr.h index 42e09fc87c..34132e2101 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf52/nrf_mbr.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf52/nrf_mbr.h @@ -88,19 +88,19 @@ This is the offset where the first byte of the SoftDevice hex file is written. * /**@brief nRF Master Boot Record API SVC numbers. */ enum NRF_MBR_SVCS { - SD_MBR_COMMAND = MBR_SVC_BASE, /**< ::sd_mbr_command */ + SD_MBR_COMMAND = MBR_SVC_BASE, /**< ::sd_mbr_command */ }; /**@brief Possible values for ::sd_mbr_command_t.command */ enum NRF_MBR_COMMANDS { - SD_MBR_COMMAND_COPY_BL, /**< Copy a new BootLoader. @see ::sd_mbr_command_copy_bl_t*/ - SD_MBR_COMMAND_COPY_SD, /**< Copy a new SoftDevice. @see ::sd_mbr_command_copy_sd_t*/ - SD_MBR_COMMAND_INIT_SD, /**< Initialize forwarding interrupts to SD, and run reset function in SD. Does not require any parameters in ::sd_mbr_command_t params.*/ - SD_MBR_COMMAND_COMPARE, /**< This command works like memcmp. @see ::sd_mbr_command_compare_t*/ - SD_MBR_COMMAND_VECTOR_TABLE_BASE_SET, /**< Change the address the MBR starts after a reset. @see ::sd_mbr_command_vector_table_base_set_t*/ - SD_MBR_COMMAND_RESERVED, - SD_MBR_COMMAND_IRQ_FORWARD_ADDRESS_SET, /**< Start forwarding all interrupts to this address. @see ::sd_mbr_command_irq_forward_address_set_t*/ + SD_MBR_COMMAND_COPY_BL, /**< Copy a new BootLoader. @see ::sd_mbr_command_copy_bl_t*/ + SD_MBR_COMMAND_COPY_SD, /**< Copy a new SoftDevice. @see ::sd_mbr_command_copy_sd_t*/ + SD_MBR_COMMAND_INIT_SD, /**< Initialize forwarding interrupts to SD, and run reset function in SD. Does not require any parameters in ::sd_mbr_command_t params.*/ + SD_MBR_COMMAND_COMPARE, /**< This command works like memcmp. @see ::sd_mbr_command_compare_t*/ + SD_MBR_COMMAND_VECTOR_TABLE_BASE_SET, /**< Change the address the MBR starts after a reset. @see ::sd_mbr_command_vector_table_base_set_t*/ + SD_MBR_COMMAND_RESERVED, + SD_MBR_COMMAND_IRQ_FORWARD_ADDRESS_SET, /**< Start forwarding all interrupts to this address. @see ::sd_mbr_command_irq_forward_address_set_t*/ }; /** @} */ @@ -121,9 +121,9 @@ enum NRF_MBR_COMMANDS */ typedef struct { - uint32_t *src; /**< Pointer to the source of data to be copied.*/ - uint32_t *dst; /**< Pointer to the destination where the content is to be copied.*/ - uint32_t len; /**< Number of 32 bit words to copy. Must be a multiple of @ref MBR_PAGE_SIZE_IN_WORDS words.*/ + uint32_t *src; /**< Pointer to the source of data to be copied.*/ + uint32_t *dst; /**< Pointer to the destination where the content is to be copied.*/ + uint32_t len; /**< Number of 32 bit words to copy. Must be a multiple of @ref MBR_PAGE_SIZE_IN_WORDS words.*/ } sd_mbr_command_copy_sd_t; @@ -134,9 +134,9 @@ typedef struct */ typedef struct { - uint32_t *ptr1; /**< Pointer to block of memory. */ - uint32_t *ptr2; /**< Pointer to block of memory. */ - uint32_t len; /**< Number of 32 bit words to compare.*/ + uint32_t *ptr1; /**< Pointer to block of memory. */ + uint32_t *ptr2; /**< Pointer to block of memory. */ + uint32_t len; /**< Number of 32 bit words to compare.*/ } sd_mbr_command_compare_t; @@ -164,8 +164,8 @@ typedef struct */ typedef struct { - uint32_t *bl_src; /**< Pointer to the source of the bootloader to be be copied.*/ - uint32_t bl_len; /**< Number of 32 bit words to copy for BootLoader. */ + uint32_t *bl_src; /**< Pointer to the source of the bootloader to be be copied.*/ + uint32_t bl_len; /**< Number of 32 bit words to copy for BootLoader. */ } sd_mbr_command_copy_bl_t; /**@brief Change the address the MBR starts after a reset @@ -192,7 +192,7 @@ typedef struct */ typedef struct { - uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/ + uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/ } sd_mbr_command_vector_table_base_set_t; /**@brief Sets the base address of the interrupt vector table for interrupts forwarded from the MBR @@ -204,7 +204,7 @@ typedef struct */ typedef struct { - uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/ + uint32_t address; /**< The base address of the interrupt vector table for forwarded interrupts.*/ } sd_mbr_command_irq_forward_address_set_t; /**@brief Input structure containing data used when calling ::sd_mbr_command @@ -215,15 +215,15 @@ typedef struct */ typedef struct { - uint32_t command; /**< Type of command to be issued. See @ref NRF_MBR_COMMANDS. */ - union - { - sd_mbr_command_copy_sd_t copy_sd; /**< Parameters for copy SoftDevice.*/ - sd_mbr_command_compare_t compare; /**< Parameters for verify.*/ - sd_mbr_command_copy_bl_t copy_bl; /**< Parameters for copy BootLoader. Requires parameter page. */ - sd_mbr_command_vector_table_base_set_t base_set; /**< Parameters for vector table base set. Requires parameter page.*/ - sd_mbr_command_irq_forward_address_set_t irq_forward_address_set; /**< Parameters for irq forward address set*/ - } params; /**< Command parameters. */ + uint32_t command; /**< Type of command to be issued. See @ref NRF_MBR_COMMANDS. */ + union + { + sd_mbr_command_copy_sd_t copy_sd; /**< Parameters for copy SoftDevice.*/ + sd_mbr_command_compare_t compare; /**< Parameters for verify.*/ + sd_mbr_command_copy_bl_t copy_bl; /**< Parameters for copy BootLoader. Requires parameter page. */ + sd_mbr_command_vector_table_base_set_t base_set; /**< Parameters for vector table base set. Requires parameter page.*/ + sd_mbr_command_irq_forward_address_set_t irq_forward_address_set; /**< Parameters for irq forward address set*/ + } params; /**< Command parameters. */ } sd_mbr_command_t; /** @} */ @@ -254,7 +254,7 @@ typedef struct * @retval ::NRF_ERROR_NO_MEM No MBR parameter page provided * @retval ::NRF_ERROR_INVALID_PARAM if an invalid command is given. */ -SVCALL(SD_MBR_COMMAND, uint32_t, sd_mbr_command(sd_mbr_command_t* param)); +SVCALL(SD_MBR_COMMAND, uint32_t, sd_mbr_command(sd_mbr_command_t * param)); /** @} */ diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_error.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_error.h index 6badee98e5..7e9bf748d5 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_error.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_error.h @@ -36,7 +36,7 @@ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - /** +/** @defgroup nrf_error SoftDevice Global Error Codes @{ diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_error_sdm.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_error_sdm.h index 530959b9d6..8e43a6102f 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_error_sdm.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_error_sdm.h @@ -36,7 +36,7 @@ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ - /** +/** @addtogroup nrf_sdm_api @{ @defgroup nrf_sdm_error SoftDevice Manager Error Codes diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_nvic.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_nvic.h index 1f79cc3c8c..c2fa90f668 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_nvic.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_nvic.h @@ -77,17 +77,17 @@ extern "C" { /**@brief Interrupt priority levels used by the SoftDevice. */ #define __NRF_NVIC_SD_IRQ_PRIOS ((uint8_t)( \ - (1U << 0) /**< Priority level high .*/ \ + (1U << 0) /**< Priority level high .*/ \ | (1U << 1) /**< Priority level medium. */ \ | (1U << 4) /**< Priority level low. */ \ - )) + )) /**@brief Interrupt priority levels available to the application. */ -#define __NRF_NVIC_APP_IRQ_PRIOS ((uint8_t)~__NRF_NVIC_SD_IRQ_PRIOS) +#define __NRF_NVIC_APP_IRQ_PRIOS ((uint8_t) ~__NRF_NVIC_SD_IRQ_PRIOS) /**@brief Interrupts used by the SoftDevice, with IRQn in the range 0-31. */ #define __NRF_NVIC_SD_IRQS_0 ((uint32_t)( \ - (1U << POWER_CLOCK_IRQn) \ + (1U << POWER_CLOCK_IRQn) \ | (1U << RADIO_IRQn) \ | (1U << RTC0_IRQn) \ | (1U << TIMER0_IRQn) \ @@ -97,7 +97,7 @@ extern "C" { | (1U << TEMP_IRQn) \ | (1U << __NRF_NVIC_NVMC_IRQn) \ | (1U << (uint32_t)SWI5_IRQn) \ - )) + )) /**@brief Interrupts used by the SoftDevice, with IRQn in the range 32-63. */ #define __NRF_NVIC_SD_IRQS_1 ((uint32_t)0) @@ -118,8 +118,8 @@ extern "C" { /**@brief Type representing the state struct for the SoftDevice NVIC module. */ typedef struct { - uint32_t volatile __irq_masks[__NRF_NVIC_ISER_COUNT]; /**< IRQs enabled by the application in the NVIC. */ - uint32_t volatile __cr_flag; /**< Non-zero if already in a critical region */ + uint32_t volatile __irq_masks[__NRF_NVIC_ISER_COUNT]; /**< IRQs enabled by the application in the NVIC. */ + uint32_t volatile __cr_flag; /**< Non-zero if already in a critical region */ } nrf_nvic_state_t; /**@brief Variable keeping the state for the SoftDevice NVIC module. This must be declared in an @@ -196,7 +196,7 @@ __STATIC_INLINE uint32_t sd_nvic_DisableIRQ(IRQn_Type IRQn); * @retval ::NRF_SUCCESS The interrupt is available for the application. * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE IRQn is not available for the application. */ -__STATIC_INLINE uint32_t sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t * p_pending_irq); +__STATIC_INLINE uint32_t sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t *p_pending_irq); /**@brief Set Pending Interrupt. * @note Corresponds to NVIC_SetPendingIRQ in CMSIS. @@ -248,7 +248,7 @@ __STATIC_INLINE uint32_t sd_nvic_SetPriority(IRQn_Type IRQn, uint32_t priority); * @retval ::NRF_SUCCESS The interrupt priority is returned in p_priority. * @retval ::NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE - IRQn is not available for the application. */ -__STATIC_INLINE uint32_t sd_nvic_GetPriority(IRQn_Type IRQn, uint32_t * p_priority); +__STATIC_INLINE uint32_t sd_nvic_GetPriority(IRQn_Type IRQn, uint32_t *p_priority); /**@brief System Reset. * @note Corresponds to NVIC_SystemReset in CMSIS. @@ -268,7 +268,7 @@ __STATIC_INLINE uint32_t sd_nvic_SystemReset(void); * * @retval ::NRF_SUCCESS */ -__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t * p_is_nested_critical_region); +__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t *p_is_nested_critical_region); /**@brief Exit critical region. * @@ -285,199 +285,150 @@ __STATIC_INLINE uint32_t sd_nvic_critical_region_exit(uint8_t is_nested_critical #ifndef SUPPRESS_INLINE_IMPLEMENTATION -__STATIC_INLINE int __sd_nvic_irq_disable(void) -{ - int pm = __get_PRIMASK(); - __disable_irq(); - return pm; +__STATIC_INLINE int __sd_nvic_irq_disable(void) { + int pm = __get_PRIMASK(); + __disable_irq(); + return pm; } -__STATIC_INLINE void __sd_nvic_irq_enable(void) -{ - __enable_irq(); +__STATIC_INLINE void __sd_nvic_irq_enable(void) { + __enable_irq(); } -__STATIC_INLINE uint32_t __sd_nvic_app_accessible_irq(IRQn_Type IRQn) -{ - if (IRQn < 32) - { - return ((1UL<= (1 << __NVIC_PRIO_BITS)) - || (((1 << priority) & __NRF_NVIC_APP_IRQ_PRIOS) == 0) - ) - { - return 0; - } - return 1; -} - - -__STATIC_INLINE uint32_t sd_nvic_EnableIRQ(IRQn_Type IRQn) -{ - if (!__sd_nvic_app_accessible_irq(IRQn)) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } - if (!__sd_nvic_is_app_accessible_priority(NVIC_GetPriority(IRQn))) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED; - } - - if (nrf_nvic_state.__cr_flag) - { - nrf_nvic_state.__irq_masks[(uint32_t)((int32_t)IRQn) >> 5] |= (uint32_t)(1 << ((uint32_t)((int32_t)IRQn) & (uint32_t)0x1F)); - } - else - { - NVIC_EnableIRQ(IRQn); - } - return NRF_SUCCESS; -} - -__STATIC_INLINE uint32_t sd_nvic_DisableIRQ(IRQn_Type IRQn) -{ - if (!__sd_nvic_app_accessible_irq(IRQn)) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } - - if (nrf_nvic_state.__cr_flag) - { - nrf_nvic_state.__irq_masks[(uint32_t)((int32_t)IRQn) >> 5] &= ~(1UL << ((uint32_t)(IRQn) & 0x1F)); - } - else - { - NVIC_DisableIRQ(IRQn); - } - - return NRF_SUCCESS; -} - -__STATIC_INLINE uint32_t sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t * p_pending_irq) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - *p_pending_irq = NVIC_GetPendingIRQ(IRQn); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } -} - -__STATIC_INLINE uint32_t sd_nvic_SetPendingIRQ(IRQn_Type IRQn) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - NVIC_SetPendingIRQ(IRQn); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } -} - -__STATIC_INLINE uint32_t sd_nvic_ClearPendingIRQ(IRQn_Type IRQn) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - NVIC_ClearPendingIRQ(IRQn); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } -} - -__STATIC_INLINE uint32_t sd_nvic_SetPriority(IRQn_Type IRQn, uint32_t priority) -{ - if (!__sd_nvic_app_accessible_irq(IRQn)) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } - - if (!__sd_nvic_is_app_accessible_priority(priority)) - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED; - } - - NVIC_SetPriority(IRQn, (uint32_t)priority); - return NRF_SUCCESS; -} - -__STATIC_INLINE uint32_t sd_nvic_GetPriority(IRQn_Type IRQn, uint32_t * p_priority) -{ - if (__sd_nvic_app_accessible_irq(IRQn)) - { - *p_priority = (NVIC_GetPriority(IRQn) & 0xFF); - return NRF_SUCCESS; - } - else - { - return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; - } -} - -__STATIC_INLINE uint32_t sd_nvic_SystemReset(void) -{ - NVIC_SystemReset(); - return NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN; -} - -__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t * p_is_nested_critical_region) -{ - int was_masked = __sd_nvic_irq_disable(); - if (!nrf_nvic_state.__cr_flag) - { - nrf_nvic_state.__cr_flag = 1; - nrf_nvic_state.__irq_masks[0] = ( NVIC->ICER[0] & __NRF_NVIC_APP_IRQS_0 ); - NVIC->ICER[0] = __NRF_NVIC_APP_IRQS_0; - nrf_nvic_state.__irq_masks[1] = ( NVIC->ICER[1] & __NRF_NVIC_APP_IRQS_1 ); - NVIC->ICER[1] = __NRF_NVIC_APP_IRQS_1; - *p_is_nested_critical_region = 0; - } - else - { - *p_is_nested_critical_region = 1; - } - if (!was_masked) - { - __sd_nvic_irq_enable(); - } - return NRF_SUCCESS; -} - -__STATIC_INLINE uint32_t sd_nvic_critical_region_exit(uint8_t is_nested_critical_region) -{ - if (nrf_nvic_state.__cr_flag && (is_nested_critical_region == 0)) - { - int was_masked = __sd_nvic_irq_disable(); - NVIC->ISER[0] = nrf_nvic_state.__irq_masks[0]; - NVIC->ISER[1] = nrf_nvic_state.__irq_masks[1]; - nrf_nvic_state.__cr_flag = 0; - if (!was_masked) - { - __sd_nvic_irq_enable(); +__STATIC_INLINE uint32_t __sd_nvic_app_accessible_irq(IRQn_Type IRQn) { + if (IRQn < 32) { + return ((1UL << IRQn) & __NRF_NVIC_APP_IRQS_0) != 0; + } else if (IRQn < 64) { + return ((1UL << (IRQn - 32)) & __NRF_NVIC_APP_IRQS_1) != 0; + } else { + return 1; } - } +} - return NRF_SUCCESS; +__STATIC_INLINE uint32_t __sd_nvic_is_app_accessible_priority(uint32_t priority) { + if ((priority >= (1 << __NVIC_PRIO_BITS)) + || (((1 << priority) & __NRF_NVIC_APP_IRQ_PRIOS) == 0) + ) { + return 0; + } + return 1; +} + + +__STATIC_INLINE uint32_t sd_nvic_EnableIRQ(IRQn_Type IRQn) { + if (!__sd_nvic_app_accessible_irq(IRQn)) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } + if (!__sd_nvic_is_app_accessible_priority(NVIC_GetPriority(IRQn))) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED; + } + + if (nrf_nvic_state.__cr_flag) { + nrf_nvic_state.__irq_masks[(uint32_t)((int32_t)IRQn) >> 5] |= (uint32_t)(1 << ((uint32_t)((int32_t)IRQn) & (uint32_t)0x1F)); + } else { + NVIC_EnableIRQ(IRQn); + } + return NRF_SUCCESS; +} + +__STATIC_INLINE uint32_t sd_nvic_DisableIRQ(IRQn_Type IRQn) { + if (!__sd_nvic_app_accessible_irq(IRQn)) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } + + if (nrf_nvic_state.__cr_flag) { + nrf_nvic_state.__irq_masks[(uint32_t)((int32_t)IRQn) >> 5] &= ~(1UL << ((uint32_t)(IRQn) & 0x1F)); + } else { + NVIC_DisableIRQ(IRQn); + } + + return NRF_SUCCESS; +} + +__STATIC_INLINE uint32_t sd_nvic_GetPendingIRQ(IRQn_Type IRQn, uint32_t *p_pending_irq) { + if (__sd_nvic_app_accessible_irq(IRQn)) { + *p_pending_irq = NVIC_GetPendingIRQ(IRQn); + return NRF_SUCCESS; + } else { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } +} + +__STATIC_INLINE uint32_t sd_nvic_SetPendingIRQ(IRQn_Type IRQn) { + if (__sd_nvic_app_accessible_irq(IRQn)) { + NVIC_SetPendingIRQ(IRQn); + return NRF_SUCCESS; + } else { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } +} + +__STATIC_INLINE uint32_t sd_nvic_ClearPendingIRQ(IRQn_Type IRQn) { + if (__sd_nvic_app_accessible_irq(IRQn)) { + NVIC_ClearPendingIRQ(IRQn); + return NRF_SUCCESS; + } else { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } +} + +__STATIC_INLINE uint32_t sd_nvic_SetPriority(IRQn_Type IRQn, uint32_t priority) { + if (!__sd_nvic_app_accessible_irq(IRQn)) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } + + if (!__sd_nvic_is_app_accessible_priority(priority)) { + return NRF_ERROR_SOC_NVIC_INTERRUPT_PRIORITY_NOT_ALLOWED; + } + + NVIC_SetPriority(IRQn, (uint32_t)priority); + return NRF_SUCCESS; +} + +__STATIC_INLINE uint32_t sd_nvic_GetPriority(IRQn_Type IRQn, uint32_t *p_priority) { + if (__sd_nvic_app_accessible_irq(IRQn)) { + *p_priority = (NVIC_GetPriority(IRQn) & 0xFF); + return NRF_SUCCESS; + } else { + return NRF_ERROR_SOC_NVIC_INTERRUPT_NOT_AVAILABLE; + } +} + +__STATIC_INLINE uint32_t sd_nvic_SystemReset(void) { + NVIC_SystemReset(); + return NRF_ERROR_SOC_NVIC_SHOULD_NOT_RETURN; +} + +__STATIC_INLINE uint32_t sd_nvic_critical_region_enter(uint8_t *p_is_nested_critical_region) { + int was_masked = __sd_nvic_irq_disable(); + if (!nrf_nvic_state.__cr_flag) { + nrf_nvic_state.__cr_flag = 1; + nrf_nvic_state.__irq_masks[0] = (NVIC->ICER[0] & __NRF_NVIC_APP_IRQS_0); + NVIC->ICER[0] = __NRF_NVIC_APP_IRQS_0; + nrf_nvic_state.__irq_masks[1] = (NVIC->ICER[1] & __NRF_NVIC_APP_IRQS_1); + NVIC->ICER[1] = __NRF_NVIC_APP_IRQS_1; + *p_is_nested_critical_region = 0; + } else { + *p_is_nested_critical_region = 1; + } + if (!was_masked) { + __sd_nvic_irq_enable(); + } + return NRF_SUCCESS; +} + +__STATIC_INLINE uint32_t sd_nvic_critical_region_exit(uint8_t is_nested_critical_region) { + if (nrf_nvic_state.__cr_flag && (is_nested_critical_region == 0)) { + int was_masked = __sd_nvic_irq_disable(); + NVIC->ISER[0] = nrf_nvic_state.__irq_masks[0]; + NVIC->ISER[1] = nrf_nvic_state.__irq_masks[1]; + nrf_nvic_state.__cr_flag = 0; + if (!was_masked) { + __sd_nvic_irq_enable(); + } + } + + return NRF_SUCCESS; } #endif /* SUPPRESS_INLINE_IMPLEMENTATION */ diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_sdm.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_sdm.h index 6834599e87..24001fb12a 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_sdm.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_sdm.h @@ -130,12 +130,12 @@ the start of the SoftDevice (without MBR)*/ /** @brief Defines a macro for retrieving the actual SoftDevice Information Structure size value * from a given base address. Use @ref MBR_SIZE as the argument when the SoftDevice is * installed just above the MBR (the usual case). */ -#define SD_INFO_STRUCT_SIZE_GET(baseaddr) (*((uint8_t *) ((baseaddr) + SD_INFO_STRUCT_SIZE_OFFSET))) +#define SD_INFO_STRUCT_SIZE_GET(baseaddr) (*((uint8_t *)((baseaddr) + SD_INFO_STRUCT_SIZE_OFFSET))) /** @brief Defines a macro for retrieving the actual SoftDevice size value from a given base * address. Use @ref MBR_SIZE as the argument when the SoftDevice is installed just above * the MBR (the usual case). */ -#define SD_SIZE_GET(baseaddr) (*((uint32_t *) ((baseaddr) + SD_SIZE_OFFSET))) +#define SD_SIZE_GET(baseaddr) (*((uint32_t *)((baseaddr) + SD_SIZE_OFFSET))) /** @brief Defines the amount of flash that is used by the SoftDevice. * Add @ref MBR_SIZE to find the first available flash address when the SoftDevice is installed @@ -146,25 +146,25 @@ the start of the SoftDevice (without MBR)*/ /** @brief Defines a macro for retrieving the actual FWID value from a given base address. Use * @ref MBR_SIZE as the argument when the SoftDevice is installed just above the MBR (the usual * case). */ -#define SD_FWID_GET(baseaddr) (*((uint16_t *) ((baseaddr) + SD_FWID_OFFSET))) +#define SD_FWID_GET(baseaddr) (*((uint16_t *)((baseaddr) + SD_FWID_OFFSET))) /** @brief Defines a macro for retrieving the actual SoftDevice ID from a given base address. Use * @ref MBR_SIZE as the argument when the SoftDevice is installed just above the MBR (the * usual case). */ #define SD_ID_GET(baseaddr) ((SD_INFO_STRUCT_SIZE_GET(baseaddr) > (SD_ID_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) \ - ? (*((uint32_t *) ((baseaddr) + SD_ID_OFFSET))) : SDM_INFO_FIELD_INVALID) + ? (*((uint32_t *)((baseaddr) + SD_ID_OFFSET))) : SDM_INFO_FIELD_INVALID) /** @brief Defines a macro for retrieving the actual SoftDevice version from a given base address. * Use @ref MBR_SIZE as the argument when the SoftDevice is installed just above the MBR * (the usual case). */ #define SD_VERSION_GET(baseaddr) ((SD_INFO_STRUCT_SIZE_GET(baseaddr) > (SD_VERSION_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) \ - ? (*((uint32_t *) ((baseaddr) + SD_VERSION_OFFSET))) : SDM_INFO_FIELD_INVALID) + ? (*((uint32_t *)((baseaddr) + SD_VERSION_OFFSET))) : SDM_INFO_FIELD_INVALID) /** @brief Defines a macro for retrieving the address of SoftDevice unique str based on a given base address. * Use @ref MBR_SIZE as the argument when the SoftDevice is installed just above the MBR * (the usual case). */ #define SD_UNIQUE_STR_ADDR_GET(baseaddr) ((SD_INFO_STRUCT_SIZE_GET(baseaddr) > (SD_UNIQUE_STR_OFFSET - SOFTDEVICE_INFO_STRUCT_OFFSET)) \ - ? (((uint8_t *) ((baseaddr) + SD_UNIQUE_STR_OFFSET))) : SDM_INFO_FIELD_INVALID) + ? (((uint8_t *)((baseaddr) + SD_UNIQUE_STR_OFFSET))) : SDM_INFO_FIELD_INVALID) /**@defgroup NRF_FAULT_ID_RANGES Fault ID ranges * @{ */ @@ -174,7 +174,7 @@ the start of the SoftDevice (without MBR)*/ /**@defgroup NRF_FAULT_IDS Fault ID types * @{ */ -#define NRF_FAULT_ID_SD_ASSERT (NRF_FAULT_ID_SD_RANGE_START + 1) /**< SoftDevice assertion. The info parameter is reserved for future used. */ +#define NRF_FAULT_ID_SD_ASSERT (NRF_FAULT_ID_SD_RANGE_START + 1) /**< SoftDevice assertion. The info parameter is reserved for future used. */ #define NRF_FAULT_ID_APP_MEMACC (NRF_FAULT_ID_APP_RANGE_START + 1) /**< Application invalid memory access. The info parameter will contain 0x00000000, in case of SoftDevice RAM access violation. In case of SoftDevice peripheral register violation the info parameter will contain the sub-region number of @@ -190,11 +190,11 @@ the start of the SoftDevice (without MBR)*/ /**@brief nRF SoftDevice Manager API SVC numbers. */ enum NRF_SD_SVCS { - SD_SOFTDEVICE_ENABLE = SDM_SVC_BASE, /**< ::sd_softdevice_enable */ - SD_SOFTDEVICE_DISABLE, /**< ::sd_softdevice_disable */ - SD_SOFTDEVICE_IS_ENABLED, /**< ::sd_softdevice_is_enabled */ - SD_SOFTDEVICE_VECTOR_TABLE_BASE_SET, /**< ::sd_softdevice_vector_table_base_set */ - SVC_SDM_LAST /**< Placeholder for last SDM SVC */ + SD_SOFTDEVICE_ENABLE = SDM_SVC_BASE, /**< ::sd_softdevice_enable */ + SD_SOFTDEVICE_DISABLE, /**< ::sd_softdevice_disable */ + SD_SOFTDEVICE_IS_ENABLED, /**< ::sd_softdevice_is_enabled */ + SD_SOFTDEVICE_VECTOR_TABLE_BASE_SET, /**< ::sd_softdevice_vector_table_base_set */ + SVC_SDM_LAST /**< Placeholder for last SDM SVC */ }; /** @} */ @@ -237,15 +237,15 @@ enum NRF_SD_SVCS /**@brief Type representing LFCLK oscillator source. */ typedef struct { - uint8_t source; /**< LF oscillator clock source, see @ref NRF_CLOCK_LF_SRC. */ - uint8_t rc_ctiv; /**< Only for ::NRF_CLOCK_LF_SRC_RC: Calibration timer interval in 1/4 second + uint8_t source; /**< LF oscillator clock source, see @ref NRF_CLOCK_LF_SRC. */ + uint8_t rc_ctiv; /**< Only for ::NRF_CLOCK_LF_SRC_RC: Calibration timer interval in 1/4 second units (nRF52: 1-32). @note To avoid excessive clock drift, 0.5 degrees Celsius is the maximum temperature change allowed in one calibration timer interval. The interval should be selected to ensure this. @note Must be 0 if source is not ::NRF_CLOCK_LF_SRC_RC. */ - uint8_t rc_temp_ctiv; /**< Only for ::NRF_CLOCK_LF_SRC_RC: How often (in number of calibration + uint8_t rc_temp_ctiv; /**< Only for ::NRF_CLOCK_LF_SRC_RC: How often (in number of calibration intervals) the RC oscillator shall be calibrated if the temperature hasn't changed. 0: Always calibrate even if the temperature hasn't changed. @@ -263,7 +263,7 @@ typedef struct least once every 8 seconds and for temperature changes of 0.5 degrees Celsius every 4 seconds. See the Product Specification for the nRF52 device being used for more information.*/ - uint8_t accuracy; /**< External clock accuracy used in the LL to compute timing + uint8_t accuracy; /**< External clock accuracy used in the LL to compute timing windows, see @ref NRF_CLOCK_LF_ACCURACY.*/ } nrf_clock_lf_cfg_t; @@ -323,7 +323,7 @@ typedef void (*nrf_fault_handler_t)(uint32_t id, uint32_t pc, uint32_t info); * @retval ::NRF_ERROR_SDM_LFCLK_SOURCE_UNKNOWN Unknown low frequency clock source selected. * @retval ::NRF_ERROR_INVALID_PARAM Invalid clock source configuration supplied in p_clock_lf_cfg. */ -SVCALL(SD_SOFTDEVICE_ENABLE, uint32_t, sd_softdevice_enable(nrf_clock_lf_cfg_t const * p_clock_lf_cfg, nrf_fault_handler_t fault_handler)); +SVCALL(SD_SOFTDEVICE_ENABLE, uint32_t, sd_softdevice_enable(nrf_clock_lf_cfg_t const *p_clock_lf_cfg, nrf_fault_handler_t fault_handler)); /**@brief Disables the SoftDevice and by extension the protocol stack. diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_soc.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_soc.h index 3751d133f5..2baf305c7a 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_soc.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_soc.h @@ -100,7 +100,7 @@ extern "C" { /**@brief Mask of PPI channels reserved by the SoftDevice when the SoftDevice is enabled. */ #define NRF_SOC_SD_PPI_CHANNELS_SD_ENABLED_MSK ((uint32_t)( \ - (1U << 17) \ + (1U << 17) \ | (1U << 18) \ | (1U << 19) \ | (1U << 20) \ @@ -115,16 +115,16 @@ extern "C" { | (1U << 29) \ | (1U << 30) \ | (1U << 31) \ - )) + )) /**@brief Mask of PPI groups reserved by the SoftDevice when the SoftDevice is disabled. */ #define NRF_SOC_SD_PPI_GROUPS_SD_DISABLED_MSK ((uint32_t)(0)) /**@brief Mask of PPI groups reserved by the SoftDevice when the SoftDevice is enabled. */ #define NRF_SOC_SD_PPI_GROUPS_SD_ENABLED_MSK ((uint32_t)( \ - (1U << 4) \ + (1U << 4) \ | (1U << 5) \ - )) + )) /**@} */ @@ -134,148 +134,148 @@ extern "C" { /**@brief The SVC numbers used by the SVC functions in the SoC library. */ enum NRF_SOC_SVCS { - SD_PPI_CHANNEL_ENABLE_GET = SOC_SVC_BASE, - SD_PPI_CHANNEL_ENABLE_SET = SOC_SVC_BASE + 1, - SD_PPI_CHANNEL_ENABLE_CLR = SOC_SVC_BASE + 2, - SD_PPI_CHANNEL_ASSIGN = SOC_SVC_BASE + 3, - SD_PPI_GROUP_TASK_ENABLE = SOC_SVC_BASE + 4, - SD_PPI_GROUP_TASK_DISABLE = SOC_SVC_BASE + 5, - SD_PPI_GROUP_ASSIGN = SOC_SVC_BASE + 6, - SD_PPI_GROUP_GET = SOC_SVC_BASE + 7, - SD_FLASH_PAGE_ERASE = SOC_SVC_BASE + 8, - SD_FLASH_WRITE = SOC_SVC_BASE + 9, - SD_PROTECTED_REGISTER_WRITE = SOC_SVC_BASE + 11, - SD_MUTEX_NEW = SOC_SVC_BASE_NOT_AVAILABLE, - SD_MUTEX_ACQUIRE = SOC_SVC_BASE_NOT_AVAILABLE + 1, - SD_MUTEX_RELEASE = SOC_SVC_BASE_NOT_AVAILABLE + 2, - SD_RAND_APPLICATION_POOL_CAPACITY_GET = SOC_SVC_BASE_NOT_AVAILABLE + 3, - SD_RAND_APPLICATION_BYTES_AVAILABLE_GET = SOC_SVC_BASE_NOT_AVAILABLE + 4, - SD_RAND_APPLICATION_VECTOR_GET = SOC_SVC_BASE_NOT_AVAILABLE + 5, - SD_POWER_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 6, - SD_POWER_SYSTEM_OFF = SOC_SVC_BASE_NOT_AVAILABLE + 7, - SD_POWER_RESET_REASON_GET = SOC_SVC_BASE_NOT_AVAILABLE + 8, - SD_POWER_RESET_REASON_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 9, - SD_POWER_POF_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 10, - SD_POWER_POF_THRESHOLD_SET = SOC_SVC_BASE_NOT_AVAILABLE + 11, - SD_POWER_POF_THRESHOLDVDDH_SET = SOC_SVC_BASE_NOT_AVAILABLE + 12, - SD_POWER_RAM_POWER_SET = SOC_SVC_BASE_NOT_AVAILABLE + 13, - SD_POWER_RAM_POWER_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 14, - SD_POWER_RAM_POWER_GET = SOC_SVC_BASE_NOT_AVAILABLE + 15, - SD_POWER_GPREGRET_SET = SOC_SVC_BASE_NOT_AVAILABLE + 16, - SD_POWER_GPREGRET_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 17, - SD_POWER_GPREGRET_GET = SOC_SVC_BASE_NOT_AVAILABLE + 18, - SD_POWER_DCDC_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 19, - SD_POWER_DCDC0_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 20, - SD_APP_EVT_WAIT = SOC_SVC_BASE_NOT_AVAILABLE + 21, - SD_CLOCK_HFCLK_REQUEST = SOC_SVC_BASE_NOT_AVAILABLE + 22, - SD_CLOCK_HFCLK_RELEASE = SOC_SVC_BASE_NOT_AVAILABLE + 23, - SD_CLOCK_HFCLK_IS_RUNNING = SOC_SVC_BASE_NOT_AVAILABLE + 24, - SD_RADIO_NOTIFICATION_CFG_SET = SOC_SVC_BASE_NOT_AVAILABLE + 25, - SD_ECB_BLOCK_ENCRYPT = SOC_SVC_BASE_NOT_AVAILABLE + 26, - SD_ECB_BLOCKS_ENCRYPT = SOC_SVC_BASE_NOT_AVAILABLE + 27, - SD_RADIO_SESSION_OPEN = SOC_SVC_BASE_NOT_AVAILABLE + 28, - SD_RADIO_SESSION_CLOSE = SOC_SVC_BASE_NOT_AVAILABLE + 29, - SD_RADIO_REQUEST = SOC_SVC_BASE_NOT_AVAILABLE + 30, - SD_EVT_GET = SOC_SVC_BASE_NOT_AVAILABLE + 31, - SD_TEMP_GET = SOC_SVC_BASE_NOT_AVAILABLE + 32, - SD_POWER_USBPWRRDY_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 33, - SD_POWER_USBDETECTED_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 34, - SD_POWER_USBREMOVED_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 35, - SD_POWER_USBREGSTATUS_GET = SOC_SVC_BASE_NOT_AVAILABLE + 36, - SVC_SOC_LAST = SOC_SVC_BASE_NOT_AVAILABLE + 37 + SD_PPI_CHANNEL_ENABLE_GET = SOC_SVC_BASE, + SD_PPI_CHANNEL_ENABLE_SET = SOC_SVC_BASE + 1, + SD_PPI_CHANNEL_ENABLE_CLR = SOC_SVC_BASE + 2, + SD_PPI_CHANNEL_ASSIGN = SOC_SVC_BASE + 3, + SD_PPI_GROUP_TASK_ENABLE = SOC_SVC_BASE + 4, + SD_PPI_GROUP_TASK_DISABLE = SOC_SVC_BASE + 5, + SD_PPI_GROUP_ASSIGN = SOC_SVC_BASE + 6, + SD_PPI_GROUP_GET = SOC_SVC_BASE + 7, + SD_FLASH_PAGE_ERASE = SOC_SVC_BASE + 8, + SD_FLASH_WRITE = SOC_SVC_BASE + 9, + SD_PROTECTED_REGISTER_WRITE = SOC_SVC_BASE + 11, + SD_MUTEX_NEW = SOC_SVC_BASE_NOT_AVAILABLE, + SD_MUTEX_ACQUIRE = SOC_SVC_BASE_NOT_AVAILABLE + 1, + SD_MUTEX_RELEASE = SOC_SVC_BASE_NOT_AVAILABLE + 2, + SD_RAND_APPLICATION_POOL_CAPACITY_GET = SOC_SVC_BASE_NOT_AVAILABLE + 3, + SD_RAND_APPLICATION_BYTES_AVAILABLE_GET = SOC_SVC_BASE_NOT_AVAILABLE + 4, + SD_RAND_APPLICATION_VECTOR_GET = SOC_SVC_BASE_NOT_AVAILABLE + 5, + SD_POWER_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 6, + SD_POWER_SYSTEM_OFF = SOC_SVC_BASE_NOT_AVAILABLE + 7, + SD_POWER_RESET_REASON_GET = SOC_SVC_BASE_NOT_AVAILABLE + 8, + SD_POWER_RESET_REASON_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 9, + SD_POWER_POF_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 10, + SD_POWER_POF_THRESHOLD_SET = SOC_SVC_BASE_NOT_AVAILABLE + 11, + SD_POWER_POF_THRESHOLDVDDH_SET = SOC_SVC_BASE_NOT_AVAILABLE + 12, + SD_POWER_RAM_POWER_SET = SOC_SVC_BASE_NOT_AVAILABLE + 13, + SD_POWER_RAM_POWER_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 14, + SD_POWER_RAM_POWER_GET = SOC_SVC_BASE_NOT_AVAILABLE + 15, + SD_POWER_GPREGRET_SET = SOC_SVC_BASE_NOT_AVAILABLE + 16, + SD_POWER_GPREGRET_CLR = SOC_SVC_BASE_NOT_AVAILABLE + 17, + SD_POWER_GPREGRET_GET = SOC_SVC_BASE_NOT_AVAILABLE + 18, + SD_POWER_DCDC_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 19, + SD_POWER_DCDC0_MODE_SET = SOC_SVC_BASE_NOT_AVAILABLE + 20, + SD_APP_EVT_WAIT = SOC_SVC_BASE_NOT_AVAILABLE + 21, + SD_CLOCK_HFCLK_REQUEST = SOC_SVC_BASE_NOT_AVAILABLE + 22, + SD_CLOCK_HFCLK_RELEASE = SOC_SVC_BASE_NOT_AVAILABLE + 23, + SD_CLOCK_HFCLK_IS_RUNNING = SOC_SVC_BASE_NOT_AVAILABLE + 24, + SD_RADIO_NOTIFICATION_CFG_SET = SOC_SVC_BASE_NOT_AVAILABLE + 25, + SD_ECB_BLOCK_ENCRYPT = SOC_SVC_BASE_NOT_AVAILABLE + 26, + SD_ECB_BLOCKS_ENCRYPT = SOC_SVC_BASE_NOT_AVAILABLE + 27, + SD_RADIO_SESSION_OPEN = SOC_SVC_BASE_NOT_AVAILABLE + 28, + SD_RADIO_SESSION_CLOSE = SOC_SVC_BASE_NOT_AVAILABLE + 29, + SD_RADIO_REQUEST = SOC_SVC_BASE_NOT_AVAILABLE + 30, + SD_EVT_GET = SOC_SVC_BASE_NOT_AVAILABLE + 31, + SD_TEMP_GET = SOC_SVC_BASE_NOT_AVAILABLE + 32, + SD_POWER_USBPWRRDY_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 33, + SD_POWER_USBDETECTED_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 34, + SD_POWER_USBREMOVED_ENABLE = SOC_SVC_BASE_NOT_AVAILABLE + 35, + SD_POWER_USBREGSTATUS_GET = SOC_SVC_BASE_NOT_AVAILABLE + 36, + SVC_SOC_LAST = SOC_SVC_BASE_NOT_AVAILABLE + 37 }; /**@brief Possible values of a ::nrf_mutex_t. */ enum NRF_MUTEX_VALUES { - NRF_MUTEX_FREE, - NRF_MUTEX_TAKEN + NRF_MUTEX_FREE, + NRF_MUTEX_TAKEN }; /**@brief Power modes. */ enum NRF_POWER_MODES { - NRF_POWER_MODE_CONSTLAT, /**< Constant latency mode. See power management in the reference manual. */ - NRF_POWER_MODE_LOWPWR /**< Low power mode. See power management in the reference manual. */ + NRF_POWER_MODE_CONSTLAT, /**< Constant latency mode. See power management in the reference manual. */ + NRF_POWER_MODE_LOWPWR /**< Low power mode. See power management in the reference manual. */ }; /**@brief Power failure thresholds */ enum NRF_POWER_THRESHOLDS { - NRF_POWER_THRESHOLD_V17 = 4UL, /**< 1.7 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V18, /**< 1.8 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V19, /**< 1.9 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V20, /**< 2.0 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V21, /**< 2.1 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V22, /**< 2.2 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V23, /**< 2.3 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V24, /**< 2.4 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V25, /**< 2.5 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V26, /**< 2.6 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V27, /**< 2.7 Volts power failure threshold. */ - NRF_POWER_THRESHOLD_V28 /**< 2.8 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V17 = 4UL, /**< 1.7 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V18, /**< 1.8 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V19, /**< 1.9 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V20, /**< 2.0 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V21, /**< 2.1 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V22, /**< 2.2 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V23, /**< 2.3 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V24, /**< 2.4 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V25, /**< 2.5 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V26, /**< 2.6 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V27, /**< 2.7 Volts power failure threshold. */ + NRF_POWER_THRESHOLD_V28 /**< 2.8 Volts power failure threshold. */ }; /**@brief Power failure thresholds for high voltage */ enum NRF_POWER_THRESHOLDVDDHS { - NRF_POWER_THRESHOLDVDDH_V27, /**< 2.7 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V28, /**< 2.8 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V29, /**< 2.9 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V30, /**< 3.0 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V31, /**< 3.1 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V32, /**< 3.2 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V33, /**< 3.3 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V34, /**< 3.4 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V35, /**< 3.5 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V36, /**< 3.6 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V37, /**< 3.7 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V38, /**< 3.8 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V39, /**< 3.9 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V40, /**< 4.0 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V41, /**< 4.1 Volts power failure threshold. */ - NRF_POWER_THRESHOLDVDDH_V42 /**< 4.2 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V27, /**< 2.7 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V28, /**< 2.8 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V29, /**< 2.9 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V30, /**< 3.0 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V31, /**< 3.1 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V32, /**< 3.2 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V33, /**< 3.3 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V34, /**< 3.4 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V35, /**< 3.5 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V36, /**< 3.6 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V37, /**< 3.7 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V38, /**< 3.8 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V39, /**< 3.9 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V40, /**< 4.0 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V41, /**< 4.1 Volts power failure threshold. */ + NRF_POWER_THRESHOLDVDDH_V42 /**< 4.2 Volts power failure threshold. */ }; /**@brief DC/DC converter modes. */ enum NRF_POWER_DCDC_MODES { - NRF_POWER_DCDC_DISABLE, /**< The DCDC is disabled. */ - NRF_POWER_DCDC_ENABLE /**< The DCDC is enabled. */ + NRF_POWER_DCDC_DISABLE, /**< The DCDC is disabled. */ + NRF_POWER_DCDC_ENABLE /**< The DCDC is enabled. */ }; /**@brief Radio notification distances. */ enum NRF_RADIO_NOTIFICATION_DISTANCES { - NRF_RADIO_NOTIFICATION_DISTANCE_NONE = 0, /**< The event does not have a notification. */ - NRF_RADIO_NOTIFICATION_DISTANCE_800US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_1740US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_2680US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_3620US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_4560US, /**< The distance from the active notification to start of radio activity. */ - NRF_RADIO_NOTIFICATION_DISTANCE_5500US /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_NONE = 0, /**< The event does not have a notification. */ + NRF_RADIO_NOTIFICATION_DISTANCE_800US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_1740US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_2680US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_3620US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_4560US, /**< The distance from the active notification to start of radio activity. */ + NRF_RADIO_NOTIFICATION_DISTANCE_5500US /**< The distance from the active notification to start of radio activity. */ }; /**@brief Radio notification types. */ enum NRF_RADIO_NOTIFICATION_TYPES { - NRF_RADIO_NOTIFICATION_TYPE_NONE = 0, /**< The event does not have a radio notification signal. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_ACTIVE, /**< Using interrupt for notification when the radio will be enabled. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_INACTIVE, /**< Using interrupt for notification when the radio has been disabled. */ - NRF_RADIO_NOTIFICATION_TYPE_INT_ON_BOTH, /**< Using interrupt for notification both when the radio will be enabled and disabled. */ + NRF_RADIO_NOTIFICATION_TYPE_NONE = 0, /**< The event does not have a radio notification signal. */ + NRF_RADIO_NOTIFICATION_TYPE_INT_ON_ACTIVE, /**< Using interrupt for notification when the radio will be enabled. */ + NRF_RADIO_NOTIFICATION_TYPE_INT_ON_INACTIVE, /**< Using interrupt for notification when the radio has been disabled. */ + NRF_RADIO_NOTIFICATION_TYPE_INT_ON_BOTH, /**< Using interrupt for notification both when the radio will be enabled and disabled. */ }; /**@brief The Radio signal callback types. */ enum NRF_RADIO_CALLBACK_SIGNAL_TYPE { - NRF_RADIO_CALLBACK_SIGNAL_TYPE_START, /**< This signal indicates the start of the radio timeslot. */ - NRF_RADIO_CALLBACK_SIGNAL_TYPE_TIMER0, /**< This signal indicates the NRF_TIMER0 interrupt. */ - NRF_RADIO_CALLBACK_SIGNAL_TYPE_RADIO, /**< This signal indicates the NRF_RADIO interrupt. */ - NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_FAILED, /**< This signal indicates extend action failed. */ - NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_SUCCEEDED /**< This signal indicates extend action succeeded. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_START, /**< This signal indicates the start of the radio timeslot. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_TIMER0, /**< This signal indicates the NRF_TIMER0 interrupt. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_RADIO, /**< This signal indicates the NRF_RADIO interrupt. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_FAILED, /**< This signal indicates extend action failed. */ + NRF_RADIO_CALLBACK_SIGNAL_TYPE_EXTEND_SUCCEEDED /**< This signal indicates extend action succeeded. */ }; /**@brief The actions requested by the signal callback. @@ -285,28 +285,28 @@ enum NRF_RADIO_CALLBACK_SIGNAL_TYPE */ enum NRF_RADIO_SIGNAL_CALLBACK_ACTION { - NRF_RADIO_SIGNAL_CALLBACK_ACTION_NONE, /**< Return without action. */ - NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND, /**< Request an extension of the current + NRF_RADIO_SIGNAL_CALLBACK_ACTION_NONE, /**< Return without action. */ + NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND, /**< Request an extension of the current timeslot. Maximum execution time for this action: @ref NRF_RADIO_MAX_EXTENSION_PROCESSING_TIME_US. This action must be started at least @ref NRF_RADIO_MIN_EXTENSION_MARGIN_US before the end of the timeslot. */ - NRF_RADIO_SIGNAL_CALLBACK_ACTION_END, /**< End the current radio timeslot. */ - NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END /**< Request a new radio timeslot and end the current timeslot. */ + NRF_RADIO_SIGNAL_CALLBACK_ACTION_END, /**< End the current radio timeslot. */ + NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END /**< Request a new radio timeslot and end the current timeslot. */ }; /**@brief Radio timeslot high frequency clock source configuration. */ enum NRF_RADIO_HFCLK_CFG { - NRF_RADIO_HFCLK_CFG_XTAL_GUARANTEED, /**< The SoftDevice will guarantee that the high frequency clock source is the + NRF_RADIO_HFCLK_CFG_XTAL_GUARANTEED, /**< The SoftDevice will guarantee that the high frequency clock source is the external crystal for the whole duration of the timeslot. This should be the preferred option for events that use the radio or require high timing accuracy. @note The SoftDevice will automatically turn on and off the external crystal, at the beginning and end of the timeslot, respectively. The crystal may also intentionally be left running after the timeslot, in cases where it is needed by the SoftDevice shortly after the end of the timeslot. */ - NRF_RADIO_HFCLK_CFG_NO_GUARANTEE /**< This configuration allows for earlier and tighter scheduling of timeslots. + NRF_RADIO_HFCLK_CFG_NO_GUARANTEE /**< This configuration allows for earlier and tighter scheduling of timeslots. The RC oscillator may be the clock source in part or for the whole duration of the timeslot. The RC oscillator's accuracy must therefore be taken into consideration. @note If the application will use the radio peripheral in timeslots with this configuration, @@ -316,33 +316,33 @@ enum NRF_RADIO_HFCLK_CFG /**@brief Radio timeslot priorities. */ enum NRF_RADIO_PRIORITY { - NRF_RADIO_PRIORITY_HIGH, /**< High (equal priority as the normal connection priority of the SoftDevice stack(s)). */ - NRF_RADIO_PRIORITY_NORMAL, /**< Normal (equal priority as the priority of secondary activities of the SoftDevice stack(s)). */ + NRF_RADIO_PRIORITY_HIGH, /**< High (equal priority as the normal connection priority of the SoftDevice stack(s)). */ + NRF_RADIO_PRIORITY_NORMAL, /**< Normal (equal priority as the priority of secondary activities of the SoftDevice stack(s)). */ }; /**@brief Radio timeslot request type. */ enum NRF_RADIO_REQUEST_TYPE { - NRF_RADIO_REQ_TYPE_EARLIEST, /**< Request radio timeslot as early as possible. This should always be used for the first request in a session. */ - NRF_RADIO_REQ_TYPE_NORMAL /**< Normal radio timeslot request. */ + NRF_RADIO_REQ_TYPE_EARLIEST, /**< Request radio timeslot as early as possible. This should always be used for the first request in a session. */ + NRF_RADIO_REQ_TYPE_NORMAL /**< Normal radio timeslot request. */ }; /**@brief SoC Events. */ enum NRF_SOC_EVTS { - NRF_EVT_HFCLKSTARTED, /**< Event indicating that the HFCLK has started. */ - NRF_EVT_POWER_FAILURE_WARNING, /**< Event indicating that a power failure warning has occurred. */ - NRF_EVT_FLASH_OPERATION_SUCCESS, /**< Event indicating that the ongoing flash operation has completed successfully. */ - NRF_EVT_FLASH_OPERATION_ERROR, /**< Event indicating that the ongoing flash operation has timed out with an error. */ - NRF_EVT_RADIO_BLOCKED, /**< Event indicating that a radio timeslot was blocked. */ - NRF_EVT_RADIO_CANCELED, /**< Event indicating that a radio timeslot was canceled by SoftDevice. */ - NRF_EVT_RADIO_SIGNAL_CALLBACK_INVALID_RETURN, /**< Event indicating that a radio timeslot signal callback handler return was invalid. */ - NRF_EVT_RADIO_SESSION_IDLE, /**< Event indicating that a radio timeslot session is idle. */ - NRF_EVT_RADIO_SESSION_CLOSED, /**< Event indicating that a radio timeslot session is closed. */ - NRF_EVT_POWER_USB_POWER_READY, /**< Event indicating that a USB 3.3 V supply is ready. */ - NRF_EVT_POWER_USB_DETECTED, /**< Event indicating that voltage supply is detected on VBUS. */ - NRF_EVT_POWER_USB_REMOVED, /**< Event indicating that voltage supply is removed from VBUS. */ - NRF_EVT_NUMBER_OF_EVTS + NRF_EVT_HFCLKSTARTED, /**< Event indicating that the HFCLK has started. */ + NRF_EVT_POWER_FAILURE_WARNING, /**< Event indicating that a power failure warning has occurred. */ + NRF_EVT_FLASH_OPERATION_SUCCESS, /**< Event indicating that the ongoing flash operation has completed successfully. */ + NRF_EVT_FLASH_OPERATION_ERROR, /**< Event indicating that the ongoing flash operation has timed out with an error. */ + NRF_EVT_RADIO_BLOCKED, /**< Event indicating that a radio timeslot was blocked. */ + NRF_EVT_RADIO_CANCELED, /**< Event indicating that a radio timeslot was canceled by SoftDevice. */ + NRF_EVT_RADIO_SIGNAL_CALLBACK_INVALID_RETURN, /**< Event indicating that a radio timeslot signal callback handler return was invalid. */ + NRF_EVT_RADIO_SESSION_IDLE, /**< Event indicating that a radio timeslot session is idle. */ + NRF_EVT_RADIO_SESSION_CLOSED, /**< Event indicating that a radio timeslot session is closed. */ + NRF_EVT_POWER_USB_POWER_READY, /**< Event indicating that a USB 3.3 V supply is ready. */ + NRF_EVT_POWER_USB_DETECTED, /**< Event indicating that voltage supply is detected on VBUS. */ + NRF_EVT_POWER_USB_REMOVED, /**< Event indicating that voltage supply is removed from VBUS. */ + NRF_EVT_NUMBER_OF_EVTS }; /**@} */ @@ -359,47 +359,47 @@ typedef volatile uint8_t nrf_mutex_t; /**@brief Parameters for a request for a timeslot as early as possible. */ typedef struct { - uint8_t hfclk; /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */ - uint8_t priority; /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */ - uint32_t length_us; /**< The radio timeslot length (in the range 100 to 100,000] microseconds). */ - uint32_t timeout_us; /**< Longest acceptable delay until the start of the requested timeslot (up to @ref NRF_RADIO_EARLIEST_TIMEOUT_MAX_US microseconds). */ + uint8_t hfclk; /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */ + uint8_t priority; /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */ + uint32_t length_us; /**< The radio timeslot length (in the range 100 to 100,000] microseconds). */ + uint32_t timeout_us; /**< Longest acceptable delay until the start of the requested timeslot (up to @ref NRF_RADIO_EARLIEST_TIMEOUT_MAX_US microseconds). */ } nrf_radio_request_earliest_t; /**@brief Parameters for a normal radio timeslot request. */ typedef struct { - uint8_t hfclk; /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */ - uint8_t priority; /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */ - uint32_t distance_us; /**< Distance from the start of the previous radio timeslot (up to @ref NRF_RADIO_DISTANCE_MAX_US microseconds). */ - uint32_t length_us; /**< The radio timeslot length (in the range [100..100,000] microseconds). */ + uint8_t hfclk; /**< High frequency clock source, see @ref NRF_RADIO_HFCLK_CFG. */ + uint8_t priority; /**< The radio timeslot priority, see @ref NRF_RADIO_PRIORITY. */ + uint32_t distance_us; /**< Distance from the start of the previous radio timeslot (up to @ref NRF_RADIO_DISTANCE_MAX_US microseconds). */ + uint32_t length_us; /**< The radio timeslot length (in the range [100..100,000] microseconds). */ } nrf_radio_request_normal_t; /**@brief Radio timeslot request parameters. */ typedef struct { - uint8_t request_type; /**< Type of request, see @ref NRF_RADIO_REQUEST_TYPE. */ - union - { - nrf_radio_request_earliest_t earliest; /**< Parameters for requesting a radio timeslot as early as possible. */ - nrf_radio_request_normal_t normal; /**< Parameters for requesting a normal radio timeslot. */ - } params; /**< Parameter union. */ + uint8_t request_type; /**< Type of request, see @ref NRF_RADIO_REQUEST_TYPE. */ + union + { + nrf_radio_request_earliest_t earliest; /**< Parameters for requesting a radio timeslot as early as possible. */ + nrf_radio_request_normal_t normal; /**< Parameters for requesting a normal radio timeslot. */ + } params; /**< Parameter union. */ } nrf_radio_request_t; /**@brief Return parameters of the radio timeslot signal callback. */ typedef struct { - uint8_t callback_action; /**< The action requested by the application when returning from the signal callback, see @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION. */ - union - { - struct + uint8_t callback_action; /**< The action requested by the application when returning from the signal callback, see @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION. */ + union { - nrf_radio_request_t * p_next; /**< The request parameters for the next radio timeslot. */ - } request; /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END. */ - struct - { - uint32_t length_us; /**< Requested extension of the radio timeslot duration (microseconds) (for minimum time see @ref NRF_RADIO_MINIMUM_TIMESLOT_LENGTH_EXTENSION_TIME_US). */ - } extend; /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND. */ - } params; /**< Parameter union. */ + struct + { + nrf_radio_request_t *p_next; /**< The request parameters for the next radio timeslot. */ + } request; /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_REQUEST_AND_END. */ + struct + { + uint32_t length_us; /**< Requested extension of the radio timeslot duration (microseconds) (for minimum time see @ref NRF_RADIO_MINIMUM_TIMESLOT_LENGTH_EXTENSION_TIME_US). */ + } extend; /**< Additional parameters for return_code @ref NRF_RADIO_SIGNAL_CALLBACK_ACTION_EXTEND. */ + } params; /**< Parameter union. */ } nrf_radio_signal_callback_return_param_t; /**@brief The radio timeslot signal callback type. @@ -414,7 +414,7 @@ typedef struct * * @return Pointer to structure containing action requested by the application. */ -typedef nrf_radio_signal_callback_return_param_t * (*nrf_radio_signal_callback_t) (uint8_t signal_type); +typedef nrf_radio_signal_callback_return_param_t * (*nrf_radio_signal_callback_t)(uint8_t signal_type); /**@brief AES ECB parameter typedefs */ typedef uint8_t soc_ecb_key_t[SOC_ECB_KEY_LENGTH]; /**< Encryption key type. */ @@ -424,18 +424,18 @@ typedef uint8_t soc_ecb_ciphertext_t[SOC_ECB_CIPHERTEXT_LENGTH]; /**< Ciphertex /**@brief AES ECB data structure */ typedef struct { - soc_ecb_key_t key; /**< Encryption key. */ - soc_ecb_cleartext_t cleartext; /**< Cleartext data. */ - soc_ecb_ciphertext_t ciphertext; /**< Ciphertext data. */ + soc_ecb_key_t key; /**< Encryption key. */ + soc_ecb_cleartext_t cleartext; /**< Cleartext data. */ + soc_ecb_ciphertext_t ciphertext; /**< Ciphertext data. */ } nrf_ecb_hal_data_t; /**@brief AES ECB block. Used to provide multiple blocks in a single call to @ref sd_ecb_blocks_encrypt.*/ typedef struct { - soc_ecb_key_t const * p_key; /**< Pointer to the Encryption key. */ - soc_ecb_cleartext_t const * p_cleartext; /**< Pointer to the Cleartext data. */ - soc_ecb_ciphertext_t * p_ciphertext; /**< Pointer to the Ciphertext data. */ + soc_ecb_key_t const *p_key; /**< Pointer to the Encryption key. */ + soc_ecb_cleartext_t const *p_cleartext; /**< Pointer to the Cleartext data. */ + soc_ecb_ciphertext_t *p_ciphertext; /**< Pointer to the Ciphertext data. */ } nrf_ecb_hal_data_block_t; /**@} */ @@ -663,7 +663,7 @@ SVCALL(SD_POWER_GPREGRET_CLR, uint32_t, sd_power_gpregret_clr(uint32_t gpregret_ * * @retval ::NRF_SUCCESS */ -SVCALL(SD_POWER_GPREGRET_GET, uint32_t, sd_power_gpregret_get(uint32_t gpregret_id, uint32_t *p_gpregret)); +SVCALL(SD_POWER_GPREGRET_GET, uint32_t, sd_power_gpregret_get(uint32_t gpregret_id, uint32_t * p_gpregret)); /**@brief Enable or disable the DC/DC regulator for the regulator stage 1 (REG1). * @@ -780,7 +780,7 @@ SVCALL(SD_PPI_CHANNEL_ENABLE_CLR, uint32_t, sd_ppi_channel_enable_clr(uint32_t c * @retval ::NRF_ERROR_SOC_PPI_INVALID_CHANNEL The channel number is invalid. * @retval ::NRF_SUCCESS */ -SVCALL(SD_PPI_CHANNEL_ASSIGN, uint32_t, sd_ppi_channel_assign(uint8_t channel_num, const volatile void * evt_endpoint, const volatile void * task_endpoint)); +SVCALL(SD_PPI_CHANNEL_ASSIGN, uint32_t, sd_ppi_channel_assign(uint8_t channel_num, const volatile void *evt_endpoint, const volatile void *task_endpoint)); /**@brief Task to enable a channel group. * @@ -941,7 +941,7 @@ SVCALL(SD_TEMP_GET, uint32_t, sd_temp_get(int32_t * p_temp)); * @retval ::NRF_ERROR_FORBIDDEN Tried to write to an address outside the application flash area. * @retval ::NRF_SUCCESS The command was accepted. */ -SVCALL(SD_FLASH_WRITE, uint32_t, sd_flash_write(uint32_t * p_dst, uint32_t const * p_src, uint32_t size)); +SVCALL(SD_FLASH_WRITE, uint32_t, sd_flash_write(uint32_t * p_dst, uint32_t const *p_src, uint32_t size)); /**@brief Flash Erase page @@ -997,7 +997,7 @@ SVCALL(SD_FLASH_PAGE_ERASE, uint32_t, sd_flash_page_erase(uint32_t page_number)) * @retval ::NRF_ERROR_INTERNAL If a new session could not be opened due to an internal error. * @retval ::NRF_SUCCESS Otherwise. */ - SVCALL(SD_RADIO_SESSION_OPEN, uint32_t, sd_radio_session_open(nrf_radio_signal_callback_t p_radio_signal_callback)); +SVCALL(SD_RADIO_SESSION_OPEN, uint32_t, sd_radio_session_open(nrf_radio_signal_callback_t p_radio_signal_callback)); /**@brief Closes a session for radio timeslot requests. * @@ -1010,7 +1010,7 @@ SVCALL(SD_FLASH_PAGE_ERASE, uint32_t, sd_flash_page_erase(uint32_t page_number)) * @retval ::NRF_ERROR_BUSY If session is currently being closed. * @retval ::NRF_SUCCESS Otherwise. */ - SVCALL(SD_RADIO_SESSION_CLOSE, uint32_t, sd_radio_session_close(void)); +SVCALL(SD_RADIO_SESSION_CLOSE, uint32_t, sd_radio_session_close(void)); /**@brief Requests a radio timeslot. * @@ -1047,7 +1047,7 @@ SVCALL(SD_FLASH_PAGE_ERASE, uint32_t, sd_flash_page_erase(uint32_t page_number)) * @retval ::NRF_ERROR_INVALID_PARAM If the parameters of p_request are not valid. * @retval ::NRF_SUCCESS Otherwise. */ - SVCALL(SD_RADIO_REQUEST, uint32_t, sd_radio_request(nrf_radio_request_t const * p_request)); +SVCALL(SD_RADIO_REQUEST, uint32_t, sd_radio_request(nrf_radio_request_t const *p_request)); /**@brief Write register protected by the SoftDevice * diff --git a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_svc.h b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_svc.h index 231a54f941..293001eccf 100644 --- a/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_svc.h +++ b/ports/nrf/bluetooth/s140_nrf52_7.0.1/s140_nrf52_7.0.1_API/include/nrf_svc.h @@ -60,33 +60,33 @@ extern "C" { #else #ifndef SVCALL -#if defined (__CC_ARM) +#if defined(__CC_ARM) #define SVCALL(number, return_type, signature) return_type __svc(number) signature -#elif defined (__GNUC__) +#elif defined(__GNUC__) #ifdef __cplusplus #define GCC_CAST_CPP (uint16_t) #else #define GCC_CAST_CPP #endif #define SVCALL(number, return_type, signature) \ - _Pragma("GCC diagnostic push") \ - _Pragma("GCC diagnostic ignored \"-Wreturn-type\"") \ - __attribute__((naked)) \ - __attribute__((unused)) \ - static return_type signature \ - { \ - __asm( \ - "svc %0\n" \ - "bx r14" : : "I" (GCC_CAST_CPP number) : "r0" \ - ); \ - } \ - _Pragma("GCC diagnostic pop") + _Pragma("GCC diagnostic push") \ + _Pragma("GCC diagnostic ignored \"-Wreturn-type\"") \ + __attribute__((naked)) \ + __attribute__((unused)) \ + static return_type signature \ + { \ + __asm( \ + "svc %0\n" \ + "bx r14" : : "I" (GCC_CAST_CPP number) : "r0" \ + ); \ + } \ + _Pragma("GCC diagnostic pop") -#elif defined (__ICCARM__) +#elif defined(__ICCARM__) #define PRAGMA(x) _Pragma(#x) #define SVCALL(number, return_type, signature) \ -PRAGMA(swi_number = (number)) \ - __swi return_type signature; + PRAGMA(swi_number = (number)) \ + __swi return_type signature; #else #define SVCALL(number, return_type, signature) return_type signature #endif diff --git a/ports/nrf/boards/ADM_B_NRF52840_1/board.c b/ports/nrf/boards/ADM_B_NRF52840_1/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/ADM_B_NRF52840_1/board.c +++ b/ports/nrf/boards/ADM_B_NRF52840_1/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/TG-Watch/board.c b/ports/nrf/boards/TG-Watch/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/TG-Watch/board.c +++ b/ports/nrf/boards/TG-Watch/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/arduino_nano_33_ble/board.c b/ports/nrf/boards/arduino_nano_33_ble/board.c index d1689e9ddc..8359b39465 100644 --- a/ports/nrf/boards/arduino_nano_33_ble/board.c +++ b/ports/nrf/boards/arduino_nano_33_ble/board.c @@ -55,7 +55,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/bastble/board.c b/ports/nrf/boards/bastble/board.c index b6fb04f06c..ee999b650b 100644 --- a/ports/nrf/boards/bastble/board.c +++ b/ports/nrf/boards/bastble/board.c @@ -33,7 +33,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/bless_dev_board_multi_sensor/board.c b/ports/nrf/boards/bless_dev_board_multi_sensor/board.c index 6970294ecc..d1f26b0b56 100644 --- a/ports/nrf/boards/bless_dev_board_multi_sensor/board.c +++ b/ports/nrf/boards/bless_dev_board_multi_sensor/board.c @@ -4,7 +4,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/circuitplayground_bluefruit/board.c b/ports/nrf/boards/circuitplayground_bluefruit/board.c index ff731d8f98..a0013e7215 100644 --- a/ports/nrf/boards/circuitplayground_bluefruit/board.c +++ b/ports/nrf/boards/circuitplayground_bluefruit/board.c @@ -36,17 +36,17 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { // Turn off board.POWER_SWITCH (power-saving switch) on each soft reload, to prevent confusion. nrf_gpio_cfg(POWER_SWITCH_PIN->number, - NRF_GPIO_PIN_DIR_OUTPUT, - NRF_GPIO_PIN_INPUT_DISCONNECT, - NRF_GPIO_PIN_NOPULL, - NRF_GPIO_PIN_S0S1, - NRF_GPIO_PIN_NOSENSE); + NRF_GPIO_PIN_DIR_OUTPUT, + NRF_GPIO_PIN_INPUT_DISCONNECT, + NRF_GPIO_PIN_NOPULL, + NRF_GPIO_PIN_S0S1, + NRF_GPIO_PIN_NOSENSE); nrf_gpio_pin_write(POWER_SWITCH_PIN->number, false); board_reset_user_neopixels(&pin_P0_13, 10); diff --git a/ports/nrf/boards/clue_nrf52840_express/board.c b/ports/nrf/boards/clue_nrf52840_express/board.c index cd46ce75d3..b5c0f56ba3 100644 --- a/ports/nrf/boards/clue_nrf52840_express/board.c +++ b/ports/nrf/boards/clue_nrf52840_express/board.c @@ -47,11 +47,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_14, &pin_P0_15, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -62,7 +62,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/nrf/boards/electronut_labs_blip/board.c b/ports/nrf/boards/electronut_labs_blip/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/electronut_labs_blip/board.c +++ b/ports/nrf/boards/electronut_labs_blip/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/electronut_labs_papyr/board.c b/ports/nrf/boards/electronut_labs_papyr/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/electronut_labs_papyr/board.c +++ b/ports/nrf/boards/electronut_labs_papyr/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/feather_bluefruit_sense/board.c b/ports/nrf/boards/feather_bluefruit_sense/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/feather_bluefruit_sense/board.c +++ b/ports/nrf/boards/feather_bluefruit_sense/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/feather_nrf52840_express/board.c b/ports/nrf/boards/feather_nrf52840_express/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/feather_nrf52840_express/board.c +++ b/ports/nrf/boards/feather_nrf52840_express/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/hiibot_bluefi/board.c b/ports/nrf/boards/hiibot_bluefi/board.c index a3fd5cf129..daca539619 100644 --- a/ports/nrf/boards/hiibot_bluefi/board.c +++ b/ports/nrf/boards/hiibot_bluefi/board.c @@ -47,23 +47,23 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_07, &pin_P1_08, NULL); // SCK, MOSI, MISO common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, &pin_P0_27, // TFT_DC Command or data &pin_P0_05, // TFT_CS Chip select - NULL, // no TFT_RST Reset - //&pin_P1_14, // TFT_RST Reset + NULL, // no TFT_RST Reset + // &pin_P1_14, // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/nrf/boards/hiibot_bluefi/mpconfigboard.h b/ports/nrf/boards/hiibot_bluefi/mpconfigboard.h index 4b7a884cfa..3c0af124e1 100644 --- a/ports/nrf/boards/hiibot_bluefi/mpconfigboard.h +++ b/ports/nrf/boards/hiibot_bluefi/mpconfigboard.h @@ -30,35 +30,35 @@ #define MICROPY_HW_BOARD_NAME "HiiBot BlueFi" #define MICROPY_HW_MCU_NAME "nRF52840" -#define MICROPY_HW_NEOPIXEL (&pin_P1_10) // P18 / D18 +#define MICROPY_HW_NEOPIXEL (&pin_P1_10) // P18 / D18 -#define MICROPY_HW_LED_STATUS (&pin_P1_12) // P17 / D17 +#define MICROPY_HW_LED_STATUS (&pin_P1_12) // P17 / D17 #if QSPI_FLASH_FILESYSTEM -#define MICROPY_QSPI_DATA0 NRF_GPIO_PIN_MAP(1, 1) -#define MICROPY_QSPI_DATA1 NRF_GPIO_PIN_MAP(1, 4) -#define MICROPY_QSPI_DATA2 NRF_GPIO_PIN_MAP(1, 6) -#define MICROPY_QSPI_DATA3 NRF_GPIO_PIN_MAP(1, 5) -#define MICROPY_QSPI_SCK NRF_GPIO_PIN_MAP(1, 3) -#define MICROPY_QSPI_CS NRF_GPIO_PIN_MAP(1, 2) +#define MICROPY_QSPI_DATA0 NRF_GPIO_PIN_MAP(1, 1) +#define MICROPY_QSPI_DATA1 NRF_GPIO_PIN_MAP(1, 4) +#define MICROPY_QSPI_DATA2 NRF_GPIO_PIN_MAP(1, 6) +#define MICROPY_QSPI_DATA3 NRF_GPIO_PIN_MAP(1, 5) +#define MICROPY_QSPI_SCK NRF_GPIO_PIN_MAP(1, 3) +#define MICROPY_QSPI_CS NRF_GPIO_PIN_MAP(1, 2) #endif #if SPI_FLASH_FILESYSTEM -#define SPI_FLASH_MOSI_PIN &pin_P1_01 -#define SPI_FLASH_MISO_PIN &pin_P1_04 -#define SPI_FLASH_SCK_PIN &pin_P1_03 -#define SPI_FLASH_CS_PIN &pin_P1_02 +#define SPI_FLASH_MOSI_PIN &pin_P1_01 +#define SPI_FLASH_MISO_PIN &pin_P1_04 +#define SPI_FLASH_SCK_PIN &pin_P1_03 +#define SPI_FLASH_CS_PIN &pin_P1_02 #endif // No 32kHz crystal. THere's a 32MHz crystal in the nRF module. -#define BOARD_HAS_32KHZ_XTAL (0) +#define BOARD_HAS_32KHZ_XTAL (0) -#define DEFAULT_I2C_BUS_SCL (&pin_P0_00) -#define DEFAULT_I2C_BUS_SDA (&pin_P0_31) +#define DEFAULT_I2C_BUS_SCL (&pin_P0_00) +#define DEFAULT_I2C_BUS_SDA (&pin_P0_31) -#define DEFAULT_SPI_BUS_SCK (&pin_P0_06) -#define DEFAULT_SPI_BUS_MOSI (&pin_P0_26) -#define DEFAULT_SPI_BUS_MISO (&pin_P0_04) +#define DEFAULT_SPI_BUS_SCK (&pin_P0_06) +#define DEFAULT_SPI_BUS_MOSI (&pin_P0_26) +#define DEFAULT_SPI_BUS_MISO (&pin_P0_04) -#define DEFAULT_UART_BUS_RX (&pin_P0_28) -#define DEFAULT_UART_BUS_TX (&pin_P0_02) +#define DEFAULT_UART_BUS_RX (&pin_P0_28) +#define DEFAULT_UART_BUS_TX (&pin_P0_02) diff --git a/ports/nrf/boards/hiibot_bluefi/pins.c b/ports/nrf/boards/hiibot_bluefi/pins.c index c7879c4c21..f871d5db86 100644 --- a/ports/nrf/boards/hiibot_bluefi/pins.c +++ b/ports/nrf/boards/hiibot_bluefi/pins.c @@ -111,7 +111,7 @@ STATIC const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_P27), MP_ROM_PTR(&pin_P1_13) }, { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_P1_13) }, - //{ MP_ROM_QSTR(MP_QSTR_TFT_RESET), MP_ROM_PTR(&pin_P1_13) }, + // { MP_ROM_QSTR(MP_QSTR_TFT_RESET), MP_ROM_PTR(&pin_P1_13) }, { MP_ROM_QSTR(MP_QSTR_TFT_BACKLIGHT), MP_ROM_PTR(&pin_P1_13) }, // P28~P33/D28~D33 connecte into QSPI FlashROM (W25Q16JV_IQ) diff --git a/ports/nrf/boards/ikigaisense_vita/board.c b/ports/nrf/boards/ikigaisense_vita/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/ikigaisense_vita/board.c +++ b/ports/nrf/boards/ikigaisense_vita/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/itsybitsy_nrf52840_express/board.c b/ports/nrf/boards/itsybitsy_nrf52840_express/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/itsybitsy_nrf52840_express/board.c +++ b/ports/nrf/boards/itsybitsy_nrf52840_express/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/makerdiary_m60_keyboard/board.c b/ports/nrf/boards/makerdiary_m60_keyboard/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/makerdiary_m60_keyboard/board.c +++ b/ports/nrf/boards/makerdiary_m60_keyboard/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/makerdiary_m60_keyboard/pins.c b/ports/nrf/boards/makerdiary_m60_keyboard/pins.c index fc85fa24b0..82e9dfc5a0 100644 --- a/ports/nrf/boards/makerdiary_m60_keyboard/pins.c +++ b/ports/nrf/boards/makerdiary_m60_keyboard/pins.c @@ -4,38 +4,38 @@ #include "shared-module/displayio/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR_R1), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_R2), MP_ROM_PTR(&pin_P0_06) }, - { MP_ROM_QSTR(MP_QSTR_R3), MP_ROM_PTR(&pin_P0_07) }, - { MP_ROM_QSTR(MP_QSTR_R4), MP_ROM_PTR(&pin_P0_08) }, - { MP_ROM_QSTR(MP_QSTR_R5), MP_ROM_PTR(&pin_P1_09) }, - { MP_ROM_QSTR(MP_QSTR_R6), MP_ROM_PTR(&pin_P1_08) }, - { MP_ROM_QSTR(MP_QSTR_R7), MP_ROM_PTR(&pin_P0_12) }, - { MP_ROM_QSTR(MP_QSTR_R8), MP_ROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_R1), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_R2), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_R3), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_R4), MP_ROM_PTR(&pin_P0_08) }, + { MP_ROM_QSTR(MP_QSTR_R5), MP_ROM_PTR(&pin_P1_09) }, + { MP_ROM_QSTR(MP_QSTR_R6), MP_ROM_PTR(&pin_P1_08) }, + { MP_ROM_QSTR(MP_QSTR_R7), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_R8), MP_ROM_PTR(&pin_P0_11) }, - { MP_ROM_QSTR(MP_QSTR_C1), MP_ROM_PTR(&pin_P0_19) }, - { MP_ROM_QSTR(MP_QSTR_C2), MP_ROM_PTR(&pin_P0_20) }, - { MP_ROM_QSTR(MP_QSTR_C3), MP_ROM_PTR(&pin_P0_21) }, - { MP_ROM_QSTR(MP_QSTR_C4), MP_ROM_PTR(&pin_P0_22) }, - { MP_ROM_QSTR(MP_QSTR_C5), MP_ROM_PTR(&pin_P0_23) }, - { MP_ROM_QSTR(MP_QSTR_C6), MP_ROM_PTR(&pin_P0_24) }, - { MP_ROM_QSTR(MP_QSTR_C7), MP_ROM_PTR(&pin_P0_25) }, - { MP_ROM_QSTR(MP_QSTR_C8), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_C1), MP_ROM_PTR(&pin_P0_19) }, + { MP_ROM_QSTR(MP_QSTR_C2), MP_ROM_PTR(&pin_P0_20) }, + { MP_ROM_QSTR(MP_QSTR_C3), MP_ROM_PTR(&pin_P0_21) }, + { MP_ROM_QSTR(MP_QSTR_C4), MP_ROM_PTR(&pin_P0_22) }, + { MP_ROM_QSTR(MP_QSTR_C5), MP_ROM_PTR(&pin_P0_23) }, + { MP_ROM_QSTR(MP_QSTR_C6), MP_ROM_PTR(&pin_P0_24) }, + { MP_ROM_QSTR(MP_QSTR_C7), MP_ROM_PTR(&pin_P0_25) }, + { MP_ROM_QSTR(MP_QSTR_C8), MP_ROM_PTR(&pin_P0_26) }, - { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_P0_16) }, - { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_P0_16) }, + { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_P0_15) }, - { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P1_06) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P1_05) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P1_06) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P1_05) }, - { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_P0_31) }, - { MP_ROM_QSTR(MP_QSTR_BTN), MP_ROM_PTR(&pin_P0_27) }, + { MP_ROM_QSTR(MP_QSTR_BTN), MP_ROM_PTR(&pin_P0_27) }, // { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, - { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) } + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) } }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/board.c b/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/board.c index 569106ec2a..51e453c1f0 100644 --- a/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/board.c +++ b/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/board.c @@ -48,11 +48,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_11, &pin_P0_12, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -63,7 +63,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/pins.c b/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/pins.c index 1892868330..a8eaab092e 100644 --- a/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/pins.c +++ b/ports/nrf/boards/makerdiary_nrf52840_m2_devkit/pins.c @@ -4,112 +4,112 @@ #include "shared-module/displayio/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR_AIN0), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_AIN3), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_AIN4), MP_ROM_PTR(&pin_P0_28) }, - { MP_ROM_QSTR(MP_QSTR_AIN5), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_AIN6), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_AIN7), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_AIN0), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_AIN3), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_AIN4), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_AIN5), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_AIN6), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_AIN7), MP_ROM_PTR(&pin_P0_31) }, - { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_VDIV), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_VDIV), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_P0_06) }, - { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_P0_07) }, - { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_P0_08) }, - { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_P10), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P11), MP_ROM_PTR(&pin_P0_11) }, - { MP_ROM_QSTR(MP_QSTR_P12), MP_ROM_PTR(&pin_P0_12) }, - { MP_ROM_QSTR(MP_QSTR_P13), MP_ROM_PTR(&pin_P0_13) }, - { MP_ROM_QSTR(MP_QSTR_P14), MP_ROM_PTR(&pin_P0_14) }, - { MP_ROM_QSTR(MP_QSTR_P15), MP_ROM_PTR(&pin_P0_15) }, - { MP_ROM_QSTR(MP_QSTR_P16), MP_ROM_PTR(&pin_P0_16) }, - { MP_ROM_QSTR(MP_QSTR_P17), MP_ROM_PTR(&pin_P0_17) }, - { MP_ROM_QSTR(MP_QSTR_P18), MP_ROM_PTR(&pin_P0_18) }, - { MP_ROM_QSTR(MP_QSTR_P19), MP_ROM_PTR(&pin_P0_19) }, - { MP_ROM_QSTR(MP_QSTR_P20), MP_ROM_PTR(&pin_P0_20) }, - { MP_ROM_QSTR(MP_QSTR_P21), MP_ROM_PTR(&pin_P0_21) }, - { MP_ROM_QSTR(MP_QSTR_P25), MP_ROM_PTR(&pin_P0_25) }, - { MP_ROM_QSTR(MP_QSTR_P26), MP_ROM_PTR(&pin_P0_26) }, - { MP_ROM_QSTR(MP_QSTR_P27), MP_ROM_PTR(&pin_P0_27) }, - { MP_ROM_QSTR(MP_QSTR_P28), MP_ROM_PTR(&pin_P0_28) }, - { MP_ROM_QSTR(MP_QSTR_P29), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_P30), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_P31), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_P0_08) }, + { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_P10), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_P11), MP_ROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_P12), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_P13), MP_ROM_PTR(&pin_P0_13) }, + { MP_ROM_QSTR(MP_QSTR_P14), MP_ROM_PTR(&pin_P0_14) }, + { MP_ROM_QSTR(MP_QSTR_P15), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_P16), MP_ROM_PTR(&pin_P0_16) }, + { MP_ROM_QSTR(MP_QSTR_P17), MP_ROM_PTR(&pin_P0_17) }, + { MP_ROM_QSTR(MP_QSTR_P18), MP_ROM_PTR(&pin_P0_18) }, + { MP_ROM_QSTR(MP_QSTR_P19), MP_ROM_PTR(&pin_P0_19) }, + { MP_ROM_QSTR(MP_QSTR_P20), MP_ROM_PTR(&pin_P0_20) }, + { MP_ROM_QSTR(MP_QSTR_P21), MP_ROM_PTR(&pin_P0_21) }, + { MP_ROM_QSTR(MP_QSTR_P25), MP_ROM_PTR(&pin_P0_25) }, + { MP_ROM_QSTR(MP_QSTR_P26), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_P27), MP_ROM_PTR(&pin_P0_27) }, + { MP_ROM_QSTR(MP_QSTR_P28), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_P29), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_P30), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_P31), MP_ROM_PTR(&pin_P0_31) }, - { MP_ROM_QSTR(MP_QSTR_P1_0), MP_ROM_PTR(&pin_P1_00) }, - { MP_ROM_QSTR(MP_QSTR_P1_1), MP_ROM_PTR(&pin_P1_01) }, - { MP_ROM_QSTR(MP_QSTR_P1_2), MP_ROM_PTR(&pin_P1_02) }, - { MP_ROM_QSTR(MP_QSTR_P1_3), MP_ROM_PTR(&pin_P1_03) }, - { MP_ROM_QSTR(MP_QSTR_P1_4), MP_ROM_PTR(&pin_P1_04) }, - { MP_ROM_QSTR(MP_QSTR_P1_5), MP_ROM_PTR(&pin_P1_05) }, - { MP_ROM_QSTR(MP_QSTR_P1_6), MP_ROM_PTR(&pin_P1_06) }, - { MP_ROM_QSTR(MP_QSTR_P1_7), MP_ROM_PTR(&pin_P1_07) }, - { MP_ROM_QSTR(MP_QSTR_P1_8), MP_ROM_PTR(&pin_P1_08) }, - { MP_ROM_QSTR(MP_QSTR_P1_9), MP_ROM_PTR(&pin_P1_09) }, + { MP_ROM_QSTR(MP_QSTR_P1_0), MP_ROM_PTR(&pin_P1_00) }, + { MP_ROM_QSTR(MP_QSTR_P1_1), MP_ROM_PTR(&pin_P1_01) }, + { MP_ROM_QSTR(MP_QSTR_P1_2), MP_ROM_PTR(&pin_P1_02) }, + { MP_ROM_QSTR(MP_QSTR_P1_3), MP_ROM_PTR(&pin_P1_03) }, + { MP_ROM_QSTR(MP_QSTR_P1_4), MP_ROM_PTR(&pin_P1_04) }, + { MP_ROM_QSTR(MP_QSTR_P1_5), MP_ROM_PTR(&pin_P1_05) }, + { MP_ROM_QSTR(MP_QSTR_P1_6), MP_ROM_PTR(&pin_P1_06) }, + { MP_ROM_QSTR(MP_QSTR_P1_7), MP_ROM_PTR(&pin_P1_07) }, + { MP_ROM_QSTR(MP_QSTR_P1_8), MP_ROM_PTR(&pin_P1_08) }, + { MP_ROM_QSTR(MP_QSTR_P1_9), MP_ROM_PTR(&pin_P1_09) }, - { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_P0_15) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_P0_15) }, - { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_P0_16) }, - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_P0_16) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_P0_16) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_P0_16) }, - { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_P0_19) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_P0_20) }, - { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_P0_21) }, - { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_P0_22) }, - { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_P0_23) }, - { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_P0_24) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_P1_00) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_P1_01) }, - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_P1_02) }, - { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_P1_03) }, - { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_P1_04) }, - { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_P1_07) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_P0_19) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_P0_20) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_P0_21) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_P0_22) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_P0_23) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_P0_24) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_P1_00) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_P1_01) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_P1_02) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_P1_03) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_P1_04) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_P1_07) }, - { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_P1_05) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P1_05) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_P1_05) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P1_05) }, - { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_P1_06) }, - { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P1_06) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_P1_06) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P1_06) }, - { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_P0_28) }, - { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_P0_27) }, - { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_P0_26) }, - { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_P0_27) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P0_11) }, - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_P0_12) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_P1_08) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_P1_08) }, - { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_P0_08) }, - { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_P0_06) }, - { MP_ROM_QSTR(MP_QSTR_LCD_BL), MP_ROM_PTR(&pin_P0_20) }, - { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_P1_09) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_P0_08) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BL), MP_ROM_PTR(&pin_P0_20) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_P1_09) }, - { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_P0_31) }, - { MP_ROM_QSTR(MP_QSTR_BUTTON_USR), MP_ROM_PTR(&pin_P0_19) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_USR), MP_ROM_PTR(&pin_P0_19) }, - { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, - { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, - { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, - { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display)} + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display)} }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nrf/boards/makerdiary_nrf52840_mdk/board.c b/ports/nrf/boards/makerdiary_nrf52840_mdk/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/makerdiary_nrf52840_mdk/board.c +++ b/ports/nrf/boards/makerdiary_nrf52840_mdk/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/makerdiary_nrf52840_mdk/pins.c b/ports/nrf/boards/makerdiary_nrf52840_mdk/pins.c index 34f487b1de..bd0e6e4802 100644 --- a/ports/nrf/boards/makerdiary_nrf52840_mdk/pins.c +++ b/ports/nrf/boards/makerdiary_nrf52840_mdk/pins.c @@ -1,61 +1,61 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR_AIN0), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_AIN3), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_AIN4), MP_ROM_PTR(&pin_P0_28) }, - { MP_ROM_QSTR(MP_QSTR_AIN5), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_AIN6), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_AIN7), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_AIN0), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_AIN3), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_AIN4), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_AIN5), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_AIN6), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_AIN7), MP_ROM_PTR(&pin_P0_31) }, - { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_VDIV), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_VDIV), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_P0_06) }, - { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_P0_07) }, - { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_P0_08) }, - { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_P10), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P11), MP_ROM_PTR(&pin_P0_11) }, - { MP_ROM_QSTR(MP_QSTR_P12), MP_ROM_PTR(&pin_P0_12) }, - { MP_ROM_QSTR(MP_QSTR_P13), MP_ROM_PTR(&pin_P0_13) }, - { MP_ROM_QSTR(MP_QSTR_P14), MP_ROM_PTR(&pin_P0_14) }, - { MP_ROM_QSTR(MP_QSTR_P15), MP_ROM_PTR(&pin_P0_15) }, - { MP_ROM_QSTR(MP_QSTR_P16), MP_ROM_PTR(&pin_P0_16) }, - { MP_ROM_QSTR(MP_QSTR_P17), MP_ROM_PTR(&pin_P0_17) }, - { MP_ROM_QSTR(MP_QSTR_P21), MP_ROM_PTR(&pin_P0_21) }, - { MP_ROM_QSTR(MP_QSTR_P25), MP_ROM_PTR(&pin_P0_25) }, - { MP_ROM_QSTR(MP_QSTR_P26), MP_ROM_PTR(&pin_P0_26) }, - { MP_ROM_QSTR(MP_QSTR_P27), MP_ROM_PTR(&pin_P0_27) }, - { MP_ROM_QSTR(MP_QSTR_P28), MP_ROM_PTR(&pin_P0_28) }, - { MP_ROM_QSTR(MP_QSTR_P29), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_P30), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_P31), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_P0_08) }, + { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_P10), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_P11), MP_ROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_P12), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_P13), MP_ROM_PTR(&pin_P0_13) }, + { MP_ROM_QSTR(MP_QSTR_P14), MP_ROM_PTR(&pin_P0_14) }, + { MP_ROM_QSTR(MP_QSTR_P15), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_P16), MP_ROM_PTR(&pin_P0_16) }, + { MP_ROM_QSTR(MP_QSTR_P17), MP_ROM_PTR(&pin_P0_17) }, + { MP_ROM_QSTR(MP_QSTR_P21), MP_ROM_PTR(&pin_P0_21) }, + { MP_ROM_QSTR(MP_QSTR_P25), MP_ROM_PTR(&pin_P0_25) }, + { MP_ROM_QSTR(MP_QSTR_P26), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_P27), MP_ROM_PTR(&pin_P0_27) }, + { MP_ROM_QSTR(MP_QSTR_P28), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_P29), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_P30), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_P31), MP_ROM_PTR(&pin_P0_31) }, - { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P1_03) }, - { MP_ROM_QSTR(MP_QSTR_CSN), MP_ROM_PTR(&pin_P1_06) }, - { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_P1_05) }, - { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_P1_04) }, - { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_P1_02) }, - { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_P1_01) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P1_03) }, + { MP_ROM_QSTR(MP_QSTR_CSN), MP_ROM_PTR(&pin_P1_06) }, + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_P1_05) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_P1_04) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_P1_02) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_P1_01) }, - { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_P0_20) }, - { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_P0_19) }, + { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_P0_20) }, + { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_P0_19) }, - { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_P0_23) }, - { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_P0_22) }, - { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_P0_24) }, + { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_P0_23) }, + { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_P0_22) }, + { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_P0_24) }, - { MP_ROM_QSTR(MP_QSTR_BUTTON_USR), MP_ROM_PTR(&pin_P1_00) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_USR), MP_ROM_PTR(&pin_P1_00) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nrf/boards/makerdiary_nrf52840_mdk_usb_dongle/board.c b/ports/nrf/boards/makerdiary_nrf52840_mdk_usb_dongle/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/makerdiary_nrf52840_mdk_usb_dongle/board.c +++ b/ports/nrf/boards/makerdiary_nrf52840_mdk_usb_dongle/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/makerdiary_nrf52840_mdk_usb_dongle/pins.c b/ports/nrf/boards/makerdiary_nrf52840_mdk_usb_dongle/pins.c index d46f369422..05813bd04a 100644 --- a/ports/nrf/boards/makerdiary_nrf52840_mdk_usb_dongle/pins.c +++ b/ports/nrf/boards/makerdiary_nrf52840_mdk_usb_dongle/pins.c @@ -1,38 +1,38 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR_AIN0), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_AIN3), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_AIN0), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_AIN3), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_P0_04) }, // User must connect manually. - { MP_ROM_QSTR(MP_QSTR_VDIV), MP_ROM_PTR(&pin_P0_05) }, // User must connect manually. + { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_P0_04) }, // User must connect manually. + { MP_ROM_QSTR(MP_QSTR_VDIV), MP_ROM_PTR(&pin_P0_05) }, // User must connect manually. - { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_P0_06) }, - { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_P0_07) }, - { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_P0_08) }, - { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_P10), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P18), MP_ROM_PTR(&pin_P0_18) }, // !Reset button. - { MP_ROM_QSTR(MP_QSTR_P19), MP_ROM_PTR(&pin_P0_19) }, - { MP_ROM_QSTR(MP_QSTR_P22), MP_ROM_PTR(&pin_P0_22) }, // green led, low is on. - { MP_ROM_QSTR(MP_QSTR_P23), MP_ROM_PTR(&pin_P0_23) }, // red led, low is on. - { MP_ROM_QSTR(MP_QSTR_P24), MP_ROM_PTR(&pin_P0_24) }, // blue led, low is on. + { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_P0_08) }, + { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_P10), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_P18), MP_ROM_PTR(&pin_P0_18) }, // !Reset button. + { MP_ROM_QSTR(MP_QSTR_P19), MP_ROM_PTR(&pin_P0_19) }, + { MP_ROM_QSTR(MP_QSTR_P22), MP_ROM_PTR(&pin_P0_22) }, // green led, low is on. + { MP_ROM_QSTR(MP_QSTR_P23), MP_ROM_PTR(&pin_P0_23) }, // red led, low is on. + { MP_ROM_QSTR(MP_QSTR_P24), MP_ROM_PTR(&pin_P0_24) }, // blue led, low is on. - { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_P0_23) }, // Low is on. - { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_P0_22) }, // Low is on. - { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_P0_24) }, // Low is on. + { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_P0_23) }, // Low is on. + { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_P0_22) }, // Low is on. + { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_P0_24) }, // Low is on. - // BUT this is the RESET pin so we can't really use it. - { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_P0_18) }, // Low is pressed. + // BUT this is the RESET pin so we can't really use it. + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_P0_18) }, // Low is pressed. }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nrf/boards/metro_nrf52840_express/board.c b/ports/nrf/boards/metro_nrf52840_express/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/metro_nrf52840_express/board.c +++ b/ports/nrf/boards/metro_nrf52840_express/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/nice_nano/board.c b/ports/nrf/boards/nice_nano/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/nice_nano/board.c +++ b/ports/nrf/boards/nice_nano/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/nice_nano/mpconfigboard.h b/ports/nrf/boards/nice_nano/mpconfigboard.h index 5f61947007..fd605e12f0 100644 --- a/ports/nrf/boards/nice_nano/mpconfigboard.h +++ b/ports/nrf/boards/nice_nano/mpconfigboard.h @@ -34,12 +34,12 @@ #define BOARD_HAS_CRYSTAL 1 -#define DEFAULT_I2C_BUS_SCL (&pin_P0_20) -#define DEFAULT_I2C_BUS_SDA (&pin_P0_17) +#define DEFAULT_I2C_BUS_SCL (&pin_P0_20) +#define DEFAULT_I2C_BUS_SDA (&pin_P0_17) -#define DEFAULT_SPI_BUS_SCK (&pin_P1_13) -#define DEFAULT_SPI_BUS_MOSI (&pin_P0_10) -#define DEFAULT_SPI_BUS_MISO (&pin_P1_11) +#define DEFAULT_SPI_BUS_SCK (&pin_P1_13) +#define DEFAULT_SPI_BUS_MOSI (&pin_P0_10) +#define DEFAULT_SPI_BUS_MISO (&pin_P1_11) -#define DEFAULT_UART_BUS_RX (&pin_P0_08) -#define DEFAULT_UART_BUS_TX (&pin_P0_06) +#define DEFAULT_UART_BUS_RX (&pin_P0_08) +#define DEFAULT_UART_BUS_TX (&pin_P0_06) diff --git a/ports/nrf/boards/nrf52_prefix.c b/ports/nrf/boards/nrf52_prefix.c index 0c96eb61ef..92fb165b50 100644 --- a/ports/nrf/boards/nrf52_prefix.c +++ b/ports/nrf/boards/nrf52_prefix.c @@ -7,10 +7,10 @@ #include "nrf_pin.h" #define PIN(p_name, p_port, p_pin, p_adc_channel) \ -{ \ - { &mcu_pin_type }, \ - .name = MP_QSTR_ ## p_name, \ - .port = (p_port), \ - .pin = (p_pin), \ - .adc_channel = (p_adc_channel), \ -} + { \ + { &mcu_pin_type }, \ + .name = MP_QSTR_##p_name, \ + .port = (p_port), \ + .pin = (p_pin), \ + .adc_channel = (p_adc_channel), \ + } diff --git a/ports/nrf/boards/ohs2020_badge/board.c b/ports/nrf/boards/ohs2020_badge/board.c index 20abf4e2a9..1522e45c9a 100644 --- a/ports/nrf/boards/ohs2020_badge/board.c +++ b/ports/nrf/boards/ohs2020_badge/board.c @@ -47,11 +47,11 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { - busio_spi_obj_t* spi = &displays[0].fourwire_bus.inline_bus; + busio_spi_obj_t *spi = &displays[0].fourwire_bus.inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_11, &pin_P0_12, NULL); common_hal_busio_spi_never_reset(spi); - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; common_hal_displayio_fourwire_construct(bus, spi, @@ -62,7 +62,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/nrf/boards/particle_argon/board.c b/ports/nrf/boards/particle_argon/board.c index a41f0ae06e..94ee5d6957 100644 --- a/ports/nrf/boards/particle_argon/board.c +++ b/ports/nrf/boards/particle_argon/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/particle_boron/board.c b/ports/nrf/boards/particle_boron/board.c index a41f0ae06e..94ee5d6957 100644 --- a/ports/nrf/boards/particle_boron/board.c +++ b/ports/nrf/boards/particle_boron/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/particle_xenon/board.c b/ports/nrf/boards/particle_xenon/board.c index a41f0ae06e..94ee5d6957 100644 --- a/ports/nrf/boards/particle_xenon/board.c +++ b/ports/nrf/boards/particle_xenon/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/pca10056/board.c b/ports/nrf/boards/pca10056/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/pca10056/board.c +++ b/ports/nrf/boards/pca10056/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/pca10056/examples/buttons.py b/ports/nrf/boards/pca10056/examples/buttons.py index 1a0c5aabbc..4db3576970 100644 --- a/ports/nrf/boards/pca10056/examples/buttons.py +++ b/ports/nrf/boards/pca10056/examples/buttons.py @@ -17,9 +17,9 @@ while True: if buttons != prev_buttons: for i in range(0, 4): - bit = (1 << i) + bit = 1 << i if (buttons & bit) != (prev_buttons & bit): - print('Button %d %s' % (i + 1, 'pressed' if buttons & bit else 'released')) + print("Button %d %s" % (i + 1, "pressed" if buttons & bit else "released")) prev_buttons = buttons diff --git a/ports/nrf/boards/pca10059/board.c b/ports/nrf/boards/pca10059/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/pca10059/board.c +++ b/ports/nrf/boards/pca10059/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/pca10100/board.c b/ports/nrf/boards/pca10100/board.c index a41f0ae06e..94ee5d6957 100644 --- a/ports/nrf/boards/pca10100/board.c +++ b/ports/nrf/boards/pca10100/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/pca10100/mpconfigboard.h b/ports/nrf/boards/pca10100/mpconfigboard.h index 4639a208b4..00c10fc255 100644 --- a/ports/nrf/boards/pca10100/mpconfigboard.h +++ b/ports/nrf/boards/pca10100/mpconfigboard.h @@ -35,9 +35,9 @@ #define MICROPY_HW_LED_RX (&pin_P0_15) #define CIRCUITPY_INTERNAL_NVM_SIZE 0 -#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (60*1024) +#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (60 * 1024) -#define CIRCUITPY_BLE_CONFIG_SIZE (12*1024) +#define CIRCUITPY_BLE_CONFIG_SIZE (12 * 1024) // Reduce nRF SoftRadio memory usage #define BLEIO_VS_UUID_COUNT 10 @@ -47,4 +47,4 @@ #define BLEIO_TOTAL_CONNECTION_COUNT 2 #define BLEIO_ATTR_TAB_SIZE (BLE_GATTS_ATTR_TAB_SIZE_DEFAULT * 2) -#define SOFTDEVICE_RAM_SIZE (32*1024) +#define SOFTDEVICE_RAM_SIZE (32 * 1024) diff --git a/ports/nrf/boards/pitaya_go/board.c b/ports/nrf/boards/pitaya_go/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/pitaya_go/board.c +++ b/ports/nrf/boards/pitaya_go/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/pitaya_go/pins.c b/ports/nrf/boards/pitaya_go/pins.c index ba333fc2be..c0f2976a57 100644 --- a/ports/nrf/boards/pitaya_go/pins.c +++ b/ports/nrf/boards/pitaya_go/pins.c @@ -1,64 +1,64 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR_AIN0), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_AIN3), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_AIN4), MP_ROM_PTR(&pin_P0_28) }, - { MP_ROM_QSTR(MP_QSTR_AIN5), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_AIN6), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_AIN7), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_AIN0), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_AIN3), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_AIN4), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_AIN5), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_AIN6), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_AIN7), MP_ROM_PTR(&pin_P0_31) }, - { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_VDIV), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_AREF), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_VDIV), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_NFC1), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_NFC2), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_P0_06) }, - { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_P0_07) }, - { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_P0_08) }, - { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_P10), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P11), MP_ROM_PTR(&pin_P0_11) }, - { MP_ROM_QSTR(MP_QSTR_P12), MP_ROM_PTR(&pin_P0_12) }, - { MP_ROM_QSTR(MP_QSTR_P13), MP_ROM_PTR(&pin_P0_13) }, - { MP_ROM_QSTR(MP_QSTR_P14), MP_ROM_PTR(&pin_P0_14) }, - { MP_ROM_QSTR(MP_QSTR_P15), MP_ROM_PTR(&pin_P0_15) }, - { MP_ROM_QSTR(MP_QSTR_P16), MP_ROM_PTR(&pin_P0_16) }, - { MP_ROM_QSTR(MP_QSTR_P17), MP_ROM_PTR(&pin_P0_17) }, - { MP_ROM_QSTR(MP_QSTR_P18), MP_ROM_PTR(&pin_P0_18) }, - { MP_ROM_QSTR(MP_QSTR_P19), MP_ROM_PTR(&pin_P0_19) }, - { MP_ROM_QSTR(MP_QSTR_P20), MP_ROM_PTR(&pin_P0_20) }, - { MP_ROM_QSTR(MP_QSTR_P21), MP_ROM_PTR(&pin_P0_21) }, - { MP_ROM_QSTR(MP_QSTR_P22), MP_ROM_PTR(&pin_P0_22) }, - { MP_ROM_QSTR(MP_QSTR_P23), MP_ROM_PTR(&pin_P0_23) }, - { MP_ROM_QSTR(MP_QSTR_P24), MP_ROM_PTR(&pin_P0_24) }, - { MP_ROM_QSTR(MP_QSTR_P25), MP_ROM_PTR(&pin_P0_25) }, - { MP_ROM_QSTR(MP_QSTR_P26), MP_ROM_PTR(&pin_P0_26) }, - { MP_ROM_QSTR(MP_QSTR_P27), MP_ROM_PTR(&pin_P0_27) }, - { MP_ROM_QSTR(MP_QSTR_P28), MP_ROM_PTR(&pin_P0_28) }, - { MP_ROM_QSTR(MP_QSTR_P29), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_P30), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_P31), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_P0_08) }, + { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_P10), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_P11), MP_ROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_P12), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_P13), MP_ROM_PTR(&pin_P0_13) }, + { MP_ROM_QSTR(MP_QSTR_P14), MP_ROM_PTR(&pin_P0_14) }, + { MP_ROM_QSTR(MP_QSTR_P15), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_P16), MP_ROM_PTR(&pin_P0_16) }, + { MP_ROM_QSTR(MP_QSTR_P17), MP_ROM_PTR(&pin_P0_17) }, + { MP_ROM_QSTR(MP_QSTR_P18), MP_ROM_PTR(&pin_P0_18) }, + { MP_ROM_QSTR(MP_QSTR_P19), MP_ROM_PTR(&pin_P0_19) }, + { MP_ROM_QSTR(MP_QSTR_P20), MP_ROM_PTR(&pin_P0_20) }, + { MP_ROM_QSTR(MP_QSTR_P21), MP_ROM_PTR(&pin_P0_21) }, + { MP_ROM_QSTR(MP_QSTR_P22), MP_ROM_PTR(&pin_P0_22) }, + { MP_ROM_QSTR(MP_QSTR_P23), MP_ROM_PTR(&pin_P0_23) }, + { MP_ROM_QSTR(MP_QSTR_P24), MP_ROM_PTR(&pin_P0_24) }, + { MP_ROM_QSTR(MP_QSTR_P25), MP_ROM_PTR(&pin_P0_25) }, + { MP_ROM_QSTR(MP_QSTR_P26), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_P27), MP_ROM_PTR(&pin_P0_27) }, + { MP_ROM_QSTR(MP_QSTR_P28), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_P29), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_P30), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_P31), MP_ROM_PTR(&pin_P0_31) }, - { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P1_04) }, - { MP_ROM_QSTR(MP_QSTR_CSN), MP_ROM_PTR(&pin_P1_03) }, - { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_P1_06) }, - { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_P1_01) }, - { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_P1_05) }, - { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_P1_02) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P1_04) }, + { MP_ROM_QSTR(MP_QSTR_CSN), MP_ROM_PTR(&pin_P1_03) }, + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_P1_06) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_P1_01) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_P1_05) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_P1_02) }, - { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_P0_11) }, - { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_P0_12) }, - { MP_ROM_QSTR(MP_QSTR_BUTTON_USER), MP_ROM_PTR(&pin_P1_00) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_USER), MP_ROM_PTR(&pin_P1_00) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nrf/boards/raytac_mdbt50q-db-40/board.c b/ports/nrf/boards/raytac_mdbt50q-db-40/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/raytac_mdbt50q-db-40/board.c +++ b/ports/nrf/boards/raytac_mdbt50q-db-40/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/simmel/board.c b/ports/nrf/boards/simmel/board.c index a41f0ae06e..94ee5d6957 100644 --- a/ports/nrf/boards/simmel/board.c +++ b/ports/nrf/boards/simmel/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/simmel/mpconfigboard.h b/ports/nrf/boards/simmel/mpconfigboard.h index a89f540b04..9361e8ef23 100644 --- a/ports/nrf/boards/simmel/mpconfigboard.h +++ b/ports/nrf/boards/simmel/mpconfigboard.h @@ -40,10 +40,10 @@ #endif #define CIRCUITPY_INTERNAL_NVM_SIZE 0 -#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (76*1024) +#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (76 * 1024) #define BOOTLOADER_SIZE (0x4000) // 12 kiB -#define CIRCUITPY_BLE_CONFIG_SIZE (12*1024) +#define CIRCUITPY_BLE_CONFIG_SIZE (12 * 1024) #define DEFAULT_I2C_BUS_SCL (&pin_P0_08) #define DEFAULT_I2C_BUS_SDA (&pin_P1_09) @@ -56,4 +56,4 @@ #define BLEIO_TOTAL_CONNECTION_COUNT 2 #define BLEIO_ATTR_TAB_SIZE (BLE_GATTS_ATTR_TAB_SIZE_DEFAULT * 2) -#define SOFTDEVICE_RAM_SIZE (32*1024) +#define SOFTDEVICE_RAM_SIZE (32 * 1024) diff --git a/ports/nrf/boards/sparkfun_nrf52840_micromod/board.c b/ports/nrf/boards/sparkfun_nrf52840_micromod/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/sparkfun_nrf52840_micromod/board.c +++ b/ports/nrf/boards/sparkfun_nrf52840_micromod/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/sparkfun_nrf52840_mini/board.c b/ports/nrf/boards/sparkfun_nrf52840_mini/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/sparkfun_nrf52840_mini/board.c +++ b/ports/nrf/boards/sparkfun_nrf52840_mini/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/sparkfun_nrf52840_mini/pins.c b/ports/nrf/boards/sparkfun_nrf52840_mini/pins.c index e7b61db584..026b566ef8 100644 --- a/ports/nrf/boards/sparkfun_nrf52840_mini/pins.c +++ b/ports/nrf/boards/sparkfun_nrf52840_mini/pins.c @@ -3,7 +3,7 @@ STATIC const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_P1_15) }, // D1/TX { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_P0_17) }, // D0/RX - // D2 on qwiic gap + // D2 on qwiic gap { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_P0_19) }, // D3 { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_P0_20) }, // D4 { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_P0_21) }, // D5 diff --git a/ports/nrf/boards/teknikio_bluebird/board.c b/ports/nrf/boards/teknikio_bluebird/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/teknikio_bluebird/board.c +++ b/ports/nrf/boards/teknikio_bluebird/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/boards/teknikio_bluebird/mpconfigboard.h b/ports/nrf/boards/teknikio_bluebird/mpconfigboard.h index c130cd8c06..8ddeeb72aa 100644 --- a/ports/nrf/boards/teknikio_bluebird/mpconfigboard.h +++ b/ports/nrf/boards/teknikio_bluebird/mpconfigboard.h @@ -25,7 +25,7 @@ * THE SOFTWARE. */ -//https://github.com/Teknikio/TKInventionBuilderFramework +// https://github.com/Teknikio/TKInventionBuilderFramework #include "nrfx/hal/nrf_gpio.h" diff --git a/ports/nrf/boards/tinkeringtech_scoutmakes_azul/board.c b/ports/nrf/boards/tinkeringtech_scoutmakes_azul/board.c index 7817933281..688cfb4ded 100644 --- a/ports/nrf/boards/tinkeringtech_scoutmakes_azul/board.c +++ b/ports/nrf/boards/tinkeringtech_scoutmakes_azul/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/nrf/common-hal/_bleio/Adapter.c b/ports/nrf/common-hal/_bleio/Adapter.c index 10794c16a8..ca21222b5d 100644 --- a/ports/nrf/common-hal/_bleio/Adapter.c +++ b/ports/nrf/common-hal/_bleio/Adapter.c @@ -80,7 +80,7 @@ const nvm_bytearray_obj_t common_hal_bleio_nvm_obj = { .base = { .type = &nvm_bytearray_type, }, - .start_address = (uint8_t*) CIRCUITPY_BLE_CONFIG_START_ADDR, + .start_address = (uint8_t *)CIRCUITPY_BLE_CONFIG_START_ADDR, .len = CIRCUITPY_BLE_CONFIG_SIZE, }; @@ -94,17 +94,17 @@ bleio_connection_internal_t bleio_connections[BLEIO_TOTAL_CONNECTION_COUNT]; extern uint32_t _ram_start; STATIC uint32_t ble_stack_enable(void) { nrf_clock_lf_cfg_t clock_config = { -#if BOARD_HAS_32KHZ_XTAL - .source = NRF_CLOCK_LF_SRC_XTAL, - .rc_ctiv = 0, + #if BOARD_HAS_32KHZ_XTAL + .source = NRF_CLOCK_LF_SRC_XTAL, + .rc_ctiv = 0, .rc_temp_ctiv = 0, - .accuracy = NRF_CLOCK_LF_ACCURACY_20_PPM, -#else - .source = NRF_CLOCK_LF_SRC_RC, - .rc_ctiv = 16, + .accuracy = NRF_CLOCK_LF_ACCURACY_20_PPM, + #else + .source = NRF_CLOCK_LF_SRC_RC, + .rc_ctiv = 16, .rc_temp_ctiv = 2, - .accuracy = NRF_CLOCK_LF_ACCURACY_250_PPM, -#endif + .accuracy = NRF_CLOCK_LF_ACCURACY_250_PPM, + #endif }; uint32_t err_code = sd_softdevice_enable(&clock_config, softdevice_assert_handler); @@ -211,20 +211,20 @@ STATIC uint32_t ble_stack_enable(void) { ble_gap_conn_params_t gap_conn_params = { .min_conn_interval = BLE_MIN_CONN_INTERVAL, .max_conn_interval = BLE_MAX_CONN_INTERVAL, - .slave_latency = BLE_SLAVE_LATENCY, - .conn_sup_timeout = BLE_CONN_SUP_TIMEOUT, + .slave_latency = BLE_SLAVE_LATENCY, + .conn_sup_timeout = BLE_CONN_SUP_TIMEOUT, }; - err_code = sd_ble_gap_ppcp_set(&gap_conn_params); - if (err_code != NRF_SUCCESS) { - return err_code; - } + err_code = sd_ble_gap_ppcp_set(&gap_conn_params); + if (err_code != NRF_SUCCESS) { + return err_code; + } - err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_UNKNOWN); - return err_code; + err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_UNKNOWN); + return err_code; } STATIC bool adapter_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { - bleio_adapter_obj_t *self = (bleio_adapter_obj_t*)self_in; + bleio_adapter_obj_t *self = (bleio_adapter_obj_t *)self_in; // For debugging. // mp_printf(&mp_plat_print, "Adapter event: 0x%04x\n", ble_evt->header.evt_id); @@ -242,7 +242,7 @@ STATIC bool adapter_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { } // Central has connected. - ble_gap_evt_connected_t* connected = &ble_evt->evt.gap_evt.params.connected; + ble_gap_evt_connected_t *connected = &ble_evt->evt.gap_evt.params.connected; connection->conn_handle = ble_evt->evt.gap_evt.conn_handle; connection->connection_obj = mp_const_none; @@ -284,7 +284,7 @@ STATIC bool adapter_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { connection->conn_handle = BLE_CONN_HANDLE_INVALID; connection->pair_status = PAIR_NOT_PAIRED; if (connection->connection_obj != mp_const_none) { - bleio_connection_obj_t* obj = connection->connection_obj; + bleio_connection_obj_t *obj = connection->connection_obj; obj->connection = NULL; obj->disconnect_reason = ble_evt->evt.gap_evt.params.disconnected.reason; } @@ -310,7 +310,7 @@ STATIC void get_address(bleio_adapter_obj_t *self, ble_gap_addr_t *address) { check_nrf_error(sd_ble_gap_addr_get(address)); } -char default_ble_name[] = { 'C', 'I', 'R', 'C', 'U', 'I', 'T', 'P', 'Y', 0, 0, 0, 0 , 0}; +char default_ble_name[] = { 'C', 'I', 'R', 'C', 'U', 'I', 'T', 'P', 'Y', 0, 0, 0, 0, 0}; STATIC void bleio_adapter_reset_name(bleio_adapter_obj_t *self) { uint8_t len = sizeof(default_ble_name) - 1; @@ -324,7 +324,7 @@ STATIC void bleio_adapter_reset_name(bleio_adapter_obj_t *self) { default_ble_name[len - 1] = nibble_to_hex_lower[local_address.addr[0] & 0xf]; default_ble_name[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings - common_hal_bleio_adapter_set_name(self, (char*) default_ble_name); + common_hal_bleio_adapter_set_name(self, (char *)default_ble_name); } void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enabled) { @@ -401,7 +401,7 @@ bool common_hal_bleio_adapter_set_address(bleio_adapter_obj_t *self, bleio_addre return sd_ble_gap_addr_set(&local_address) == NRF_SUCCESS; } -mp_obj_str_t* common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) { +mp_obj_str_t *common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) { uint16_t len = 0; sd_ble_gap_device_name_get(NULL, &len); uint8_t buf[len]; @@ -409,18 +409,18 @@ mp_obj_str_t* common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) { if (err_code != NRF_SUCCESS) { return NULL; } - return mp_obj_new_str((char*) buf, len); + return mp_obj_new_str((char *)buf, len); } -void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char* name) { +void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char *name) { ble_gap_conn_sec_mode_t sec; sec.lv = 0; sec.sm = 0; - sd_ble_gap_device_name_set(&sec, (const uint8_t*) name, strlen(name)); + sd_ble_gap_device_name_set(&sec, (const uint8_t *)name, strlen(name)); } STATIC bool scan_on_ble_evt(ble_evt_t *ble_evt, void *scan_results_in) { - bleio_scanresults_obj_t *scan_results = (bleio_scanresults_obj_t*)scan_results_in; + bleio_scanresults_obj_t *scan_results = (bleio_scanresults_obj_t *)scan_results_in; if (ble_evt->header.evt_id == BLE_GAP_EVT_TIMEOUT && ble_evt->evt.gap_evt.params.timeout.src == BLE_GAP_TIMEOUT_SRC_SCAN) { @@ -435,14 +435,14 @@ STATIC bool scan_on_ble_evt(ble_evt_t *ble_evt, void *scan_results_in) { ble_gap_evt_adv_report_t *report = &ble_evt->evt.gap_evt.params.adv_report; shared_module_bleio_scanresults_append(scan_results, - supervisor_ticks_ms64(), - report->type.connectable, - report->type.scan_response, - report->rssi, - report->peer_addr.addr, - report->peer_addr.addr_type, - report->data.p_data, - report->data.len); + supervisor_ticks_ms64(), + report->type.connectable, + report->type.scan_response, + report->rssi, + report->peer_addr.addr, + report->peer_addr.addr_type, + report->data.p_data, + report->data.len); const uint32_t err_code = sd_ble_gap_scan_start(NULL, scan_results->common_hal_data); if (err_code != NRF_SUCCESS) { @@ -452,7 +452,7 @@ STATIC bool scan_on_ble_evt(ble_evt_t *ble_evt, void *scan_results_in) { return true; } -mp_obj_t common_hal_bleio_adapter_start_scan(bleio_adapter_obj_t *self, uint8_t* prefixes, size_t prefix_length, bool extended, mp_int_t buffer_size, mp_float_t timeout, mp_float_t interval, mp_float_t window, mp_int_t minimum_rssi, bool active) { +mp_obj_t common_hal_bleio_adapter_start_scan(bleio_adapter_obj_t *self, uint8_t *prefixes, size_t prefix_length, bool extended, mp_int_t buffer_size, mp_float_t timeout, mp_float_t interval, mp_float_t window, mp_int_t minimum_rssi, bool active) { if (self->scan_results != NULL) { if (!shared_module_bleio_scanresults_get_done(self->scan_results)) { mp_raise_bleio_BluetoothError(translate("Scan already in progess. Stop with stop_scan.")); @@ -462,7 +462,7 @@ mp_obj_t common_hal_bleio_adapter_start_scan(bleio_adapter_obj_t *self, uint8_t* self->scan_results = shared_module_bleio_new_scanresults(buffer_size, prefixes, prefix_length, minimum_rssi); size_t max_packet_size = extended ? BLE_GAP_SCAN_BUFFER_EXTENDED_MAX_SUPPORTED : BLE_GAP_SCAN_BUFFER_MAX; uint8_t *raw_data = m_malloc(sizeof(ble_data_t) + max_packet_size, false); - ble_data_t * sd_data = (ble_data_t *) raw_data; + ble_data_t *sd_data = (ble_data_t *)raw_data; self->scan_results->common_hal_data = sd_data; sd_data->len = max_packet_size; sd_data->p_data = raw_data + sizeof(ble_data_t); @@ -517,7 +517,7 @@ typedef struct { } connect_info_t; STATIC bool connect_on_ble_evt(ble_evt_t *ble_evt, void *info_in) { - connect_info_t *info = (connect_info_t*)info_in; + connect_info_t *info = (connect_info_t *)info_in; switch (ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: @@ -546,7 +546,7 @@ mp_obj_t common_hal_bleio_adapter_connect(bleio_adapter_obj_t *self, bleio_addre addr.addr_type = address->type; mp_buffer_info_t address_buf_info; mp_get_buffer_raise(address->bytes, &address_buf_info, MP_BUFFER_READ); - memcpy(addr.addr, (uint8_t *) address_buf_info.buf, NUM_BLEIO_ADDRESS_BYTES); + memcpy(addr.addr, (uint8_t *)address_buf_info.buf, NUM_BLEIO_ADDRESS_BYTES); ble_gap_scan_params_t scan_params = { .interval = MSEC_TO_UNITS(100, UNIT_0_625_MS), @@ -621,7 +621,7 @@ STATIC void check_data_fit(size_t data_len, bool connectable) { } STATIC bool advertising_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { - bleio_adapter_obj_t *self = (bleio_adapter_obj_t*)self_in; + bleio_adapter_obj_t *self = (bleio_adapter_obj_t *)self_in; switch (ble_evt->header.evt_id) { case BLE_GAP_EVT_ADV_SET_TERMINATED: @@ -651,7 +651,7 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, uint32_t err_code; bool extended = advertising_data_len > BLE_GAP_ADV_SET_DATA_SIZE_MAX || - scan_response_data_len > BLE_GAP_ADV_SET_DATA_SIZE_MAX; + scan_response_data_len > BLE_GAP_ADV_SET_DATA_SIZE_MAX; uint8_t adv_type; if (extended) { @@ -749,39 +749,39 @@ void common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool uint32_t adv_timeout_max_secs = UNITS_TO_SEC(BLE_GAP_ADV_TIMEOUT_LIMITED_MAX, UNIT_10_MS); uint32_t rotate_timeout_max_secs = BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S; timeout = MIN(adv_timeout_max_secs, rotate_timeout_max_secs); - } - else { + } else { timeout = BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED; } } else { if (SEC_TO_UNITS(timeout, UNIT_10_MS) > BLE_GAP_ADV_TIMEOUT_LIMITED_MAX) { mp_raise_bleio_BluetoothError(translate("Timeout is too long: Maximum timeout length is %d seconds"), - UNITS_TO_SEC(BLE_GAP_ADV_TIMEOUT_LIMITED_MAX, UNIT_10_MS)); + UNITS_TO_SEC(BLE_GAP_ADV_TIMEOUT_LIMITED_MAX, UNIT_10_MS)); } } // The advertising data buffers must not move, because the SoftDevice depends on them. // So make them long-lived and reuse them onwards. if (self->advertising_data == NULL) { - self->advertising_data = (uint8_t *) gc_alloc(BLE_GAP_ADV_SET_DATA_SIZE_EXTENDED_MAX_SUPPORTED * sizeof(uint8_t), false, true); + self->advertising_data = (uint8_t *)gc_alloc(BLE_GAP_ADV_SET_DATA_SIZE_EXTENDED_MAX_SUPPORTED * sizeof(uint8_t), false, true); } if (self->scan_response_data == NULL) { - self->scan_response_data = (uint8_t *) gc_alloc(BLE_GAP_ADV_SET_DATA_SIZE_EXTENDED_MAX_SUPPORTED * sizeof(uint8_t), false, true); + self->scan_response_data = (uint8_t *)gc_alloc(BLE_GAP_ADV_SET_DATA_SIZE_EXTENDED_MAX_SUPPORTED * sizeof(uint8_t), false, true); } memcpy(self->advertising_data, advertising_data_bufinfo->buf, advertising_data_bufinfo->len); memcpy(self->scan_response_data, scan_response_data_bufinfo->buf, scan_response_data_bufinfo->len); check_nrf_error(_common_hal_bleio_adapter_start_advertising(self, connectable, anonymous, timeout, interval, - self->advertising_data, - advertising_data_bufinfo->len, - self->scan_response_data, - scan_response_data_bufinfo->len)); + self->advertising_data, + advertising_data_bufinfo->len, + self->scan_response_data, + scan_response_data_bufinfo->len)); } void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self) { - if (adv_handle == BLE_GAP_ADV_SET_HANDLE_NOT_SET) + if (adv_handle == BLE_GAP_ADV_SET_HANDLE_NOT_SET) { return; + } // TODO: Don't actually stop. Switch to advertising CircuitPython if we don't already have a connection. const uint32_t err_code = sd_ble_gap_adv_stop(adv_handle); @@ -830,12 +830,12 @@ void common_hal_bleio_adapter_erase_bonding(bleio_adapter_obj_t *self) { bonding_erase_storage(); } -void bleio_adapter_gc_collect(bleio_adapter_obj_t* adapter) { - gc_collect_root((void**)adapter, sizeof(bleio_adapter_obj_t) / sizeof(size_t)); - gc_collect_root((void**)bleio_connections, sizeof(bleio_connections) / sizeof(size_t)); +void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter) { + gc_collect_root((void **)adapter, sizeof(bleio_adapter_obj_t) / sizeof(size_t)); + gc_collect_root((void **)bleio_connections, sizeof(bleio_connections) / sizeof(size_t)); } -void bleio_adapter_reset(bleio_adapter_obj_t* adapter) { +void bleio_adapter_reset(bleio_adapter_obj_t *adapter) { common_hal_bleio_adapter_stop_scan(adapter); if (adapter->current_advertising_data != NULL) { common_hal_bleio_adapter_stop_advertising(adapter); diff --git a/ports/nrf/common-hal/_bleio/Adapter.h b/ports/nrf/common-hal/_bleio/Adapter.h index 837e5c111e..68a8b48644 100644 --- a/ports/nrf/common-hal/_bleio/Adapter.h +++ b/ports/nrf/common-hal/_bleio/Adapter.h @@ -43,16 +43,16 @@ extern bleio_connection_internal_t bleio_connections[BLEIO_TOTAL_CONNECTION_COUN typedef struct { mp_obj_base_t base; - uint8_t* advertising_data; - uint8_t* scan_response_data; - uint8_t* current_advertising_data; - bleio_scanresults_obj_t* scan_results; + uint8_t *advertising_data; + uint8_t *scan_response_data; + uint8_t *current_advertising_data; + bleio_scanresults_obj_t *scan_results; mp_obj_t name; mp_obj_tuple_t *connection_objs; ble_drv_evt_handler_entry_t handler_entry; } bleio_adapter_obj_t; -void bleio_adapter_gc_collect(bleio_adapter_obj_t* adapter); -void bleio_adapter_reset(bleio_adapter_obj_t* adapter); +void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter); +void bleio_adapter_reset(bleio_adapter_obj_t *adapter); #endif // MICROPY_INCLUDED_NRF_COMMON_HAL_BLEIO_ADAPTER_H diff --git a/ports/nrf/common-hal/_bleio/Characteristic.c b/ports/nrf/common-hal/_bleio/Characteristic.c index c0f0372c3f..4c5de3124e 100644 --- a/ports/nrf/common-hal/_bleio/Characteristic.c +++ b/ports/nrf/common-hal/_bleio/Characteristic.c @@ -38,7 +38,7 @@ STATIC uint16_t characteristic_get_cccd(uint16_t cccd_handle, uint16_t conn_handle) { uint16_t cccd; ble_gatts_value_t value = { - .p_value = (uint8_t*) &cccd, + .p_value = (uint8_t *)&cccd, .len = 2, }; @@ -96,7 +96,7 @@ void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, const mp_int_t max_length_max = fixed_length ? BLE_GATTS_FIX_ATTR_LEN_MAX : BLE_GATTS_VAR_ATTR_LEN_MAX; if (max_length < 0 || max_length > max_length_max) { mp_raise_ValueError_varg(translate("max_length must be 0-%d when fixed_length is %s"), - max_length_max, fixed_length ? "True" : "False"); + max_length_max, fixed_length ? "True" : "False"); } self->max_length = max_length; self->fixed_length = fixed_length; @@ -116,7 +116,7 @@ bleio_service_obj_t *common_hal_bleio_characteristic_get_service(bleio_character return self->service; } -size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t* buf, size_t len) { +size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t *buf, size_t len) { // Do GATT operations only if this characteristic has been added to a registered service. if (self->handle != BLE_GATT_HANDLE_INVALID) { uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); @@ -139,7 +139,7 @@ void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); // Last argument is true if write-no-reponse desired. common_hal_bleio_gattc_write(self->handle, conn_handle, bufinfo, - (self->props & CHAR_PROP_WRITE_NO_RESPONSE)); + (self->props & CHAR_PROP_WRITE_NO_RESPONSE)); } else { // Validate data length for local characteristics only. if (self->fixed_length && bufinfo->len != self->max_length) { @@ -216,7 +216,7 @@ void common_hal_bleio_characteristic_add_descriptor(bleio_characteristic_obj_t * check_nrf_error(sd_ble_gatts_descriptor_add(self->handle, &desc_attr, &descriptor->handle)); mp_obj_list_append(MP_OBJ_FROM_PTR(self->descriptor_list), - MP_OBJ_FROM_PTR(descriptor)); + MP_OBJ_FROM_PTR(descriptor)); } void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, bool notify, bool indicate) { @@ -238,7 +238,7 @@ void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, ble_gattc_write_params_t write_params = { .write_op = BLE_GATT_OP_WRITE_REQ, .handle = self->cccd_handle, - .p_value = (uint8_t *) &cccd_value, + .p_value = (uint8_t *)&cccd_value, .len = 2, }; diff --git a/ports/nrf/common-hal/_bleio/CharacteristicBuffer.c b/ports/nrf/common-hal/_bleio/CharacteristicBuffer.c index 132e392dd7..b17327da47 100644 --- a/ports/nrf/common-hal/_bleio/CharacteristicBuffer.c +++ b/ports/nrf/common-hal/_bleio/CharacteristicBuffer.c @@ -49,7 +49,7 @@ STATIC void write_to_ringbuf(bleio_characteristic_buffer_obj_t *self, uint8_t *d } STATIC bool characteristic_buffer_on_ble_evt(ble_evt_t *ble_evt, void *param) { - bleio_characteristic_buffer_obj_t *self = (bleio_characteristic_buffer_obj_t *) param; + bleio_characteristic_buffer_obj_t *self = (bleio_characteristic_buffer_obj_t *)param; switch (ble_evt->header.evt_id) { case BLE_GATTS_EVT_WRITE: { // A client wrote to this server characteristic. @@ -65,7 +65,7 @@ STATIC bool characteristic_buffer_on_ble_evt(ble_evt_t *ble_evt, void *param) { case BLE_GATTC_EVT_HVX: { // A remote service wrote to this characteristic. - ble_gattc_evt_hvx_t* evt_hvx = &ble_evt->evt.gattc_evt.params.hvx; + ble_gattc_evt_hvx_t *evt_hvx = &ble_evt->evt.gattc_evt.params.hvx; // Must be a notification, and event handle must match the handle for my characteristic. if (evt_hvx->type == BLE_GATT_HVX_NOTIFICATION && evt_hvx->handle == self->characteristic->handle) { @@ -82,9 +82,9 @@ STATIC bool characteristic_buffer_on_ble_evt(ble_evt_t *ble_evt, void *param) { // Assumes that timeout and buffer_size have been validated before call. void common_hal_bleio_characteristic_buffer_construct(bleio_characteristic_buffer_obj_t *self, - bleio_characteristic_obj_t *characteristic, - mp_float_t timeout, - size_t buffer_size) { + bleio_characteristic_obj_t *characteristic, + mp_float_t timeout, + size_t buffer_size) { self->characteristic = characteristic; self->timeout_ms = timeout * 1000; @@ -100,10 +100,10 @@ uint32_t common_hal_bleio_characteristic_buffer_read(bleio_characteristic_buffer uint64_t start_ticks = supervisor_ticks_ms64(); // Wait for all bytes received or timeout - while ( (ringbuf_num_filled(&self->ringbuf) < len) && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms) ) { + while ((ringbuf_num_filled(&self->ringbuf) < len) && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms)) { RUN_BACKGROUND_TASKS; // Allow user to break out of a timeout with a KeyboardInterrupt. - if ( mp_hal_is_interrupted() ) { + if (mp_hal_is_interrupted()) { return 0; } } @@ -148,8 +148,8 @@ void common_hal_bleio_characteristic_buffer_deinit(bleio_characteristic_buffer_o bool common_hal_bleio_characteristic_buffer_connected(bleio_characteristic_buffer_obj_t *self) { return self->characteristic != NULL && - self->characteristic->service != NULL && - (!self->characteristic->service->is_remote || - (self->characteristic->service->connection != MP_OBJ_NULL && - common_hal_bleio_connection_get_connected(self->characteristic->service->connection))); + self->characteristic->service != NULL && + (!self->characteristic->service->is_remote || + (self->characteristic->service->connection != MP_OBJ_NULL && + common_hal_bleio_connection_get_connected(self->characteristic->service->connection))); } diff --git a/ports/nrf/common-hal/_bleio/Connection.c b/ports/nrf/common-hal/_bleio/Connection.c index 36fda0bb35..f57ee639a5 100644 --- a/ports/nrf/common-hal/_bleio/Connection.c +++ b/ports/nrf/common-hal/_bleio/Connection.c @@ -63,8 +63,8 @@ static const ble_gap_sec_params_t pairing_sec_params = { .io_caps = BLE_GAP_IO_CAPS_NONE, .min_key_size = 7, .max_key_size = 16, - .kdist_own = { .enc = 1, .id = 1}, - .kdist_peer = { .enc = 1, .id = 1}, + .kdist_own = { .enc = 1, .id = 1}, + .kdist_peer = { .enc = 1, .id = 1}, }; #define CONNECTION_DEBUG (1) @@ -81,7 +81,7 @@ static bleio_service_obj_t *m_char_discovery_service; static bleio_characteristic_obj_t *m_desc_discovery_characteristic; bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { - bleio_connection_internal_t *self = (bleio_connection_internal_t*)self_in; + bleio_connection_internal_t *self = (bleio_connection_internal_t *)self_in; if (BLE_GAP_EVT_BASE <= ble_evt->header.evt_id && ble_evt->header.evt_id <= BLE_GAP_EVT_LAST && ble_evt->evt.gap_evt.conn_handle != self->conn_handle) { @@ -121,7 +121,7 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { case BLE_GATTS_EVT_EXCHANGE_MTU_REQUEST: { ble_gatts_evt_exchange_mtu_request_t *request = - &ble_evt->evt.gatts_evt.params.exchange_mtu_request; + &ble_evt->evt.gatts_evt.params.exchange_mtu_request; uint16_t new_mtu = BLE_GATTS_VAR_ATTR_LEN_MAX; if (request->client_rx_mtu < new_mtu) { @@ -142,7 +142,7 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { case BLE_GATTC_EVT_EXCHANGE_MTU_RSP: { ble_gattc_evt_exchange_mtu_rsp_t *response = - &ble_evt->evt.gattc_evt.params.exchange_mtu_rsp; + &ble_evt->evt.gattc_evt.params.exchange_mtu_rsp; self->mtu = response->server_rx_mtu; break; @@ -169,12 +169,12 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { sd_ble_gatts_sys_attr_set(self->conn_handle, NULL, 0, 0); break; - #if CIRCUITPY_VERBOSE_BLE + #if CIRCUITPY_VERBOSE_BLE // Use read authorization to snoop on all reads when doing verbose debugging. case BLE_GATTS_EVT_RW_AUTHORIZE_REQUEST: { ble_gatts_evt_rw_authorize_request_t *request = - &ble_evt->evt.gatts_evt.params.authorize_request; + &ble_evt->evt.gatts_evt.params.authorize_request; mp_printf(&mp_plat_print, "Read %x offset %d ", request->request.read.handle, request->request.read.offset); uint8_t value_bytes[22]; @@ -200,20 +200,20 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { sd_ble_gatts_rw_authorize_reply(self->conn_handle, &reply); break; } - #endif + #endif case BLE_GATTS_EVT_HVN_TX_COMPLETE: // Capture this for now. 0x55 break; case BLE_GAP_EVT_CONN_PARAM_UPDATE_REQUEST: { self->conn_params_updating = true; ble_gap_evt_conn_param_update_request_t *request = - &ble_evt->evt.gap_evt.params.conn_param_update_request; + &ble_evt->evt.gap_evt.params.conn_param_update_request; sd_ble_gap_conn_param_update(self->conn_handle, &request->conn_params); break; } case BLE_GAP_EVT_CONN_PARAM_UPDATE: { // 0x12 ble_gap_evt_conn_param_update_t *result = - &ble_evt->evt.gap_evt.params.conn_param_update; + &ble_evt->evt.gap_evt.params.conn_param_update; #if CIRCUITPY_VERBOSE_BLE ble_gap_conn_params_t *cp = &ble_evt->evt.gap_evt.params.conn_param_update.conn_params; @@ -236,23 +236,23 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { self->ediv = EDIV_INVALID; ble_gap_sec_keyset_t keyset = { .keys_own = { - .p_enc_key = &self->bonding_keys.own_enc, - .p_id_key = NULL, + .p_enc_key = &self->bonding_keys.own_enc, + .p_id_key = NULL, .p_sign_key = NULL, - .p_pk = NULL + .p_pk = NULL }, .keys_peer = { - .p_enc_key = &self->bonding_keys.peer_enc, - .p_id_key = &self->bonding_keys.peer_id, + .p_enc_key = &self->bonding_keys.peer_enc, + .p_id_key = &self->bonding_keys.peer_id, .p_sign_key = NULL, - .p_pk = NULL + .p_pk = NULL } }; sd_ble_gap_sec_params_reply(self->conn_handle, BLE_GAP_SEC_STATUS_SUCCESS, - self->is_central ? NULL : &pairing_sec_params, - &keyset); + self->is_central ? NULL : &pairing_sec_params, + &keyset); break; } @@ -263,7 +263,7 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { case BLE_GAP_EVT_AUTH_STATUS: { // 0x19 // Key exchange completed. - ble_gap_evt_auth_status_t* status = &ble_evt->evt.gap_evt.params.auth_status; + ble_gap_evt_auth_status_t *status = &ble_evt->evt.gap_evt.params.auth_status; self->sec_status = status->auth_status; if (status->auth_status == BLE_GAP_SEC_STATUS_SUCCESS) { self->ediv = self->bonding_keys.own_enc.master_id.ediv; @@ -281,9 +281,9 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { // Peer asks for the stored keys. // - load key and return if bonded previously. // - Else return NULL --> Initiate key exchange - ble_gap_evt_sec_info_request_t* sec_info_request = &ble_evt->evt.gap_evt.params.sec_info_request; - (void) sec_info_request; - if ( bonding_load_keys(self->is_central, sec_info_request->master_id.ediv, &self->bonding_keys) ) { + ble_gap_evt_sec_info_request_t *sec_info_request = &ble_evt->evt.gap_evt.params.sec_info_request; + (void)sec_info_request; + if (bonding_load_keys(self->is_central, sec_info_request->master_id.ediv, &self->bonding_keys)) { sd_ble_gap_sec_info_reply( self->conn_handle, &self->bonding_keys.own_enc.enc_info, @@ -299,7 +299,7 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { case BLE_GAP_EVT_CONN_SEC_UPDATE: { // 0x1a // We get this both on first-time pairing and on subsequent pairings using stored keys. - ble_gap_conn_sec_t* conn_sec = &ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec; + ble_gap_conn_sec_t *conn_sec = &ble_evt->evt.gap_evt.params.conn_sec_update.conn_sec; if (conn_sec->sec_mode.sm <= 1 && conn_sec->sec_mode.lv <= 1) { // Security setup did not succeed: // mode 0, level 0 means no access @@ -391,7 +391,7 @@ void common_hal_bleio_connection_set_connection_interval(bleio_connection_intern } // service_uuid may be NULL, to discover all services. -STATIC bool discover_next_services(bleio_connection_internal_t* connection, uint16_t start_handle, ble_uuid_t *service_uuid) { +STATIC bool discover_next_services(bleio_connection_internal_t *connection, uint16_t start_handle, ble_uuid_t *service_uuid) { m_discovery_successful = false; m_discovery_in_process = true; @@ -408,7 +408,7 @@ STATIC bool discover_next_services(bleio_connection_internal_t* connection, uint return m_discovery_successful; } -STATIC bool discover_next_characteristics(bleio_connection_internal_t* connection, bleio_service_obj_t *service, uint16_t start_handle) { +STATIC bool discover_next_characteristics(bleio_connection_internal_t *connection, bleio_service_obj_t *service, uint16_t start_handle) { m_char_discovery_service = service; ble_gattc_handle_range_t handle_range; @@ -430,7 +430,7 @@ STATIC bool discover_next_characteristics(bleio_connection_internal_t* connectio return m_discovery_successful; } -STATIC bool discover_next_descriptors(bleio_connection_internal_t* connection, bleio_characteristic_obj_t *characteristic, uint16_t start_handle, uint16_t end_handle) { +STATIC bool discover_next_descriptors(bleio_connection_internal_t *connection, bleio_characteristic_obj_t *characteristic, uint16_t start_handle, uint16_t end_handle) { m_desc_discovery_characteristic = characteristic; ble_gattc_handle_range_t handle_range; @@ -452,7 +452,7 @@ STATIC bool discover_next_descriptors(bleio_connection_internal_t* connection, b return m_discovery_successful; } -STATIC void on_primary_srv_discovery_rsp(ble_gattc_evt_prim_srvc_disc_rsp_t *response, bleio_connection_internal_t* connection) { +STATIC void on_primary_srv_discovery_rsp(ble_gattc_evt_prim_srvc_disc_rsp_t *response, bleio_connection_internal_t *connection) { for (size_t i = 0; i < response->count; ++i) { ble_gattc_service_t *gattc_service = &response->services[i]; @@ -481,7 +481,7 @@ STATIC void on_primary_srv_discovery_rsp(ble_gattc_evt_prim_srvc_disc_rsp_t *res } mp_obj_list_append(MP_OBJ_FROM_PTR(connection->remote_service_list), - MP_OBJ_FROM_PTR(service)); + MP_OBJ_FROM_PTR(service)); } if (response->count > 0) { @@ -490,7 +490,7 @@ STATIC void on_primary_srv_discovery_rsp(ble_gattc_evt_prim_srvc_disc_rsp_t *res m_discovery_in_process = false; } -STATIC void on_char_discovery_rsp(ble_gattc_evt_char_disc_rsp_t *response, bleio_connection_internal_t* connection) { +STATIC void on_char_discovery_rsp(ble_gattc_evt_char_disc_rsp_t *response, bleio_connection_internal_t *connection) { for (size_t i = 0; i < response->count; ++i) { ble_gattc_char_t *gattc_char = &response->chars[i]; @@ -526,7 +526,7 @@ STATIC void on_char_discovery_rsp(ble_gattc_evt_char_disc_rsp_t *response, bleio mp_const_empty_bytes); mp_obj_list_append(MP_OBJ_FROM_PTR(m_char_discovery_service->characteristic_list), - MP_OBJ_FROM_PTR(characteristic)); + MP_OBJ_FROM_PTR(characteristic)); } if (response->count > 0) { @@ -535,7 +535,7 @@ STATIC void on_char_discovery_rsp(ble_gattc_evt_char_disc_rsp_t *response, bleio m_discovery_in_process = false; } -STATIC void on_desc_discovery_rsp(ble_gattc_evt_desc_disc_rsp_t *response, bleio_connection_internal_t* connection) { +STATIC void on_desc_discovery_rsp(ble_gattc_evt_desc_disc_rsp_t *response, bleio_connection_internal_t *connection) { for (size_t i = 0; i < response->count; ++i) { ble_gattc_desc_t *gattc_desc = &response->descs[i]; @@ -583,7 +583,7 @@ STATIC void on_desc_discovery_rsp(ble_gattc_evt_desc_disc_rsp_t *response, bleio descriptor->handle = gattc_desc->handle; mp_obj_list_append(MP_OBJ_FROM_PTR(m_desc_discovery_characteristic->descriptor_list), - MP_OBJ_FROM_PTR(descriptor)); + MP_OBJ_FROM_PTR(descriptor)); } if (response->count > 0) { @@ -593,7 +593,7 @@ STATIC void on_desc_discovery_rsp(ble_gattc_evt_desc_disc_rsp_t *response, bleio } STATIC bool discovery_on_ble_evt(ble_evt_t *ble_evt, mp_obj_t payload) { - bleio_connection_internal_t* connection = MP_OBJ_TO_PTR(payload); + bleio_connection_internal_t *connection = MP_OBJ_TO_PTR(payload); switch (ble_evt->header.evt_id) { case BLE_GAP_EVT_DISCONNECTED: m_discovery_successful = false; @@ -714,7 +714,7 @@ STATIC void discover_remote_services(bleio_connection_internal_t *self, mp_obj_t while (next_desc_start_handle <= service->end_handle && next_desc_start_handle <= next_desc_end_handle && discover_next_descriptors(self, characteristic, - next_desc_start_handle, next_desc_end_handle)) { + next_desc_start_handle, next_desc_end_handle)) { // Get the most recently discovered descriptor, and then ask for descriptors // whose handles start after that descriptor's handle. // There must be at least one if discover_next_descriptors() returned true. @@ -735,7 +735,7 @@ mp_obj_tuple_t *common_hal_bleio_connection_discover_remote_services(bleio_conne // Convert to a tuple and then clear the list so the callee will take ownership. mp_obj_tuple_t *services_tuple = mp_obj_new_tuple(self->connection->remote_service_list->len, - self->connection->remote_service_list->items); + self->connection->remote_service_list->items); mp_obj_list_clear(MP_OBJ_FROM_PTR(self->connection->remote_service_list)); return services_tuple; @@ -748,7 +748,7 @@ uint16_t bleio_connection_get_conn_handle(bleio_connection_obj_t *self) { return self->connection->conn_handle; } -mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t* internal) { +mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t *internal) { if (internal->connection_obj != mp_const_none) { return internal->connection_obj; } diff --git a/ports/nrf/common-hal/_bleio/Connection.h b/ports/nrf/common-hal/_bleio/Connection.h index 180b2727ca..eb095c993a 100644 --- a/ports/nrf/common-hal/_bleio/Connection.h +++ b/ports/nrf/common-hal/_bleio/Connection.h @@ -78,7 +78,7 @@ typedef struct { typedef struct { mp_obj_base_t base; - bleio_connection_internal_t* connection; + bleio_connection_internal_t *connection; // The HCI disconnect reason. uint8_t disconnect_reason; } bleio_connection_obj_t; @@ -87,7 +87,7 @@ void bleio_connection_clear(bleio_connection_internal_t *self); bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in); uint16_t bleio_connection_get_conn_handle(bleio_connection_obj_t *self); -mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t* connection); +mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t *connection); bleio_connection_internal_t *bleio_conn_handle_to_connection(uint16_t conn_handle); #endif // MICROPY_INCLUDED_NRF_COMMON_HAL_BLEIO_CONNECTION_H diff --git a/ports/nrf/common-hal/_bleio/Descriptor.c b/ports/nrf/common-hal/_bleio/Descriptor.c index d848659fce..7ec287260b 100644 --- a/ports/nrf/common-hal/_bleio/Descriptor.c +++ b/ports/nrf/common-hal/_bleio/Descriptor.c @@ -44,7 +44,7 @@ void common_hal_bleio_descriptor_construct(bleio_descriptor_obj_t *self, bleio_c const mp_int_t max_length_max = fixed_length ? BLE_GATTS_FIX_ATTR_LEN_MAX : BLE_GATTS_VAR_ATTR_LEN_MAX; if (max_length < 0 || max_length > max_length_max) { mp_raise_ValueError_varg(translate("max_length must be 0-%d when fixed_length is %s"), - max_length_max, fixed_length ? "True" : "False"); + max_length_max, fixed_length ? "True" : "False"); } self->max_length = max_length; self->fixed_length = fixed_length; @@ -58,7 +58,7 @@ bleio_characteristic_obj_t *common_hal_bleio_descriptor_get_characteristic(bleio return self->characteristic; } -size_t common_hal_bleio_descriptor_get_value(bleio_descriptor_obj_t *self, uint8_t* buf, size_t len) { +size_t common_hal_bleio_descriptor_get_value(bleio_descriptor_obj_t *self, uint8_t *buf, size_t len) { // Do GATT operations only if this descriptor has been registered if (self->handle != BLE_GATT_HANDLE_INVALID) { uint16_t conn_handle = bleio_connection_get_conn_handle(self->characteristic->service->connection); diff --git a/ports/nrf/common-hal/_bleio/PacketBuffer.c b/ports/nrf/common-hal/_bleio/PacketBuffer.c index 6d587984ca..8f87b24972 100644 --- a/ports/nrf/common-hal/_bleio/PacketBuffer.c +++ b/ports/nrf/common-hal/_bleio/PacketBuffer.c @@ -51,13 +51,13 @@ STATIC void write_to_ringbuf(bleio_packet_buffer_obj_t *self, uint8_t *data, uin // Make room for the new value by dropping the oldest packets first. while (ringbuf_capacity(&self->ringbuf) - ringbuf_num_filled(&self->ringbuf) < len + sizeof(uint16_t)) { uint16_t packet_length; - ringbuf_get_n(&self->ringbuf, (uint8_t*) &packet_length, sizeof(uint16_t)); + ringbuf_get_n(&self->ringbuf, (uint8_t *)&packet_length, sizeof(uint16_t)); for (uint16_t i = 0; i < packet_length; i++) { ringbuf_get(&self->ringbuf); } // set an overflow flag? } - ringbuf_put_n(&self->ringbuf, (uint8_t*) &len, sizeof(uint16_t)); + ringbuf_put_n(&self->ringbuf, (uint8_t *)&len, sizeof(uint16_t)); ringbuf_put_n(&self->ringbuf, data, len); sd_nvic_critical_region_exit(is_nested_critical_region); } @@ -112,14 +112,14 @@ STATIC bool packet_buffer_on_ble_client_evt(ble_evt_t *ble_evt, void *param) { } uint16_t conn_handle = ble_evt->evt.gattc_evt.conn_handle; - bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *) param; + bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *)param; if (conn_handle != self->conn_handle) { return false; } switch (evt_id) { case BLE_GATTC_EVT_HVX: { // A remote service wrote to this characteristic. - ble_gattc_evt_hvx_t* evt_hvx = &ble_evt->evt.gattc_evt.params.hvx; + ble_gattc_evt_hvx_t *evt_hvx = &ble_evt->evt.gattc_evt.params.hvx; // Must be a notification, and event handle must match the handle for my characteristic. if (evt_hvx->handle == self->characteristic->handle) { write_to_ringbuf(self, evt_hvx->data, evt_hvx->len); @@ -143,7 +143,7 @@ STATIC bool packet_buffer_on_ble_client_evt(ble_evt_t *ble_evt, void *param) { } STATIC bool packet_buffer_on_ble_server_evt(ble_evt_t *ble_evt, void *param) { - bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *) param; + bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *)param; switch (ble_evt->header.evt_id) { case BLE_GATTS_EVT_WRITE: { uint16_t conn_handle = ble_evt->evt.gatts_evt.conn_handle; @@ -160,7 +160,7 @@ STATIC bool packet_buffer_on_ble_server_evt(ble_evt_t *ble_evt, void *param) { } write_to_ringbuf(self, evt_write->data, evt_write->len); } else if (evt_write->handle == self->characteristic->cccd_handle) { - uint16_t cccd = *((uint16_t*) evt_write->data); + uint16_t cccd = *((uint16_t *)evt_write->data); if (cccd & BLE_GATT_HVX_NOTIFICATION) { self->conn_handle = conn_handle; } else { @@ -185,8 +185,8 @@ STATIC bool packet_buffer_on_ble_server_evt(ble_evt_t *ble_evt, void *param) { } void common_hal_bleio_packet_buffer_construct( - bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, - size_t buffer_size) { + bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, + size_t buffer_size) { self->characteristic = characteristic; self->client = self->characteristic->service->is_remote; @@ -259,7 +259,7 @@ mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self // Get packet length, which is in first two bytes of packet. uint16_t packet_length; - ringbuf_get_n(&self->ringbuf, (uint8_t*) &packet_length, sizeof(uint16_t)); + ringbuf_get_n(&self->ringbuf, (uint8_t *)&packet_length, sizeof(uint16_t)); mp_int_t ret; if (packet_length > len) { @@ -267,7 +267,7 @@ mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self ret = len - packet_length; // Discard the packet if it's too large. Don't fill data. while (packet_length--) { - (void) ringbuf_get(&self->ringbuf); + (void)ringbuf_get(&self->ringbuf); } } else { // Read as much as possible, but might be shorter than len. @@ -281,7 +281,7 @@ mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self return ret; } -mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len, uint8_t* header, size_t header_len) { +mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len, uint8_t *header, size_t header_len) { if (self->outgoing[0] == NULL) { mp_raise_bleio_BluetoothError(translate("Writes not supported on Characteristic")); } @@ -311,7 +311,7 @@ mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, u uint8_t is_nested_critical_region; sd_nvic_critical_region_enter(&is_nested_critical_region); - uint8_t* pending = self->outgoing[self->pending_index]; + uint8_t *pending = self->outgoing[self->pending_index]; if (self->pending_size == 0) { memcpy(pending, header, header_len); @@ -352,7 +352,7 @@ mp_int_t common_hal_bleio_packet_buffer_get_incoming_packet_length(bleio_packet_ bleio_connection_internal_t *connection = bleio_conn_handle_to_connection(self->conn_handle); if (connection) { return MIN(common_hal_bleio_connection_get_max_packet_length(connection), - self->characteristic->max_length); + self->characteristic->max_length); } } // There's no current connection, so we don't know the MTU, and @@ -383,7 +383,7 @@ mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_ bleio_connection_internal_t *connection = bleio_conn_handle_to_connection(self->conn_handle); if (connection) { return MIN(common_hal_bleio_connection_get_max_packet_length(connection), - self->characteristic->max_length); + self->characteristic->max_length); } } // There's no current connection, so we don't know the MTU, and diff --git a/ports/nrf/common-hal/_bleio/PacketBuffer.h b/ports/nrf/common-hal/_bleio/PacketBuffer.h index 699291749f..94e0f11d80 100644 --- a/ports/nrf/common-hal/_bleio/PacketBuffer.h +++ b/ports/nrf/common-hal/_bleio/PacketBuffer.h @@ -39,7 +39,7 @@ typedef struct { ringbuf_t ringbuf; // Two outgoing buffers to alternate between. One will be queued for transmission by the SD and // the other is waiting to be queued and can be extended. - uint8_t* outgoing[2]; + uint8_t *outgoing[2]; volatile uint16_t pending_size; // We remember the conn_handle so we can do a NOTIFY/INDICATE to a client. // We can find out the conn_handle on a Characteristic write or a CCCD write (but not a read). diff --git a/ports/nrf/common-hal/_bleio/Service.c b/ports/nrf/common-hal/_bleio/Service.c index 3159d3392f..74e74fac9f 100644 --- a/ports/nrf/common-hal/_bleio/Service.c +++ b/ports/nrf/common-hal/_bleio/Service.c @@ -34,7 +34,7 @@ #include "shared-bindings/_bleio/Service.h" #include "shared-bindings/_bleio/Adapter.h" -uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary, mp_obj_list_t * characteristic_list) { +uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary, mp_obj_list_t *characteristic_list) { self->handle = 0xFFFF; self->uuid = uuid; self->characteristic_list = characteristic_list; @@ -57,7 +57,7 @@ uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uu void common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary) { check_nrf_error(_common_hal_bleio_service_construct(self, uuid, is_secondary, - mp_obj_new_list(0, NULL))); + mp_obj_new_list(0, NULL))); } void bleio_service_from_connection(bleio_service_obj_t *self, mp_obj_t connection) { @@ -86,15 +86,15 @@ bool common_hal_bleio_service_get_is_secondary(bleio_service_obj_t *self) { } void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, - bleio_characteristic_obj_t *characteristic, - mp_buffer_info_t *initial_value_bufinfo) { + bleio_characteristic_obj_t *characteristic, + mp_buffer_info_t *initial_value_bufinfo) { ble_gatts_char_md_t char_md = { - .char_props.broadcast = (characteristic->props & CHAR_PROP_BROADCAST) ? 1 : 0, - .char_props.read = (characteristic->props & CHAR_PROP_READ) ? 1 : 0, - .char_props.write_wo_resp = (characteristic->props & CHAR_PROP_WRITE_NO_RESPONSE) ? 1 : 0, - .char_props.write = (characteristic->props & CHAR_PROP_WRITE) ? 1 : 0, - .char_props.notify = (characteristic->props & CHAR_PROP_NOTIFY) ? 1 : 0, - .char_props.indicate = (characteristic->props & CHAR_PROP_INDICATE) ? 1 : 0, + .char_props.broadcast = (characteristic->props & CHAR_PROP_BROADCAST) ? 1 : 0, + .char_props.read = (characteristic->props & CHAR_PROP_READ) ? 1 : 0, + .char_props.write_wo_resp = (characteristic->props & CHAR_PROP_WRITE_NO_RESPONSE) ? 1 : 0, + .char_props.write = (characteristic->props & CHAR_PROP_WRITE) ? 1 : 0, + .char_props.notify = (characteristic->props & CHAR_PROP_NOTIFY) ? 1 : 0, + .char_props.indicate = (characteristic->props & CHAR_PROP_INDICATE) ? 1 : 0, }; ble_gatts_attr_md_t cccd_md = { diff --git a/ports/nrf/common-hal/_bleio/UUID.c b/ports/nrf/common-hal/_bleio/UUID.c index 0c79e980ee..399bf23ed2 100644 --- a/ports/nrf/common-hal/_bleio/UUID.c +++ b/ports/nrf/common-hal/_bleio/UUID.c @@ -67,7 +67,7 @@ void common_hal_bleio_uuid_get_uuid128(bleio_uuid_obj_t *self, uint8_t uuid128[1 check_nrf_error(sd_ble_uuid_encode(&self->nrf_ble_uuid, &length, uuid128)); } -void common_hal_bleio_uuid_pack_into(bleio_uuid_obj_t *self, uint8_t* buf) { +void common_hal_bleio_uuid_pack_into(bleio_uuid_obj_t *self, uint8_t *buf) { if (self->nrf_ble_uuid.type == BLE_UUID_TYPE_BLE) { buf[0] = self->nrf_ble_uuid.uuid & 0xff; buf[1] = self->nrf_ble_uuid.uuid >> 8; diff --git a/ports/nrf/common-hal/_bleio/__init__.c b/ports/nrf/common-hal/_bleio/__init__.c index 5293f7ad14..7248f83150 100644 --- a/ports/nrf/common-hal/_bleio/__init__.c +++ b/ports/nrf/common-hal/_bleio/__init__.c @@ -120,7 +120,7 @@ void common_hal_bleio_check_connected(uint16_t conn_handle) { } // GATTS read of a Characteristic or Descriptor. -size_t common_hal_bleio_gatts_read(uint16_t handle, uint16_t conn_handle, uint8_t* buf, size_t len) { +size_t common_hal_bleio_gatts_read(uint16_t handle, uint16_t conn_handle, uint8_t *buf, size_t len) { // conn_handle is ignored unless this is a system attribute. // If we're not connected, that's OK, because we can still read and write the local value. @@ -147,7 +147,7 @@ void common_hal_bleio_gatts_write(uint16_t handle, uint16_t conn_handle, mp_buff } typedef struct { - uint8_t* buf; + uint8_t *buf; size_t len; size_t final_len; uint16_t conn_handle; @@ -156,13 +156,13 @@ typedef struct { } read_info_t; STATIC bool _on_gattc_read_rsp_evt(ble_evt_t *ble_evt, void *param) { - read_info_t* read = param; + read_info_t *read = param; switch (ble_evt->header.evt_id) { // More events may be handled later, so keep this as a switch. case BLE_GATTC_EVT_READ_RSP: { - ble_gattc_evt_t* evt = &ble_evt->evt.gattc_evt; + ble_gattc_evt_t *evt = &ble_evt->evt.gattc_evt; ble_gattc_evt_read_rsp_t *response = &evt->params.read_rsp; if (read && evt->conn_handle == read->conn_handle) { read->status = evt->gatt_status; @@ -184,7 +184,7 @@ STATIC bool _on_gattc_read_rsp_evt(ble_evt_t *ble_evt, void *param) { return true; } -size_t common_hal_bleio_gattc_read(uint16_t handle, uint16_t conn_handle, uint8_t* buf, size_t len) { +size_t common_hal_bleio_gattc_read(uint16_t handle, uint16_t conn_handle, uint8_t *buf, size_t len) { common_hal_bleio_check_connected(conn_handle); read_info_t read_info; diff --git a/ports/nrf/common-hal/_bleio/bonding.c b/ports/nrf/common-hal/_bleio/bonding.c index 081ba992f3..0c39bfe423 100644 --- a/ports/nrf/common-hal/_bleio/bonding.c +++ b/ports/nrf/common-hal/_bleio/bonding.c @@ -59,12 +59,12 @@ const uint32_t BONDING_FLAG = ('1' | '0' << 8 | 'D' << 16 | 'B' << 24); #if BONDING_DEBUG void bonding_print_block(bonding_block_t *block) { printf("at 0x%08lx: is_central: %1d, type: 0x%x, ediv: 0x%04x, data_length: %d\n", - (uint32_t) block, block->is_central, block->type, block->ediv, block->data_length); + (uint32_t)block, block->is_central, block->type, block->ediv, block->data_length); } void bonding_print_keys(bonding_keys_t *keys) { - for (size_t i = 0; i < sizeof(bonding_keys_t); i ++) { - printf("%x", ((uint8_t*) keys)[i]); + for (size_t i = 0; i < sizeof(bonding_keys_t); i++) { + printf("%x", ((uint8_t *)keys)[i]); } printf("\n"); } @@ -77,16 +77,16 @@ STATIC size_t compute_block_size(uint16_t data_length) { void bonding_erase_storage(void) { // Erase all pages in the bonding area. - for(uint32_t page_address = BONDING_PAGES_START_ADDR; - page_address < BONDING_PAGES_END_ADDR; - page_address += FLASH_PAGE_SIZE) { + for (uint32_t page_address = BONDING_PAGES_START_ADDR; + page_address < BONDING_PAGES_END_ADDR; + page_address += FLASH_PAGE_SIZE) { // Argument is page number, not address. sd_flash_page_erase_sync(page_address / FLASH_PAGE_SIZE); } // Write marker words at the beginning and the end of the bonding area. uint32_t flag = BONDING_FLAG; - sd_flash_write_sync((uint32_t *) BONDING_START_FLAG_ADDR, &flag, 1); - sd_flash_write_sync((uint32_t *) BONDING_END_FLAG_ADDR, &flag, 1); + sd_flash_write_sync((uint32_t *)BONDING_START_FLAG_ADDR, &flag, 1); + sd_flash_write_sync((uint32_t *)BONDING_END_FLAG_ADDR, &flag, 1); } // Given NULL to start or block address, return the address of the next valid block. @@ -97,16 +97,16 @@ STATIC bonding_block_t *next_block(bonding_block_t *block) { while (1) { // Advance to next block. if (block == NULL) { - return (bonding_block_t *) BONDING_DATA_START_ADDR; + return (bonding_block_t *)BONDING_DATA_START_ADDR; } else if (block->type == BLOCK_UNUSED) { // Already at last block (the unused block). return NULL; } // Advance to next block. - block = (bonding_block_t *) ((uint8_t *) block + compute_block_size(block->data_length)); + block = (bonding_block_t *)((uint8_t *)block + compute_block_size(block->data_length)); - if (block >= (bonding_block_t *) BONDING_DATA_END_ADDR) { + if (block >= (bonding_block_t *)BONDING_DATA_END_ADDR) { // Went past end of bonding space. return NULL; } @@ -133,20 +133,20 @@ STATIC bonding_block_t *find_existing_block(bool is_central, bonding_block_type_ if (type == block->type) { if (type == BLOCK_UNUSED || (is_central == block->is_central && ediv == block->ediv)) { - return block; + return block; } } } } // Get an empty block large enough to store data_length data. -STATIC bonding_block_t* find_unused_block(uint16_t data_length) { +STATIC bonding_block_t *find_unused_block(uint16_t data_length) { bonding_block_t *unused_block = find_existing_block(true, BLOCK_UNUSED, EDIV_INVALID); // If no more room, erase all existing blocks and start over. if (!unused_block || - (uint8_t *) unused_block + compute_block_size(data_length) >= (uint8_t *) BONDING_DATA_END_ADDR) { + (uint8_t *)unused_block + compute_block_size(data_length) >= (uint8_t *)BONDING_DATA_END_ADDR) { bonding_erase_storage(); - unused_block = (bonding_block_t *) BONDING_DATA_START_ADDR; + unused_block = (bonding_block_t *)BONDING_DATA_START_ADDR; } return unused_block; } @@ -155,12 +155,12 @@ STATIC bonding_block_t* find_unused_block(uint16_t data_length) { // We don't change data_length, so we can still skip over this block. STATIC void invalidate_block(bonding_block_t *block) { uint32_t zero = 0; - sd_flash_write_sync((uint32_t *) block, &zero, 1); + sd_flash_write_sync((uint32_t *)block, &zero, 1); } // Write bonding block header. STATIC void write_block_header(bonding_block_t *dest_block, bonding_block_t *source_block_header) { - sd_flash_write_sync((uint32_t *) dest_block, (uint32_t *) source_block_header, sizeof(bonding_block_t) / 4); + sd_flash_write_sync((uint32_t *)dest_block, (uint32_t *)source_block_header, sizeof(bonding_block_t) / 4); } // Write variable-length data at end of bonding block. @@ -168,7 +168,7 @@ STATIC void write_block_data(bonding_block_t *dest_block, uint8_t *data, uint16_ // Minimize the number of writes. Datasheet says no more than two writes per word before erasing again. // Start writing after the current header. - uint32_t *flash_word_p = (uint32_t *) ((uint8_t *) dest_block + sizeof(bonding_block_t)); + uint32_t *flash_word_p = (uint32_t *)((uint8_t *)dest_block + sizeof(bonding_block_t)); while (1) { uint32_t word = 0xffffffff; memcpy(&word, data, data_length >= 4 ? 4 : data_length); @@ -186,11 +186,11 @@ STATIC void write_block_data(bonding_block_t *dest_block, uint8_t *data, uint16_ STATIC void write_sys_attr_block(bleio_connection_internal_t *connection) { uint16_t length = 0; // First find out how big a buffer we need, then fetch the data. - if(sd_ble_gatts_sys_attr_get(connection->conn_handle, NULL, &length, SYS_ATTR_FLAGS) != NRF_SUCCESS) { + if (sd_ble_gatts_sys_attr_get(connection->conn_handle, NULL, &length, SYS_ATTR_FLAGS) != NRF_SUCCESS) { return; } uint8_t sys_attr[length]; - if(sd_ble_gatts_sys_attr_get(connection->conn_handle, sys_attr, &length, SYS_ATTR_FLAGS) != NRF_SUCCESS) { + if (sd_ble_gatts_sys_attr_get(connection->conn_handle, sys_attr, &length, SYS_ATTR_FLAGS) != NRF_SUCCESS) { return; } @@ -246,16 +246,16 @@ STATIC void write_keys_block(bleio_connection_internal_t *connection) { }; bonding_block_t *new_block = find_unused_block(sizeof(bonding_keys_t)); write_block_header(new_block, &block_header); - write_block_data(new_block, (uint8_t *) &connection->bonding_keys, sizeof(bonding_keys_t)); + write_block_data(new_block, (uint8_t *)&connection->bonding_keys, sizeof(bonding_keys_t)); } void bonding_clear_keys(bonding_keys_t *bonding_keys) { - memset((uint8_t*) bonding_keys, 0, sizeof(bonding_keys_t)); + memset((uint8_t *)bonding_keys, 0, sizeof(bonding_keys_t)); } void bonding_reset(void) { - if (BONDING_FLAG != *((uint32_t *) BONDING_START_FLAG_ADDR) || - BONDING_FLAG != *((uint32_t *) BONDING_END_FLAG_ADDR)) { + if (BONDING_FLAG != *((uint32_t *)BONDING_START_FLAG_ADDR) || + BONDING_FLAG != *((uint32_t *)BONDING_END_FLAG_ADDR)) { bonding_erase_storage(); } } @@ -292,7 +292,7 @@ bool bonding_load_cccd_info(bool is_central, uint16_t conn_handle, uint16_t ediv } return NRF_SUCCESS == - sd_ble_gatts_sys_attr_set(conn_handle, block->data, block->data_length, SYS_ATTR_FLAGS); + sd_ble_gatts_sys_attr_set(conn_handle, block->data, block->data_length, SYS_ATTR_FLAGS); } bool bonding_load_keys(bool is_central, uint16_t ediv, bonding_keys_t *bonding_keys) { diff --git a/ports/nrf/common-hal/_bleio/bonding.h b/ports/nrf/common-hal/_bleio/bonding.h index cb8e7c427b..c0dbe2aec0 100644 --- a/ports/nrf/common-hal/_bleio/bonding.h +++ b/ports/nrf/common-hal/_bleio/bonding.h @@ -63,9 +63,9 @@ typedef enum { } bonding_block_type_t; typedef struct { - bool is_central: 1; // 1 if data is for a central role. - uint16_t reserved: 7; // Not currently used - bonding_block_type_t type: 8; // What kind of data is stored in. + bool is_central : 1; // 1 if data is for a central role. + uint16_t reserved : 7; // Not currently used + bonding_block_type_t type : 8; // What kind of data is stored in. uint16_t ediv; // ediv value; used as a lookup key. uint16_t conn_handle; // Connection handle: used when a BLOCK_SYS_ATTR is queued to write. // Not used as a key, etc. diff --git a/ports/nrf/common-hal/analogio/AnalogIn.c b/ports/nrf/common-hal/analogio/AnalogIn.c index dbcc5281ce..2f7bede165 100644 --- a/ports/nrf/common-hal/analogio/AnalogIn.c +++ b/ports/nrf/common-hal/analogio/AnalogIn.c @@ -39,14 +39,16 @@ void analogin_init(void) { nrf_saadc_enable(NRF_SAADC); nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE); nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_CALIBRATEOFFSET); - while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE) == 0) { } + while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE) == 0) { + } nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE); nrf_saadc_disable(NRF_SAADC); } void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, const mcu_pin_obj_t *pin) { - if (pin->adc_channel == 0) + if (pin->adc_channel == 0) { mp_raise_ValueError(translate("Pin does not have ADC capabilities")); + } nrf_gpio_cfg_default(pin->number); @@ -59,8 +61,9 @@ bool common_hal_analogio_analogin_deinited(analogio_analogin_obj_t *self) { } void common_hal_analogio_analogin_deinit(analogio_analogin_obj_t *self) { - if (common_hal_analogio_analogin_deinited(self)) + if (common_hal_analogio_analogin_deinited(self)) { return; + } nrf_gpio_cfg_default(self->pin->number); @@ -88,32 +91,40 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { nrf_saadc_oversample_set(NRF_SAADC, NRF_SAADC_OVERSAMPLE_DISABLED); nrf_saadc_enable(NRF_SAADC); - for (uint32_t i = 0; i < SAADC_CH_NUM; i++) + for (uint32_t i = 0; i < SAADC_CH_NUM; i++) { nrf_saadc_channel_input_set(NRF_SAADC, i, NRF_SAADC_INPUT_DISABLED, NRF_SAADC_INPUT_DISABLED); + } nrf_saadc_channel_init(NRF_SAADC, CHANNEL_NO, &config); nrf_saadc_channel_input_set(NRF_SAADC, CHANNEL_NO, self->pin->adc_channel, self->pin->adc_channel); nrf_saadc_buffer_init(NRF_SAADC, &value, 1); nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START); - while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED) == 0); + while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED) == 0) { + ; + } nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STARTED); nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_SAMPLE); - while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_END) == 0); + while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_END) == 0) { + ; + } nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END); nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_STOP); - while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STOPPED) == 0); + while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STOPPED) == 0) { + ; + } nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STOPPED); nrf_saadc_disable(NRF_SAADC); - if (value < 0) + if (value < 0) { value = 0; + } // Map value to from 14 to 16 bits - return (value << 2); + return value << 2; } float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t *self) { diff --git a/ports/nrf/common-hal/analogio/AnalogIn.h b/ports/nrf/common-hal/analogio/AnalogIn.h index a268bb54e4..0f5fe3208f 100644 --- a/ports/nrf/common-hal/analogio/AnalogIn.h +++ b/ports/nrf/common-hal/analogio/AnalogIn.h @@ -33,7 +33,7 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t * pin; + const mcu_pin_obj_t *pin; } analogio_analogin_obj_t; void analogin_init(void); diff --git a/ports/nrf/common-hal/analogio/AnalogOut.c b/ports/nrf/common-hal/analogio/AnalogOut.c index adafa15d5c..7afa773d30 100644 --- a/ports/nrf/common-hal/analogio/AnalogOut.c +++ b/ports/nrf/common-hal/analogio/AnalogOut.c @@ -33,7 +33,7 @@ #include "py/runtime.h" #include "supervisor/shared/translate.h" -void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, const mcu_pin_obj_t *pin) { mp_raise_RuntimeError(translate("AnalogOut functionality not supported")); } diff --git a/ports/nrf/common-hal/audiobusio/I2SOut.c b/ports/nrf/common-hal/audiobusio/I2SOut.c index 34eecf8d54..ded03c07c2 100644 --- a/ports/nrf/common-hal/audiobusio/I2SOut.c +++ b/ports/nrf/common-hal/audiobusio/I2SOut.c @@ -38,11 +38,20 @@ static audiobusio_i2sout_obj_t *instance; -struct { int16_t l, r; } static_sample16 = {0x8000, 0x8000}; -struct { uint8_t l1, r1, l2, r2; } static_sample8 = {0x80, 0x80, 0x80, 0x80}; +struct { int16_t l, r; +} static_sample16 = {0x8000, 0x8000}; +struct { uint8_t l1, r1, l2, r2; +} static_sample8 = {0x80, 0x80, 0x80, 0x80}; -struct frequency_info { uint32_t RATIO; uint32_t MCKFREQ; int sample_rate; float abserr; }; -struct ratio_info { uint32_t RATIO; int16_t divisor; bool can_16bit; }; +struct frequency_info { uint32_t RATIO; + uint32_t MCKFREQ; + int sample_rate; + float abserr; +}; +struct ratio_info { uint32_t RATIO; + int16_t divisor; + bool can_16bit; +}; struct ratio_info ratios[] = { { I2S_CONFIG_RATIO_RATIO_32X, 32, true }, { I2S_CONFIG_RATIO_RATIO_48X, 48, false }, @@ -55,7 +64,9 @@ struct ratio_info ratios[] = { { I2S_CONFIG_RATIO_RATIO_512X, 512, true }, }; -struct mclk_info { uint32_t MCKFREQ; int divisor; }; +struct mclk_info { uint32_t MCKFREQ; + int divisor; +}; struct mclk_info mclks[] = { { I2S_CONFIG_MCKFREQ_MCKFREQ_32MDIV8, 8 }, { I2S_CONFIG_MCKFREQ_MCKFREQ_32MDIV10, 10 }, @@ -71,7 +82,7 @@ struct mclk_info mclks[] = { }; static void calculate_ratio_info(uint32_t target_sample_rate, struct frequency_info *info, - int ratio_index, int mclk_index) { + int ratio_index, int mclk_index) { info->RATIO = ratios[ratio_index].RATIO; info->MCKFREQ = mclks[mclk_index].MCKFREQ; info->sample_rate = 32000000 @@ -82,24 +93,24 @@ static void calculate_ratio_info(uint32_t target_sample_rate, struct frequency_i void choose_i2s_clocking(audiobusio_i2sout_obj_t *self, uint32_t sample_rate) { struct frequency_info best = {0, 0, 0, 1.0}; - for (size_t ri=0; riCONFIG.SWIDTH == I2S_CONFIG_SWIDTH_SWIDTH_16Bit - && !ratios[ri].can_16bit) { + && !ratios[ri].can_16bit) { continue; } - for (size_t mi=0; miCONFIG.RATIO = best.RATIO; @@ -107,7 +118,7 @@ void choose_i2s_clocking(audiobusio_i2sout_obj_t *self, uint32_t sample_rate) { self->sample_rate = best.sample_rate; } -static void i2s_buffer_fill(audiobusio_i2sout_obj_t* self) { +static void i2s_buffer_fill(audiobusio_i2sout_obj_t *self) { void *buffer = self->buffers[self->next_buffer]; void *buffer_start = buffer; NRF_I2S->TXD.PTR = (uintptr_t)buffer; @@ -119,7 +130,7 @@ static void i2s_buffer_fill(audiobusio_i2sout_obj_t* self) { uint32_t sample_buffer_length; audioio_get_buffer_result_t get_buffer_result = audiosample_get_buffer(self->sample, false, 0, - &self->sample_data, &sample_buffer_length); + &self->sample_data, &sample_buffer_length); self->sample_end = self->sample_data + sample_buffer_length; if (get_buffer_result == GET_BUFFER_DONE) { if (self->loop) { @@ -138,16 +149,16 @@ static void i2s_buffer_fill(audiobusio_i2sout_obj_t* self) { if (self->samples_signed) { memcpy(buffer, self->sample_data, bytecount); } else if (self->bytes_per_sample == 2) { - uint16_t *bp = (uint16_t*)buffer; - uint16_t *be = (uint16_t*)(buffer + bytecount); - uint16_t *sp = (uint16_t*)self->sample_data; + uint16_t *bp = (uint16_t *)buffer; + uint16_t *be = (uint16_t *)(buffer + bytecount); + uint16_t *sp = (uint16_t *)self->sample_data; for (; bp < be;) { *bp++ = *sp++ + 0x8000; } } else { - uint8_t *bp = (uint8_t*)buffer; - uint8_t *be = (uint8_t*)(buffer + bytecount); - uint8_t *sp = (uint8_t*)self->sample_data; + uint8_t *bp = (uint8_t *)buffer; + uint8_t *be = (uint8_t *)(buffer + bytecount); + uint8_t *sp = (uint8_t *)self->sample_data; for (; bp < be;) { *bp++ = *sp++ + 0x80; } @@ -162,13 +173,13 @@ static void i2s_buffer_fill(audiobusio_i2sout_obj_t* self) { if (buffer != buffer_start) { if (self->bytes_per_sample == 1 && self->channel_count == 1) { // For 8-bit mono, 4 copies of the final sample are required - self->hold_value = 0x01010101 * *(uint8_t*)(buffer-1); + self->hold_value = 0x01010101 * *(uint8_t *)(buffer - 1); } else if (self->bytes_per_sample == 2 && self->channel_count == 2) { // For 16-bit stereo, 1 copy of the final sample is required - self->hold_value = *(uint32_t*)(buffer-4); + self->hold_value = *(uint32_t *)(buffer - 4); } else { // For 8-bit stereo and 16-bit mono, 2 copies of the final sample are required - self->hold_value = 0x00010001 * *(uint16_t*)(buffer-2); + self->hold_value = 0x00010001 * *(uint16_t *)(buffer - 2); } } @@ -180,19 +191,21 @@ static void i2s_buffer_fill(audiobusio_i2sout_obj_t* self) { NRF_I2S->TASKS_STOP = 1; self->playing = false; } - uint32_t *bp = (uint32_t*)buffer; - uint32_t *be = (uint32_t*)(buffer + bytesleft); - for (; bp != be; ) + uint32_t *bp = (uint32_t *)buffer; + uint32_t *be = (uint32_t *)(buffer + bytesleft); + for (; bp != be;) { *bp++ = self->hold_value; + } return; } } -void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, - const mcu_pin_obj_t* bit_clock, const mcu_pin_obj_t* word_select, - const mcu_pin_obj_t* data, bool left_justified) { - if (instance) +void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, + const mcu_pin_obj_t *bit_clock, const mcu_pin_obj_t *word_select, + const mcu_pin_obj_t *data, bool left_justified) { + if (instance) { mp_raise_RuntimeError(translate("Device in use")); + } instance = self; claim_pin(bit_clock); @@ -216,11 +229,11 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, supervisor_enable_tick(); } -bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t *self) { return self->data_pin_number == 0xff; } -void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self) { if (common_hal_audiobusio_i2sout_deinited(self)) { return; } @@ -236,8 +249,8 @@ void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { supervisor_disable_tick(); } -void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, - mp_obj_t sample, bool loop) { +void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, + mp_obj_t sample, bool loop) { if (common_hal_audiobusio_i2sout_get_playing(self)) { common_hal_audiobusio_i2sout_stop(self); } @@ -271,7 +284,7 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, */ enum { buffer_length_ms = 16 }; self->buffer_length = sample_rate * buffer_length_ms - * self->bytes_per_sample * self->channel_count / 1000; + * self->bytes_per_sample * self->channel_count / 1000; self->buffer_length = (self->buffer_length + 3) & ~3; self->buffers[0] = m_malloc(self->buffer_length, false); self->buffers[1] = m_malloc(self->buffer_length, false); @@ -297,25 +310,25 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, i2s_background(); } -void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t *self) { self->paused = true; } -void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t *self) { self->paused = false; } -bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t *self) { return self->paused; } -void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t *self) { NRF_I2S->TASKS_STOP = 1; self->stopping = true; NRF_I2S->INTENCLR = I2S_INTENSET_TXPTRUPD_Msk; } -bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t *self) { if (NRF_I2S->EVENTS_STOPPED) { self->playing = false; NRF_I2S->EVENTS_STOPPED = 0; diff --git a/ports/nrf/common-hal/audiobusio/PDMIn.c b/ports/nrf/common-hal/audiobusio/PDMIn.c index ddd34174b2..47d7365777 100644 --- a/ports/nrf/common-hal/audiobusio/PDMIn.c +++ b/ports/nrf/common-hal/audiobusio/PDMIn.c @@ -35,13 +35,13 @@ NRF_PDM_Type *nrf_pdm = NRF_PDM; static uint32_t dummy_buffer[4]; // Caller validates that pins are free. -void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t* self, - const mcu_pin_obj_t* clock_pin, - const mcu_pin_obj_t* data_pin, - uint32_t sample_rate, - uint8_t bit_depth, - bool mono, - uint8_t oversample) { +void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, + const mcu_pin_obj_t *clock_pin, + const mcu_pin_obj_t *data_pin, + uint32_t sample_rate, + uint8_t bit_depth, + bool mono, + uint8_t oversample) { claim_pin(clock_pin); claim_pin(data_pin); @@ -68,11 +68,11 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t* self, nrf_pdm->TASKS_START = 1; } -bool common_hal_audiobusio_pdmin_deinited(audiobusio_pdmin_obj_t* self) { +bool common_hal_audiobusio_pdmin_deinited(audiobusio_pdmin_obj_t *self) { return !self->clock_pin_number; } -void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t* self) { +void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t *self) { nrf_pdm->ENABLE = 0; reset_pin_number(self->clock_pin_number); @@ -81,16 +81,16 @@ void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t* self) { self->data_pin_number = 0; } -uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t* self) { +uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t *self) { return 16; } -uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t* self) { +uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t *self) { return 16000; } -uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* self, - uint16_t* output_buffer, uint32_t output_buffer_length) { +uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t *self, + uint16_t *output_buffer, uint32_t output_buffer_length) { // Note: Adafruit's module has SELECT pulled to GND, which makes the DATA // valid when the CLK is low, therefore it must be sampled on the rising edge. if (self->mono) { @@ -113,11 +113,11 @@ uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* se // Step 3. wait for PDM to end while (!nrf_pdm->EVENTS_END) { - MICROPY_VM_HOOK_LOOP; + MICROPY_VM_HOOK_LOOP; } // Step 4. They want unsigned - for (uint32_t i=0; ipwm->INTENCLR = PWM_INTENSET_SEQSTARTED0_Msk | PWM_INTENSET_SEQSTARTED1_Msk; - for (size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(active_audio); i++) { if (active_audio[i] == self) { active_audio[i] = NULL; supervisor_disable_tick(); @@ -85,7 +85,7 @@ STATIC void deactivate_audiopwmout_obj(audiopwmio_pwmaudioout_obj_t *self) { } void audiopwmout_reset() { - for (size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(active_audio); i++) { if (active_audio[i]) { supervisor_disable_tick(); } @@ -99,7 +99,7 @@ STATIC void fill_buffers(audiopwmio_pwmaudioout_obj_t *self, int buf) { uint32_t buffer_length; audioio_get_buffer_result_t get_buffer_result = audiosample_get_buffer(self->sample, false, 0, - &buffer, &buffer_length); + &buffer, &buffer_length); if (get_buffer_result == GET_BUFFER_ERROR) { common_hal_audiopwmio_pwmaudioout_stop(self); return; @@ -114,23 +114,25 @@ STATIC void fill_buffers(audiopwmio_pwmaudioout_obj_t *self, int buf) { uint8_t rawval = (*buffer++ + offset); uint16_t val = (uint16_t)(((uint32_t)rawval * (uint32_t)scale) >> 8); *dev_buffer++ = val; - if (self->sample_channel_count == 1) + if (self->sample_channel_count == 1) { *dev_buffer++ = val; + } } } else { uint16_t offset = self->signed_to_unsigned ? 0x8000 : 0; uint16_t scale = self->scale; - uint16_t *buffer16 = (uint16_t*)buffer; + uint16_t *buffer16 = (uint16_t *)buffer; while (dev_buffer < end_dev_buffer) { uint16_t rawval = (*buffer16++ + offset); uint16_t val = (uint16_t)((rawval * (uint32_t)scale) >> 16); *dev_buffer++ = val; - if (self->sample_channel_count == 1) + if (self->sample_channel_count == 1) { *dev_buffer++ = val; + } } } self->pwm->SEQ[buf].PTR = (intptr_t)self->buffers[buf]; - self->pwm->SEQ[buf].CNT = num_samples*2; + self->pwm->SEQ[buf].CNT = num_samples * 2; if (self->loop && get_buffer_result == GET_BUFFER_DONE) { audiosample_reset_buffer(self->sample, false, 0); @@ -141,14 +143,16 @@ STATIC void fill_buffers(audiopwmio_pwmaudioout_obj_t *self, int buf) { } STATIC void audiopwmout_background_obj(audiopwmio_pwmaudioout_obj_t *self) { - if (!common_hal_audiopwmio_pwmaudioout_get_playing(self)) + if (!common_hal_audiopwmio_pwmaudioout_get_playing(self)) { return; + } if (self->stopping) { bool stopped = (self->pwm->EVENTS_SEQEND[0] || !self->pwm->EVENTS_SEQSTARTED[0]) && (self->pwm->EVENTS_SEQEND[1] || !self->pwm->EVENTS_SEQSTARTED[1]); - if (stopped) + if (stopped) { self->pwm->TASKS_STOP = 1; + } } else if (!self->paused && !self->single_buffer) { if (self->pwm->EVENTS_SEQSTARTED[0]) { fill_buffers(self, 1); @@ -171,17 +175,19 @@ void audiopwmout_background() { return; } // Check our objects because the PWM could be active for some other reason. - for (size_t i=0; i < MP_ARRAY_SIZE(active_audio); i++) { - if (!active_audio[i]) continue; + for (size_t i = 0; i < MP_ARRAY_SIZE(active_audio); i++) { + if (!active_audio[i]) { + continue; + } audiopwmout_background_obj(active_audio[i]); } } // Caller validates that pins are free. -void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t* self, - const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t quiescent_value) { +void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t *self, + const mcu_pin_obj_t *left_channel, const mcu_pin_obj_t *right_channel, uint16_t quiescent_value) { self->pwm = pwmout_allocate(256, PWM_PRESCALER_PRESCALER_DIV_1, true, NULL, NULL, - &self->pwm_irq); + &self->pwm_irq); if (!self->pwm) { mp_raise_RuntimeError(translate("All timers in use")); } @@ -197,8 +203,7 @@ void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t* s self->pwm->PSEL.OUT[0] = self->left_channel_number = left_channel->number; claim_pin(left_channel); - if (right_channel) - { + if (right_channel) { self->pwm->PSEL.OUT[2] = self->right_channel_number = right_channel->number; claim_pin(right_channel); } @@ -209,11 +214,11 @@ void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t* s // TODO: Ramp from 0 to quiescent value } -bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t* self) { +bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t *self) { return !self->pwm; } -void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t* self) { +void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t *self) { if (common_hal_audiopwmio_pwmaudioout_deinited(self)) { return; } @@ -222,10 +227,12 @@ void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t* self // TODO: ramp the pwm down from quiescent value to 0 self->pwm->ENABLE = 0; - if (self->left_channel_number) + if (self->left_channel_number) { reset_pin_number(self->left_channel_number); - if (self->right_channel_number) + } + if (self->right_channel_number) { reset_pin_number(self->right_channel_number); + } pwmout_free_channel(self->pwm, 0); pwmout_free_channel(self->pwm, 2); @@ -239,7 +246,7 @@ void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t* self self->buffers[1] = NULL; } -void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, mp_obj_t sample, bool loop) { +void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, mp_obj_t sample, bool loop) { if (common_hal_audiopwmio_pwmaudioout_get_playing(self)) { common_hal_audiopwmio_pwmaudioout_stop(self); } @@ -261,13 +268,14 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, } uint16_t buffer_length = (uint16_t)max_buffer_length; self->buffers[0] = m_malloc(buffer_length * 2 * sizeof(uint16_t), false); - if (!self->single_buffer) + if (!self->single_buffer) { self->buffers[1] = m_malloc(buffer_length * 2 * sizeof(uint16_t), false); + } uint32_t top; self->pwm->SEQ[0].REFRESH = self->pwm->SEQ[1].REFRESH = calculate_pwm_parameters(sample_rate, &top); - self->scale = top-1; + self->scale = top - 1; self->pwm->COUNTERTOP = top; self->pwm->LOOP = 1; @@ -291,7 +299,7 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, self->paused = false; } -void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t* self) { +void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t *self) { deactivate_audiopwmout_obj(self); self->pwm->TASKS_STOP = 1; self->stopping = false; @@ -304,7 +312,7 @@ void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t* self) self->buffers[1] = NULL; } -bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t* self) { +bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t *self) { if (!self->paused && self->pwm->EVENTS_STOPPED) { self->playing = false; self->pwm->EVENTS_STOPPED = 0; @@ -328,12 +336,12 @@ bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t* * feels instant. (This also saves on memory, for long in-memory "single buffer" * samples, since we have to locally take a resampled copy!) */ -void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t* self) { +void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t *self) { self->paused = true; self->pwm->SHORTS = NRF_PWM_SHORT_SEQEND1_STOP_MASK; } -void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t* self) { +void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t *self) { self->paused = false; self->pwm->SHORTS = NRF_PWM_SHORT_LOOPSDONE_SEQSTART0_MASK; if (self->pwm->EVENTS_STOPPED) { @@ -342,6 +350,6 @@ void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t* self } } -bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t* self) { +bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t *self) { return self->paused; } diff --git a/ports/nrf/common-hal/busio/I2C.c b/ports/nrf/common-hal/busio/I2C.c index 654fa857ff..de9417a6cc 100644 --- a/ports/nrf/common-hal/busio/I2C.c +++ b/ports/nrf/common-hal/busio/I2C.c @@ -42,24 +42,22 @@ #define I2C_MAX_XFER_LEN ((1UL << TWIM0_EASYDMA_MAXCNT_SIZE) - 1) STATIC twim_peripheral_t twim_peripherals[] = { -#if NRFX_CHECK(NRFX_TWIM0_ENABLED) + #if NRFX_CHECK(NRFX_TWIM0_ENABLED) // SPIM0 and TWIM0 share an address. { .twim = NRFX_TWIM_INSTANCE(0), - .in_use = false - }, -#endif -#if NRFX_CHECK(NRFX_TWIM1_ENABLED) + .in_use = false}, + #endif + #if NRFX_CHECK(NRFX_TWIM1_ENABLED) // SPIM1 and TWIM1 share an address. { .twim = NRFX_TWIM_INSTANCE(1), - .in_use = false - }, -#endif + .in_use = false}, + #endif }; STATIC bool never_reset[MP_ARRAY_SIZE(twim_peripherals)]; void i2c_reset(void) { - for (size_t i = 0 ; i < MP_ARRAY_SIZE(twim_peripherals); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(twim_peripherals); i++) { if (never_reset[i]) { continue; } @@ -69,7 +67,7 @@ void i2c_reset(void) { } void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - for (size_t i = 0 ; i < MP_ARRAY_SIZE(twim_peripherals); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(twim_peripherals); i++) { if (self->twim_peripheral == &twim_peripherals[i]) { never_reset[i] = true; @@ -82,15 +80,15 @@ void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { static uint8_t twi_error_to_mp(const nrfx_err_t err) { switch (err) { - case NRFX_ERROR_DRV_TWI_ERR_ANACK: - return MP_ENODEV; - case NRFX_ERROR_BUSY: - return MP_EBUSY; - case NRFX_ERROR_DRV_TWI_ERR_DNACK: - case NRFX_ERROR_INVALID_ADDR: - return MP_EIO; - default: - break; + case NRFX_ERROR_DRV_TWI_ERR_ANACK: + return MP_ENODEV; + case NRFX_ERROR_BUSY: + return MP_EBUSY; + case NRFX_ERROR_DRV_TWI_ERR_DNACK: + case NRFX_ERROR_INVALID_ADDR: + return MP_EIO; + default: + break; } return 0; @@ -103,7 +101,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, const mcu_pin_obj_t * // Find a free instance. self->twim_peripheral = NULL; - for (size_t i = 0 ; i < MP_ARRAY_SIZE(twim_peripherals); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(twim_peripherals); i++) { if (!twim_peripherals[i].in_use) { self->twim_peripheral = &twim_peripherals[i]; // Mark it as in_use later after other validation is finished. @@ -115,7 +113,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, const mcu_pin_obj_t * mp_raise_ValueError(translate("All I2C peripherals are in use")); } -#if CIRCUITPY_REQUIRE_I2C_PULLUPS + #if CIRCUITPY_REQUIRE_I2C_PULLUPS // Test that the pins are in a high state. (Hopefully indicating they are pulled up.) nrf_gpio_cfg_input(scl->number, NRF_GPIO_PIN_PULLDOWN); nrf_gpio_cfg_input(sda->number, NRF_GPIO_PIN_PULLDOWN); @@ -133,19 +131,19 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, const mcu_pin_obj_t * reset_pin_number(scl->number); mp_raise_RuntimeError(translate("No pull up found on SDA or SCL; check your wiring")); } -#endif + #endif nrfx_twim_config_t config = NRFX_TWIM_DEFAULT_CONFIG(scl->number, sda->number); -#if defined(TWIM_FREQUENCY_FREQUENCY_K1000) + #if defined(TWIM_FREQUENCY_FREQUENCY_K1000) if (frequency >= 1000000) { config.frequency = NRF_TWIM_FREQ_1000K; } else -#endif + #endif if (frequency >= 400000) { - config.frequency = NRF_TWIM_FREQ_400K; + config.frequency = NRF_TWIM_FREQ_400K; } else if (frequency >= 250000) { - config.frequency = NRF_TWIM_FREQ_250K; + config.frequency = NRF_TWIM_FREQ_250K; } else { config.frequency = NRF_TWIM_FREQ_100K; } @@ -198,11 +196,15 @@ bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { nrf_twim_task_trigger(reg, NRF_TWIM_TASK_STARTTX); while (nrf_twim_event_check(reg, NRF_TWIM_EVENT_TXSTARTED) == 0 && - nrf_twim_event_check(reg, NRF_TWIM_EVENT_ERROR) == 0); + nrf_twim_event_check(reg, NRF_TWIM_EVENT_ERROR) == 0) { + ; + } nrf_twim_event_clear(reg, NRF_TWIM_EVENT_TXSTARTED); nrf_twim_task_trigger(reg, NRF_TWIM_TASK_STOP); - while (nrf_twim_event_check(reg, NRF_TWIM_EVENT_STOPPED) == 0); + while (nrf_twim_event_check(reg, NRF_TWIM_EVENT_STOPPED) == 0) { + ; + } nrf_twim_event_clear(reg, NRF_TWIM_EVENT_STOPPED); if (nrf_twim_event_check(reg, NRF_TWIM_EVENT_ERROR)) { @@ -237,7 +239,7 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { } uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len, bool stopBit) { - if(len == 0) { + if (len == 0) { return common_hal_busio_i2c_probe(self, addr) ? 0 : MP_ENODEV; } @@ -246,12 +248,12 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const u nrfx_twim_enable(&self->twim_peripheral->twim); // break into MAX_XFER_LEN transaction - while ( len ) { + while (len) { const size_t xact_len = MIN(len, I2C_MAX_XFER_LEN); - nrfx_twim_xfer_desc_t xfer_desc = NRFX_TWIM_XFER_DESC_TX(addr, (uint8_t*) data, xact_len); + nrfx_twim_xfer_desc_t xfer_desc = NRFX_TWIM_XFER_DESC_TX(addr, (uint8_t *)data, xact_len); uint32_t const flags = (stopBit ? 0 : NRFX_TWIM_FLAG_TX_NO_STOP); - if ( NRFX_SUCCESS != (err = nrfx_twim_xfer(&self->twim_peripheral->twim, &xfer_desc, flags)) ) { + if (NRFX_SUCCESS != (err = nrfx_twim_xfer(&self->twim_peripheral->twim, &xfer_desc, flags))) { break; } @@ -265,7 +267,7 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const u } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { - if(len == 0) { + if (len == 0) { return 0; } @@ -274,11 +276,11 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t nrfx_twim_enable(&self->twim_peripheral->twim); // break into MAX_XFER_LEN transaction - while ( len ) { + while (len) { const size_t xact_len = MIN(len, I2C_MAX_XFER_LEN); nrfx_twim_xfer_desc_t xfer_desc = NRFX_TWIM_XFER_DESC_RX(addr, data, xact_len); - if ( NRFX_SUCCESS != (err = nrfx_twim_xfer(&self->twim_peripheral->twim, &xfer_desc, 0)) ) { + if (NRFX_SUCCESS != (err = nrfx_twim_xfer(&self->twim_peripheral->twim, &xfer_desc, 0))) { break; } diff --git a/ports/nrf/common-hal/busio/I2C.h b/ports/nrf/common-hal/busio/I2C.h index b75d15f00f..04bc578684 100644 --- a/ports/nrf/common-hal/busio/I2C.h +++ b/ports/nrf/common-hal/busio/I2C.h @@ -38,7 +38,7 @@ typedef struct { typedef struct { mp_obj_base_t base; - twim_peripheral_t* twim_peripheral; + twim_peripheral_t *twim_peripheral; bool has_lock; uint8_t scl_pin_number; uint8_t sda_pin_number; diff --git a/ports/nrf/common-hal/busio/SPI.c b/ports/nrf/common-hal/busio/SPI.c index 1cf074955f..309e1bce18 100644 --- a/ports/nrf/common-hal/busio/SPI.c +++ b/ports/nrf/common-hal/busio/SPI.c @@ -52,45 +52,41 @@ // These are in order from highest available frequency to lowest (32MHz first, then 8MHz). STATIC spim_peripheral_t spim_peripherals[] = { -#if NRFX_CHECK(NRFX_SPIM3_ENABLED) + #if NRFX_CHECK(NRFX_SPIM3_ENABLED) // SPIM3 exists only on nRF52840 and supports 32MHz max. All other SPIM's are only 8MHz max. // Allocate SPIM3 first. { .spim = NRFX_SPIM_INSTANCE(3), .max_frequency = 32000000, - .max_xfer_size = MIN(SPIM3_BUFFER_RAM_SIZE, (1UL << SPIM3_EASYDMA_MAXCNT_SIZE) - 1) - }, -#endif -#if NRFX_CHECK(NRFX_SPIM2_ENABLED) + .max_xfer_size = MIN(SPIM3_BUFFER_RAM_SIZE, (1UL << SPIM3_EASYDMA_MAXCNT_SIZE) - 1)}, + #endif + #if NRFX_CHECK(NRFX_SPIM2_ENABLED) // SPIM2 is not shared with a TWIM, so allocate before the shared ones. { .spim = NRFX_SPIM_INSTANCE(2), .max_frequency = 8000000, - .max_xfer_size = (1UL << SPIM2_EASYDMA_MAXCNT_SIZE) - 1 - }, -#endif -#if NRFX_CHECK(NRFX_SPIM1_ENABLED) + .max_xfer_size = (1UL << SPIM2_EASYDMA_MAXCNT_SIZE) - 1}, + #endif + #if NRFX_CHECK(NRFX_SPIM1_ENABLED) // SPIM1 and TWIM1 share an address. { .spim = NRFX_SPIM_INSTANCE(1), .max_frequency = 8000000, - .max_xfer_size = (1UL << SPIM1_EASYDMA_MAXCNT_SIZE) - 1 - }, -#endif -#if NRFX_CHECK(NRFX_SPIM0_ENABLED) + .max_xfer_size = (1UL << SPIM1_EASYDMA_MAXCNT_SIZE) - 1}, + #endif + #if NRFX_CHECK(NRFX_SPIM0_ENABLED) // SPIM0 and TWIM0 share an address. { .spim = NRFX_SPIM_INSTANCE(0), .max_frequency = 8000000, - .max_xfer_size = (1UL << SPIM0_EASYDMA_MAXCNT_SIZE) - 1 - }, -#endif + .max_xfer_size = (1UL << SPIM0_EASYDMA_MAXCNT_SIZE) - 1}, + #endif }; STATIC bool never_reset[MP_ARRAY_SIZE(spim_peripherals)]; // Separate RAM area for SPIM3 transmit buffer to avoid SPIM3 hardware errata. // https://infocenter.nordicsemi.com/index.jsp?topic=%2Ferrata_nRF52840_Rev2%2FERR%2FnRF52840%2FRev2%2Flatest%2Fanomaly_840_198.html -STATIC uint8_t *spim3_transmit_buffer = (uint8_t *) SPIM3_BUFFER_RAM_START_ADDR; +STATIC uint8_t *spim3_transmit_buffer = (uint8_t *)SPIM3_BUFFER_RAM_START_ADDR; void spi_reset(void) { - for (size_t i = 0 ; i < MP_ARRAY_SIZE(spim_peripherals); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(spim_peripherals); i++) { if (never_reset[i]) { continue; } @@ -99,7 +95,7 @@ void spi_reset(void) { } void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - for (size_t i = 0 ; i < MP_ARRAY_SIZE(spim_peripherals); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(spim_peripherals); i++) { if (self->spim_peripheral == &spim_peripherals[i]) { never_reset[i] = true; @@ -119,12 +115,12 @@ static nrf_spim_frequency_t baudrate_to_spim_frequency(const uint32_t baudrate) const uint32_t boundary; nrf_spim_frequency_t spim_frequency; } baudrate_map[] = { -#ifdef SPIM_FREQUENCY_FREQUENCY_M32 + #ifdef SPIM_FREQUENCY_FREQUENCY_M32 { 32000000, NRF_SPIM_FREQ_32M }, -#endif -#ifdef SPIM_FREQUENCY_FREQUENCY_M16 + #endif + #ifdef SPIM_FREQUENCY_FREQUENCY_M16 { 16000000, NRF_SPIM_FREQ_16M }, -#endif + #endif { 8000000, NRF_SPIM_FREQ_8M }, { 4000000, NRF_SPIM_FREQ_4M }, { 2000000, NRF_SPIM_FREQ_2M }, @@ -147,10 +143,10 @@ static nrf_spim_frequency_t baudrate_to_spim_frequency(const uint32_t baudrate) return 0; } -void common_hal_busio_spi_construct(busio_spi_obj_t *self, const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, const mcu_pin_obj_t * miso) { +void common_hal_busio_spi_construct(busio_spi_obj_t *self, const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, const mcu_pin_obj_t *miso) { // Find a free instance, with most desirable (highest freq and not shared) allocated first. self->spim_peripheral = NULL; - for (size_t i = 0 ; i < MP_ARRAY_SIZE(spim_peripherals); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(spim_peripherals); i++) { if ((spim_peripherals[i].spim.p_reg->ENABLE & SPIM_ENABLE_ENABLE_Msk) == 0) { self->spim_peripheral = &spim_peripherals[i]; break; @@ -162,7 +158,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, const mcu_pin_obj_t * } nrfx_spim_config_t config = NRFX_SPIM_DEFAULT_CONFIG(NRFX_SPIM_PIN_NOT_USED, NRFX_SPIM_PIN_NOT_USED, - NRFX_SPIM_PIN_NOT_USED, NRFX_SPIM_PIN_NOT_USED); + NRFX_SPIM_PIN_NOT_USED, NRFX_SPIM_PIN_NOT_USED); config.frequency = baudrate_to_spim_frequency(self->spim_peripheral->max_frequency); @@ -198,8 +194,9 @@ bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { } void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { - if (common_hal_busio_spi_deinited(self)) + if (common_hal_busio_spi_deinited(self)) { return; + } nrfx_spim_uninit(&self->spim_peripheral->spim); @@ -211,12 +208,12 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { bool common_hal_busio_spi_configure(busio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { // nrf52 does not support 16 bit if (bits != 8) { - return false; + return false; } // Set desired frequency, rounding down, and don't go above available frequency for this SPIM. nrf_spim_frequency_set(self->spim_peripheral->spim.p_reg, - baudrate_to_spim_frequency(MIN(baudrate, self->spim_peripheral->max_frequency))); + baudrate_to_spim_frequency(MIN(baudrate, self->spim_peripheral->max_frequency))); nrf_spim_mode_t mode = NRF_SPIM_MODE_0; if (polarity) { @@ -251,7 +248,7 @@ void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { bool common_hal_busio_spi_write(busio_spi_obj_t *self, const uint8_t *data, size_t len) { const bool is_spim3 = self->spim_peripheral->spim.p_reg == NRF_SPIM3; - uint8_t *next_chunk = (uint8_t *) data; + uint8_t *next_chunk = (uint8_t *)data; while (len > 0) { size_t chunk_size = MIN(len, self->spim_peripheral->max_xfer_size); @@ -301,7 +298,7 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou } const nrfx_spim_xfer_desc_t xfer = NRFX_SPIM_SINGLE_XFER(next_chunk_out, chunk_size, - next_chunk_in, chunk_size); + next_chunk_in, chunk_size); if (nrfx_spim_xfer(&self->spim_peripheral->spim, &xfer, 0) != NRFX_SUCCESS) { return false; } @@ -313,39 +310,39 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_ou return true; } -uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self) { +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { switch (self->spim_peripheral->spim.p_reg->FREQUENCY) { - case NRF_SPIM_FREQ_125K: - return 125000; - case NRF_SPIM_FREQ_250K: - return 250000; - case NRF_SPIM_FREQ_500K: - return 500000; - case NRF_SPIM_FREQ_1M: - return 1000000; - case NRF_SPIM_FREQ_2M: - return 2000000; - case NRF_SPIM_FREQ_4M: - return 4000000; - case NRF_SPIM_FREQ_8M: - return 8000000; -#ifdef SPIM_FREQUENCY_FREQUENCY_M16 - case NRF_SPIM_FREQ_16M: - return 16000000; -#endif -#ifdef SPIM_FREQUENCY_FREQUENCY_M32 - case NRF_SPIM_FREQ_32M: - return 32000000; -#endif - default: - return 0; + case NRF_SPIM_FREQ_125K: + return 125000; + case NRF_SPIM_FREQ_250K: + return 250000; + case NRF_SPIM_FREQ_500K: + return 500000; + case NRF_SPIM_FREQ_1M: + return 1000000; + case NRF_SPIM_FREQ_2M: + return 2000000; + case NRF_SPIM_FREQ_4M: + return 4000000; + case NRF_SPIM_FREQ_8M: + return 8000000; + #ifdef SPIM_FREQUENCY_FREQUENCY_M16 + case NRF_SPIM_FREQ_16M: + return 16000000; + #endif + #ifdef SPIM_FREQUENCY_FREQUENCY_M32 + case NRF_SPIM_FREQ_32M: + return 32000000; + #endif + default: + return 0; } } -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { return (self->spim_peripheral->spim.p_reg->CONFIG & SPIM_CONFIG_CPHA_Msk) >> SPIM_CONFIG_CPHA_Pos; } -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { return (self->spim_peripheral->spim.p_reg->CONFIG & SPIM_CONFIG_CPOL_Msk) >> SPIM_CONFIG_CPOL_Pos; } diff --git a/ports/nrf/common-hal/busio/SPI.h b/ports/nrf/common-hal/busio/SPI.h index ef3ac9531e..796ff59f93 100644 --- a/ports/nrf/common-hal/busio/SPI.h +++ b/ports/nrf/common-hal/busio/SPI.h @@ -38,7 +38,7 @@ typedef struct { typedef struct { mp_obj_base_t base; - spim_peripheral_t* spim_peripheral; + spim_peripheral_t *spim_peripheral; bool has_lock; uint8_t clock_pin_number; uint8_t MOSI_pin_number; diff --git a/ports/nrf/common-hal/busio/UART.c b/ports/nrf/common-hal/busio/UART.c index 491e360e4d..6436cb4e70 100644 --- a/ports/nrf/common-hal/busio/UART.c +++ b/ports/nrf/common-hal/busio/UART.c @@ -41,23 +41,23 @@ // expression to examine, and return value in case of failing #define _VERIFY_ERR(_exp) \ - do {\ - uint32_t _err = (_exp);\ - if (NRFX_SUCCESS != _err ) {\ - mp_raise_msg_varg(&mp_type_RuntimeError, translate("error = 0x%08lX"), _err);\ - }\ - }while(0) + do { \ + uint32_t _err = (_exp); \ + if (NRFX_SUCCESS != _err) { \ + mp_raise_msg_varg(&mp_type_RuntimeError, translate("error = 0x%08lX"), _err); \ + } \ + } while (0) static nrfx_uarte_t nrfx_uartes[] = { -#if NRFX_CHECK(NRFX_UARTE0_ENABLED) + #if NRFX_CHECK(NRFX_UARTE0_ENABLED) NRFX_UARTE_INSTANCE(0), -#endif -#if NRFX_CHECK(NRFX_UARTE1_ENABLED) + #endif + #if NRFX_CHECK(NRFX_UARTE1_ENABLED) NRFX_UARTE_INSTANCE(1), -#endif + #endif }; -static uint32_t get_nrf_baud (uint32_t baudrate) { +static uint32_t get_nrf_baud(uint32_t baudrate) { static const struct { const uint32_t boundary; @@ -70,9 +70,9 @@ static uint32_t get_nrf_baud (uint32_t baudrate) { { 14400, NRF_UARTE_BAUDRATE_14400 }, { 19200, NRF_UARTE_BAUDRATE_19200 }, { 28800, NRF_UARTE_BAUDRATE_28800 }, - { 31250, NRF_UARTE_BAUDRATE_31250 }, + { 31250, NRF_UARTE_BAUDRATE_31250 }, { 38400, NRF_UARTE_BAUDRATE_38400 }, - { 56000, NRF_UARTE_BAUDRATE_56000 }, + { 56000, NRF_UARTE_BAUDRATE_56000 }, { 57600, NRF_UARTE_BAUDRATE_57600 }, { 76800, NRF_UARTE_BAUDRATE_76800 }, { 115200, NRF_UARTE_BAUDRATE_115200 }, @@ -94,26 +94,26 @@ static uint32_t get_nrf_baud (uint32_t baudrate) { } while (true); } -static void uart_callback_irq (const nrfx_uarte_event_t * event, void * context) { - busio_uart_obj_t* self = (busio_uart_obj_t*) context; +static void uart_callback_irq(const nrfx_uarte_event_t *event, void *context) { + busio_uart_obj_t *self = (busio_uart_obj_t *)context; - switch ( event->type ) { + switch (event->type) { case NRFX_UARTE_EVT_RX_DONE: if (ringbuf_num_empty(&self->ringbuf) >= event->data.rxtx.bytes) { ringbuf_put_n(&self->ringbuf, event->data.rxtx.p_data, event->data.rxtx.bytes); // keep receiving - (void) nrfx_uarte_rx(self->uarte, &self->rx_char, 1); + (void)nrfx_uarte_rx(self->uarte, &self->rx_char, 1); } else { // receive buffer full, suspend self->rx_paused = true; nrf_gpio_pin_write(self->rts_pin_number, true); } - break; + break; case NRFX_UARTE_EVT_TX_DONE: // nothing to do - break; + break; case NRFX_UARTE_EVT_ERROR: // Possible Error source is Overrun, Parity, Framing, Break @@ -122,26 +122,26 @@ static void uart_callback_irq (const nrfx_uarte_event_t * event, void * context) ringbuf_put_n(&self->ringbuf, event->data.error.rxtx.p_data, event->data.error.rxtx.bytes); // Keep receiving - (void) nrfx_uarte_rx(self->uarte, &self->rx_char, 1); - break; + (void)nrfx_uarte_rx(self->uarte, &self->rx_char, 1); + break; default: - break; + break; } } void uart_reset(void) { - for (size_t i = 0 ; i < MP_ARRAY_SIZE(nrfx_uartes); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(nrfx_uartes); i++) { nrfx_uarte_uninit(&nrfx_uartes[i]); } } void common_hal_busio_uart_construct(busio_uart_obj_t *self, - const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, - const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, - const mcu_pin_obj_t * rs485_dir, bool rs485_invert, + const mcu_pin_obj_t *tx, const mcu_pin_obj_t *rx, + const mcu_pin_obj_t *rts, const mcu_pin_obj_t *cts, + const mcu_pin_obj_t *rs485_dir, bool rs485_invert, uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, - mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, + mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { if (bits != 8) { @@ -154,7 +154,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, // Find a free UART peripheral. self->uarte = NULL; - for (size_t i = 0 ; i < MP_ARRAY_SIZE(nrfx_uartes); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(nrfx_uartes); i++) { if ((nrfx_uartes[i].p_reg->ENABLE & UARTE_ENABLE_ENABLE_Msk) == 0) { self->uarte = &nrfx_uartes[i]; break; @@ -165,15 +165,15 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_raise_ValueError(translate("All UART peripherals are in use")); } - if ( (tx == NULL) && (rx == NULL) ) { + if ((tx == NULL) && (rx == NULL)) { mp_raise_ValueError(translate("tx and rx cannot both be None")); } - if ( receiver_buffer_size == 0 ) { + if (receiver_buffer_size == 0) { mp_raise_ValueError(translate("Invalid buffer size")); } - if ( parity == BUSIO_UART_PARITY_ODD ) { + if (parity == BUSIO_UART_PARITY_ODD) { mp_raise_ValueError(translate("Odd parity is not supported")); } @@ -196,7 +196,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, _VERIFY_ERR(nrfx_uarte_init(self->uarte, &config, uart_callback_irq)); // Init buffer for rx - if ( rx != NULL ) { + if (rx != NULL) { // Initially allocate the UART's buffer in the long-lived part of the // heap. UARTs are generally long-lived objects, but the "make long- // lived" machinery is incapable of moving internal pointers like @@ -213,21 +213,21 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, claim_pin(rx); } - if ( tx != NULL ) { + if (tx != NULL) { self->tx_pin_number = tx->number; claim_pin(tx); } else { self->tx_pin_number = NO_PIN; } - if ( rts != NULL ) { + if (rts != NULL) { self->rts_pin_number = rts->number; claim_pin(rts); } else { self->rts_pin_number = NO_PIN; } - if ( cts != NULL ) { + if (cts != NULL) { self->cts_pin_number = cts->number; claim_pin(cts); } else { @@ -248,7 +248,7 @@ bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { } void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { - if ( !common_hal_busio_uart_deinited(self) ) { + if (!common_hal_busio_uart_deinited(self)) { nrfx_uarte_uninit(self->uarte); reset_pin_number(self->tx_pin_number); reset_pin_number(self->rx_pin_number); @@ -264,7 +264,7 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { // Read characters. size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t len, int *errcode) { - if ( nrf_uarte_rx_pin_get(self->uarte->p_reg) == NRF_UARTE_PSEL_DISCONNECTED ) { + if (nrf_uarte_rx_pin_get(self->uarte->p_reg) == NRF_UARTE_PSEL_DISCONNECTED) { mp_raise_ValueError(translate("No RX pin")); } @@ -278,10 +278,10 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t */ // Wait for all bytes received or timeout - while ( (ringbuf_num_filled(&self->ringbuf) < len) && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms) ) { + while ((ringbuf_num_filled(&self->ringbuf) < len) && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms)) { RUN_BACKGROUND_TASKS; // Allow user to break out of a timeout with a KeyboardInterrupt. - if ( mp_hal_is_interrupted() ) { + if (mp_hal_is_interrupted()) { return 0; } } @@ -297,7 +297,7 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t // the character that did not fit in ringbuf is in rx_char ringbuf_put_n(&self->ringbuf, &self->rx_char, 1); // keep receiving - (void) nrfx_uarte_rx(self->uarte, &self->rx_char, 1); + (void)nrfx_uarte_rx(self->uarte, &self->rx_char, 1); nrf_gpio_pin_write(self->rts_pin_number, false); self->rx_paused = false; } @@ -308,18 +308,20 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t } // Write characters. -size_t common_hal_busio_uart_write (busio_uart_obj_t *self, const uint8_t *data, size_t len, int *errcode) { - if ( nrf_uarte_tx_pin_get(self->uarte->p_reg) == NRF_UARTE_PSEL_DISCONNECTED ) { +size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, size_t len, int *errcode) { + if (nrf_uarte_tx_pin_get(self->uarte->p_reg) == NRF_UARTE_PSEL_DISCONNECTED) { mp_raise_ValueError(translate("No TX pin")); } - if ( len == 0 ) return 0; + if (len == 0) { + return 0; + } // EasyDMA can only access SRAM - uint8_t * tx_buf = (uint8_t*) data; - if ( !nrfx_is_in_ram(data) ) { + uint8_t *tx_buf = (uint8_t *)data; + if (!nrfx_is_in_ram(data)) { // TODO: If this is not too big, we could allocate it on the stack. - tx_buf = (uint8_t *) gc_alloc(len, false, false); + tx_buf = (uint8_t *)gc_alloc(len, false, false); memcpy(tx_buf, data, len); } @@ -328,11 +330,11 @@ size_t common_hal_busio_uart_write (busio_uart_obj_t *self, const uint8_t *data, (*errcode) = 0; // Wait for write to complete. - while ( nrfx_uarte_tx_in_progress(self->uarte) ) { + while (nrfx_uarte_tx_in_progress(self->uarte)) { RUN_BACKGROUND_TASKS; } - if ( !nrfx_is_in_ram(data) ) { + if (!nrfx_is_in_ram(data)) { gc_free(tx_buf); } @@ -349,7 +351,7 @@ void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrat } mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { - return (mp_float_t) (self->timeout_ms / 1000.0f); + return (mp_float_t)(self->timeout_ms / 1000.0f); } void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { diff --git a/ports/nrf/common-hal/digitalio/DigitalInOut.c b/ports/nrf/common-hal/digitalio/DigitalInOut.c index 2a72151b77..b42d7dc704 100644 --- a/ports/nrf/common-hal/digitalio/DigitalInOut.c +++ b/ports/nrf/common-hal/digitalio/DigitalInOut.c @@ -31,12 +31,12 @@ #include "nrf_gpio.h" void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { never_reset_pin_number(self->pin->number); } digitalinout_result_t common_hal_digitalio_digitalinout_construct( - digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { + digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { claim_pin(pin); self->pin = pin; @@ -60,14 +60,14 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self } void common_hal_digitalio_digitalinout_switch_to_input( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { nrf_gpio_cfg_input(self->pin->number, NRF_GPIO_PIN_NOPULL); common_hal_digitalio_digitalinout_set_pull(self, pull); } digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( - digitalio_digitalinout_obj_t *self, bool value, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, bool value, + digitalio_drive_mode_t drive_mode) { common_hal_digitalio_digitalinout_set_drive_mode(self, drive_mode); common_hal_digitalio_digitalinout_set_value(self, value); @@ -75,53 +75,53 @@ digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( } digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { return (nrf_gpio_pin_dir_get(self->pin->number) == NRF_GPIO_PIN_DIR_INPUT) ? DIRECTION_INPUT : DIRECTION_OUTPUT; } void common_hal_digitalio_digitalinout_set_value( - digitalio_digitalinout_obj_t *self, bool value) { + digitalio_digitalinout_obj_t *self, bool value) { nrf_gpio_pin_write(self->pin->number, value); } bool common_hal_digitalio_digitalinout_get_value( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { return (nrf_gpio_pin_dir_get(self->pin->number) == NRF_GPIO_PIN_DIR_INPUT) ? nrf_gpio_pin_read(self->pin->number) : nrf_gpio_pin_out_read(self->pin->number); } digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( - digitalio_digitalinout_obj_t *self, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, + digitalio_drive_mode_t drive_mode) { nrf_gpio_cfg(self->pin->number, - NRF_GPIO_PIN_DIR_OUTPUT, - NRF_GPIO_PIN_INPUT_DISCONNECT, - NRF_GPIO_PIN_NOPULL, - drive_mode == DRIVE_MODE_OPEN_DRAIN ? NRF_GPIO_PIN_H0D1 : NRF_GPIO_PIN_H0H1, - NRF_GPIO_PIN_NOSENSE); + NRF_GPIO_PIN_DIR_OUTPUT, + NRF_GPIO_PIN_INPUT_DISCONNECT, + NRF_GPIO_PIN_NOPULL, + drive_mode == DRIVE_MODE_OPEN_DRAIN ? NRF_GPIO_PIN_H0D1 : NRF_GPIO_PIN_H0H1, + NRF_GPIO_PIN_NOSENSE); return DIGITALINOUT_OK; } digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { uint32_t pin = self->pin->number; // Changes pin to be a relative pin number in port. NRF_GPIO_Type *reg = nrf_gpio_pin_port_decode(&pin); switch ((reg->PIN_CNF[pin] & GPIO_PIN_CNF_DRIVE_Msk) >> GPIO_PIN_CNF_DRIVE_Pos) { - case NRF_GPIO_PIN_S0D1: - case NRF_GPIO_PIN_H0D1: - return DRIVE_MODE_OPEN_DRAIN; - default: - return DRIVE_MODE_PUSH_PULL; + case NRF_GPIO_PIN_S0D1: + case NRF_GPIO_PIN_H0D1: + return DRIVE_MODE_OPEN_DRAIN; + default: + return DRIVE_MODE_PUSH_PULL; } } void common_hal_digitalio_digitalinout_set_pull( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { nrf_gpio_pin_pull_t hal_pull = NRF_GPIO_PIN_NOPULL; switch (pull) { @@ -140,7 +140,7 @@ void common_hal_digitalio_digitalinout_set_pull( } digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { uint32_t pin = self->pin->number; // Changes pin to be a relative pin number in port. NRF_GPIO_Type *reg = nrf_gpio_pin_port_decode(&pin); diff --git a/ports/nrf/common-hal/displayio/ParallelBus.c b/ports/nrf/common-hal/displayio/ParallelBus.c index 31ee1f48e4..1afa6c4d6b 100644 --- a/ports/nrf/common-hal/displayio/ParallelBus.c +++ b/ports/nrf/common-hal/displayio/ParallelBus.c @@ -33,9 +33,9 @@ #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/microcontroller/__init__.h" -void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* self, - const mcu_pin_obj_t* data0, const mcu_pin_obj_t* command, const mcu_pin_obj_t* chip_select, - const mcu_pin_obj_t* write, const mcu_pin_obj_t* read, const mcu_pin_obj_t* reset) { +void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t *self, + const mcu_pin_obj_t *data0, const mcu_pin_obj_t *command, const mcu_pin_obj_t *chip_select, + const mcu_pin_obj_t *write, const mcu_pin_obj_t *read, const mcu_pin_obj_t *reset) { uint8_t data_pin = data0->number; if (data_pin % 8 != 0) { @@ -59,7 +59,7 @@ void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* sel for (uint8_t i = 0; i < 8; i++) { g->PIN_CNF[data_pin + i] |= NRF_GPIO_PIN_S0S1 << GPIO_PIN_CNF_DRIVE_Pos; } - self->bus = ((uint8_t*) &g->OUT) + (data0->number % num_pins_in_port / 8); + self->bus = ((uint8_t *)&g->OUT) + (data0->number % num_pins_in_port / 8); self->command.base.type = &digitalio_digitalinout_type; common_hal_digitalio_digitalinout_construct(&self->command, command); @@ -106,7 +106,7 @@ void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* sel } } -void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) { +void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t *self) { for (uint8_t i = 0; i < 8; i++) { reset_pin_number(self->data0_pin + i); } @@ -119,7 +119,7 @@ void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) } bool common_hal_displayio_parallelbus_reset(mp_obj_t obj) { - displayio_parallelbus_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); if (self->reset.base.type == &mp_type_NoneType) { return false; } @@ -135,7 +135,7 @@ bool common_hal_displayio_parallelbus_bus_free(mp_obj_t obj) { } bool common_hal_displayio_parallelbus_begin_transaction(mp_obj_t obj) { - displayio_parallelbus_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_digitalio_digitalinout_set_value(&self->chip_select, false); return true; } @@ -143,10 +143,10 @@ bool common_hal_displayio_parallelbus_begin_transaction(mp_obj_t obj) { // This ignores chip_select behaviour because data is clocked in by the write line toggling. void common_hal_displayio_parallelbus_send(mp_obj_t obj, display_byte_type_t byte_type, display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { - displayio_parallelbus_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_digitalio_digitalinout_set_value(&self->command, byte_type == DISPLAY_DATA); - uint32_t* clear_write = (uint32_t*) &self->write_group->OUTCLR; - uint32_t* set_write = (uint32_t*) &self->write_group->OUTSET; + uint32_t *clear_write = (uint32_t *)&self->write_group->OUTCLR; + uint32_t *set_write = (uint32_t *)&self->write_group->OUTSET; uint32_t mask = self->write_mask; for (uint32_t i = 0; i < data_length; i++) { *clear_write = mask; @@ -156,6 +156,6 @@ void common_hal_displayio_parallelbus_send(mp_obj_t obj, display_byte_type_t byt } void common_hal_displayio_parallelbus_end_transaction(mp_obj_t obj) { - displayio_parallelbus_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_digitalio_digitalinout_set_value(&self->chip_select, true); } diff --git a/ports/nrf/common-hal/displayio/ParallelBus.h b/ports/nrf/common-hal/displayio/ParallelBus.h index 5c10d3d42a..30a0c7e61e 100644 --- a/ports/nrf/common-hal/displayio/ParallelBus.h +++ b/ports/nrf/common-hal/displayio/ParallelBus.h @@ -31,14 +31,14 @@ typedef struct { mp_obj_base_t base; - uint8_t* bus; + uint8_t *bus; digitalio_digitalinout_obj_t command; digitalio_digitalinout_obj_t chip_select; digitalio_digitalinout_obj_t reset; digitalio_digitalinout_obj_t write; digitalio_digitalinout_obj_t read; uint8_t data0_pin; - NRF_GPIO_Type* write_group; + NRF_GPIO_Type *write_group; uint32_t write_mask; } displayio_parallelbus_obj_t; diff --git a/ports/nrf/common-hal/microcontroller/Pin.c b/ports/nrf/common-hal/microcontroller/Pin.c index 23d6e23bfe..aea4f63eae 100644 --- a/ports/nrf/common-hal/microcontroller/Pin.c +++ b/ports/nrf/common-hal/microcontroller/Pin.c @@ -49,16 +49,16 @@ STATIC uint32_t claimed_pins[GPIO_COUNT]; STATIC uint32_t never_reset_pins[GPIO_COUNT]; STATIC void reset_speaker_enable_pin(void) { -#ifdef SPEAKER_ENABLE_PIN + #ifdef SPEAKER_ENABLE_PIN speaker_enable_in_use = false; nrf_gpio_cfg(SPEAKER_ENABLE_PIN->number, - NRF_GPIO_PIN_DIR_OUTPUT, - NRF_GPIO_PIN_INPUT_DISCONNECT, - NRF_GPIO_PIN_NOPULL, - NRF_GPIO_PIN_H0H1, - NRF_GPIO_PIN_NOSENSE); + NRF_GPIO_PIN_DIR_OUTPUT, + NRF_GPIO_PIN_INPUT_DISCONNECT, + NRF_GPIO_PIN_NOPULL, + NRF_GPIO_PIN_H0H1, + NRF_GPIO_PIN_NOSENSE); nrf_gpio_pin_write(SPEAKER_ENABLE_PIN->number, false); -#endif + #endif } void reset_all_pins(void) { @@ -129,18 +129,18 @@ void never_reset_pin_number(uint8_t pin_number) { never_reset_pins[nrf_pin_port(pin_number)] |= 1 << nrf_relative_pin_number(pin_number); } -void common_hal_never_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { never_reset_pin_number(pin->number); } -void common_hal_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_reset_pin(const mcu_pin_obj_t *pin) { if (pin == NULL) { return; } reset_pin_number(pin->number); } -void claim_pin(const mcu_pin_obj_t* pin) { +void claim_pin(const mcu_pin_obj_t *pin) { // Set bit in claimed_pins bitmask. claimed_pins[nrf_pin_port(pin->number)] |= 1 << nrf_relative_pin_number(pin->number); @@ -204,11 +204,11 @@ bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { } -uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t* pin) { +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin) { return pin->number; } -void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) { +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { claim_pin(pin); } diff --git a/ports/nrf/common-hal/microcontroller/Pin.h b/ports/nrf/common-hal/microcontroller/Pin.h index 735ed90cca..888ab6a8c4 100644 --- a/ports/nrf/common-hal/microcontroller/Pin.h +++ b/ports/nrf/common-hal/microcontroller/Pin.h @@ -43,7 +43,7 @@ void reset_all_pins(void); // reset_pin_number takes the pin number instead of the pointer so that objects don't // need to store a full pointer. void reset_pin_number(uint8_t pin); -void claim_pin(const mcu_pin_obj_t* pin); +void claim_pin(const mcu_pin_obj_t *pin); bool pin_number_is_free(uint8_t pin_number); void never_reset_pin_number(uint8_t pin_number); diff --git a/ports/nrf/common-hal/microcontroller/Processor.c b/ports/nrf/common-hal/microcontroller/Processor.c index ab5f29b5db..b31c4c12d7 100644 --- a/ports/nrf/common-hal/microcontroller/Processor.c +++ b/ports/nrf/common-hal/microcontroller/Processor.c @@ -40,10 +40,10 @@ float common_hal_mcu_processor_get_temperature(void) { int32_t temp = 0; -#ifdef BLUETOOTH_SD + #ifdef BLUETOOTH_SD uint8_t sd_en = 0; - (void) sd_softdevice_is_enabled(&sd_en); + (void)sd_softdevice_is_enabled(&sd_en); if (sd_en) { uint32_t err_code = sd_temp_get(&temp); @@ -52,9 +52,10 @@ float common_hal_mcu_processor_get_temperature(void) { } return temp / 4.0f; } // Fall through if SD not enabled. -#endif + #endif NRF_TEMP->TASKS_START = 1; - while (NRF_TEMP->EVENTS_DATARDY == 0) { } + while (NRF_TEMP->EVENTS_DATARDY == 0) { + } NRF_TEMP->EVENTS_DATARDY = 0; temp = NRF_TEMP->TEMP; NRF_TEMP->TASKS_STOP = 1; @@ -93,15 +94,18 @@ float common_hal_mcu_processor_get_voltage(void) { nrf_saadc_buffer_init(NRF_SAADC, &value, 1); nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START); - while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED) == 0) { } + while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED) == 0) { + } nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STARTED); nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_SAMPLE); - while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_END) == 0) { } + while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_END) == 0) { + } nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END); nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_STOP); - while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STOPPED) == 0) { } + while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STOPPED) == 0) { + } nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STOPPED); nrf_saadc_disable(NRF_SAADC); @@ -111,14 +115,14 @@ float common_hal_mcu_processor_get_voltage(void) { } // The ADC reading we expect if VDD is 3.3V. -#define NOMINAL_VALUE_3_3 (((3.3f/6)/0.6f)*16383) - return (value/NOMINAL_VALUE_3_3) * 3.3f; +#define NOMINAL_VALUE_3_3 (((3.3f / 6) / 0.6f) * 16383) + return (value / NOMINAL_VALUE_3_3) * 3.3f; } void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { - for (int i=0; i<2; i++) { - ((uint32_t*) raw_id)[i] = NRF_FICR->DEVICEID[i]; + for (int i = 0; i < 2; i++) { + ((uint32_t *)raw_id)[i] = NRF_FICR->DEVICEID[i]; } } diff --git a/ports/nrf/common-hal/microcontroller/__init__.c b/ports/nrf/common-hal/microcontroller/__init__.c index 06aac9409d..d84cc58455 100644 --- a/ports/nrf/common-hal/microcontroller/__init__.c +++ b/ports/nrf/common-hal/microcontroller/__init__.c @@ -82,12 +82,14 @@ void common_hal_mcu_enable_interrupts() { void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { enum { DFU_MAGIC_UF2_RESET = 0x57 }; - if(runmode == RUNMODE_BOOTLOADER) + if (runmode == RUNMODE_BOOTLOADER) { NRF_POWER->GPREGRET = DFU_MAGIC_UF2_RESET; - else + } else { NRF_POWER->GPREGRET = 0; - if(runmode == RUNMODE_SAFE_MODE) + } + if (runmode == RUNMODE_SAFE_MODE) { safe_mode_on_next_reset(PROGRAMMATIC_SAFE_MODE); + } } void common_hal_mcu_reset(void) { @@ -109,7 +111,7 @@ const nvm_bytearray_obj_t common_hal_mcu_nvm_obj = { .base = { .type = &nvm_bytearray_type, }, - .start_address = (uint8_t*) CIRCUITPY_INTERNAL_NVM_START_ADDR, + .start_address = (uint8_t *)CIRCUITPY_INTERNAL_NVM_START_ADDR, .len = CIRCUITPY_INTERNAL_NVM_SIZE, }; #endif @@ -126,67 +128,67 @@ watchdog_watchdogtimer_obj_t common_hal_mcu_watchdogtimer_obj = { #endif STATIC const mp_rom_map_elem_t mcu_pin_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR_P0_00), MP_ROM_PTR(&pin_P0_00) }, - { MP_ROM_QSTR(MP_QSTR_P0_01), MP_ROM_PTR(&pin_P0_01) }, - { MP_ROM_QSTR(MP_QSTR_P0_02), MP_ROM_PTR(&pin_P0_02) }, - { MP_ROM_QSTR(MP_QSTR_P0_03), MP_ROM_PTR(&pin_P0_03) }, - { MP_ROM_QSTR(MP_QSTR_P0_04), MP_ROM_PTR(&pin_P0_04) }, - { MP_ROM_QSTR(MP_QSTR_P0_05), MP_ROM_PTR(&pin_P0_05) }, - { MP_ROM_QSTR(MP_QSTR_P0_06), MP_ROM_PTR(&pin_P0_06) }, - { MP_ROM_QSTR(MP_QSTR_P0_07), MP_ROM_PTR(&pin_P0_07) }, - { MP_ROM_QSTR(MP_QSTR_P0_08), MP_ROM_PTR(&pin_P0_08) }, - { MP_ROM_QSTR(MP_QSTR_P0_09), MP_ROM_PTR(&pin_P0_09) }, - { MP_ROM_QSTR(MP_QSTR_P0_10), MP_ROM_PTR(&pin_P0_10) }, - { MP_ROM_QSTR(MP_QSTR_P0_11), MP_ROM_PTR(&pin_P0_11) }, - { MP_ROM_QSTR(MP_QSTR_P0_12), MP_ROM_PTR(&pin_P0_12) }, - { MP_ROM_QSTR(MP_QSTR_P0_13), MP_ROM_PTR(&pin_P0_13) }, - { MP_ROM_QSTR(MP_QSTR_P0_14), MP_ROM_PTR(&pin_P0_14) }, - { MP_ROM_QSTR(MP_QSTR_P0_15), MP_ROM_PTR(&pin_P0_15) }, - { MP_ROM_QSTR(MP_QSTR_P0_16), MP_ROM_PTR(&pin_P0_16) }, - { MP_ROM_QSTR(MP_QSTR_P0_17), MP_ROM_PTR(&pin_P0_17) }, - { MP_ROM_QSTR(MP_QSTR_P0_18), MP_ROM_PTR(&pin_P0_18) }, - { MP_ROM_QSTR(MP_QSTR_P0_19), MP_ROM_PTR(&pin_P0_19) }, - { MP_ROM_QSTR(MP_QSTR_P0_20), MP_ROM_PTR(&pin_P0_20) }, - { MP_ROM_QSTR(MP_QSTR_P0_21), MP_ROM_PTR(&pin_P0_21) }, - { MP_ROM_QSTR(MP_QSTR_P0_22), MP_ROM_PTR(&pin_P0_22) }, - { MP_ROM_QSTR(MP_QSTR_P0_23), MP_ROM_PTR(&pin_P0_23) }, - { MP_ROM_QSTR(MP_QSTR_P0_24), MP_ROM_PTR(&pin_P0_24) }, - { MP_ROM_QSTR(MP_QSTR_P0_25), MP_ROM_PTR(&pin_P0_25) }, - { MP_ROM_QSTR(MP_QSTR_P0_26), MP_ROM_PTR(&pin_P0_26) }, - { MP_ROM_QSTR(MP_QSTR_P0_27), MP_ROM_PTR(&pin_P0_27) }, - { MP_ROM_QSTR(MP_QSTR_P0_28), MP_ROM_PTR(&pin_P0_28) }, - { MP_ROM_QSTR(MP_QSTR_P0_29), MP_ROM_PTR(&pin_P0_29) }, - { MP_ROM_QSTR(MP_QSTR_P0_30), MP_ROM_PTR(&pin_P0_30) }, - { MP_ROM_QSTR(MP_QSTR_P0_31), MP_ROM_PTR(&pin_P0_31) }, -#ifdef NRF52840 - { MP_ROM_QSTR(MP_QSTR_P1_00), MP_ROM_PTR(&pin_P1_00) }, - { MP_ROM_QSTR(MP_QSTR_P1_01), MP_ROM_PTR(&pin_P1_01) }, - { MP_ROM_QSTR(MP_QSTR_P1_02), MP_ROM_PTR(&pin_P1_02) }, - { MP_ROM_QSTR(MP_QSTR_P1_03), MP_ROM_PTR(&pin_P1_03) }, - { MP_ROM_QSTR(MP_QSTR_P1_04), MP_ROM_PTR(&pin_P1_04) }, - { MP_ROM_QSTR(MP_QSTR_P1_05), MP_ROM_PTR(&pin_P1_05) }, - { MP_ROM_QSTR(MP_QSTR_P1_06), MP_ROM_PTR(&pin_P1_06) }, - { MP_ROM_QSTR(MP_QSTR_P1_07), MP_ROM_PTR(&pin_P1_07) }, - { MP_ROM_QSTR(MP_QSTR_P1_08), MP_ROM_PTR(&pin_P1_08) }, - { MP_ROM_QSTR(MP_QSTR_P1_09), MP_ROM_PTR(&pin_P1_09) }, - { MP_ROM_QSTR(MP_QSTR_P1_10), MP_ROM_PTR(&pin_P1_10) }, - { MP_ROM_QSTR(MP_QSTR_P1_11), MP_ROM_PTR(&pin_P1_11) }, - { MP_ROM_QSTR(MP_QSTR_P1_12), MP_ROM_PTR(&pin_P1_12) }, - { MP_ROM_QSTR(MP_QSTR_P1_13), MP_ROM_PTR(&pin_P1_13) }, - { MP_ROM_QSTR(MP_QSTR_P1_14), MP_ROM_PTR(&pin_P1_14) }, - { MP_ROM_QSTR(MP_QSTR_P1_15), MP_ROM_PTR(&pin_P1_15) }, -#endif -#ifdef NRF52833 - { MP_ROM_QSTR(MP_QSTR_P1_00), MP_ROM_PTR(&pin_P1_00) }, - { MP_ROM_QSTR(MP_QSTR_P1_01), MP_ROM_PTR(&pin_P1_01) }, - { MP_ROM_QSTR(MP_QSTR_P1_02), MP_ROM_PTR(&pin_P1_02) }, - { MP_ROM_QSTR(MP_QSTR_P1_03), MP_ROM_PTR(&pin_P1_03) }, - { MP_ROM_QSTR(MP_QSTR_P1_04), MP_ROM_PTR(&pin_P1_04) }, - { MP_ROM_QSTR(MP_QSTR_P1_05), MP_ROM_PTR(&pin_P1_05) }, - { MP_ROM_QSTR(MP_QSTR_P1_06), MP_ROM_PTR(&pin_P1_06) }, - { MP_ROM_QSTR(MP_QSTR_P1_07), MP_ROM_PTR(&pin_P1_07) }, - { MP_ROM_QSTR(MP_QSTR_P1_08), MP_ROM_PTR(&pin_P1_08) }, - { MP_ROM_QSTR(MP_QSTR_P1_09), MP_ROM_PTR(&pin_P1_09) }, -#endif + { MP_ROM_QSTR(MP_QSTR_P0_00), MP_ROM_PTR(&pin_P0_00) }, + { MP_ROM_QSTR(MP_QSTR_P0_01), MP_ROM_PTR(&pin_P0_01) }, + { MP_ROM_QSTR(MP_QSTR_P0_02), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_P0_03), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_P0_04), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_P0_05), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_P0_06), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_P0_07), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_P0_08), MP_ROM_PTR(&pin_P0_08) }, + { MP_ROM_QSTR(MP_QSTR_P0_09), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_P0_10), MP_ROM_PTR(&pin_P0_10) }, + { MP_ROM_QSTR(MP_QSTR_P0_11), MP_ROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_P0_12), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_P0_13), MP_ROM_PTR(&pin_P0_13) }, + { MP_ROM_QSTR(MP_QSTR_P0_14), MP_ROM_PTR(&pin_P0_14) }, + { MP_ROM_QSTR(MP_QSTR_P0_15), MP_ROM_PTR(&pin_P0_15) }, + { MP_ROM_QSTR(MP_QSTR_P0_16), MP_ROM_PTR(&pin_P0_16) }, + { MP_ROM_QSTR(MP_QSTR_P0_17), MP_ROM_PTR(&pin_P0_17) }, + { MP_ROM_QSTR(MP_QSTR_P0_18), MP_ROM_PTR(&pin_P0_18) }, + { MP_ROM_QSTR(MP_QSTR_P0_19), MP_ROM_PTR(&pin_P0_19) }, + { MP_ROM_QSTR(MP_QSTR_P0_20), MP_ROM_PTR(&pin_P0_20) }, + { MP_ROM_QSTR(MP_QSTR_P0_21), MP_ROM_PTR(&pin_P0_21) }, + { MP_ROM_QSTR(MP_QSTR_P0_22), MP_ROM_PTR(&pin_P0_22) }, + { MP_ROM_QSTR(MP_QSTR_P0_23), MP_ROM_PTR(&pin_P0_23) }, + { MP_ROM_QSTR(MP_QSTR_P0_24), MP_ROM_PTR(&pin_P0_24) }, + { MP_ROM_QSTR(MP_QSTR_P0_25), MP_ROM_PTR(&pin_P0_25) }, + { MP_ROM_QSTR(MP_QSTR_P0_26), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_P0_27), MP_ROM_PTR(&pin_P0_27) }, + { MP_ROM_QSTR(MP_QSTR_P0_28), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_P0_29), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_P0_30), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_P0_31), MP_ROM_PTR(&pin_P0_31) }, + #ifdef NRF52840 + { MP_ROM_QSTR(MP_QSTR_P1_00), MP_ROM_PTR(&pin_P1_00) }, + { MP_ROM_QSTR(MP_QSTR_P1_01), MP_ROM_PTR(&pin_P1_01) }, + { MP_ROM_QSTR(MP_QSTR_P1_02), MP_ROM_PTR(&pin_P1_02) }, + { MP_ROM_QSTR(MP_QSTR_P1_03), MP_ROM_PTR(&pin_P1_03) }, + { MP_ROM_QSTR(MP_QSTR_P1_04), MP_ROM_PTR(&pin_P1_04) }, + { MP_ROM_QSTR(MP_QSTR_P1_05), MP_ROM_PTR(&pin_P1_05) }, + { MP_ROM_QSTR(MP_QSTR_P1_06), MP_ROM_PTR(&pin_P1_06) }, + { MP_ROM_QSTR(MP_QSTR_P1_07), MP_ROM_PTR(&pin_P1_07) }, + { MP_ROM_QSTR(MP_QSTR_P1_08), MP_ROM_PTR(&pin_P1_08) }, + { MP_ROM_QSTR(MP_QSTR_P1_09), MP_ROM_PTR(&pin_P1_09) }, + { MP_ROM_QSTR(MP_QSTR_P1_10), MP_ROM_PTR(&pin_P1_10) }, + { MP_ROM_QSTR(MP_QSTR_P1_11), MP_ROM_PTR(&pin_P1_11) }, + { MP_ROM_QSTR(MP_QSTR_P1_12), MP_ROM_PTR(&pin_P1_12) }, + { MP_ROM_QSTR(MP_QSTR_P1_13), MP_ROM_PTR(&pin_P1_13) }, + { MP_ROM_QSTR(MP_QSTR_P1_14), MP_ROM_PTR(&pin_P1_14) }, + { MP_ROM_QSTR(MP_QSTR_P1_15), MP_ROM_PTR(&pin_P1_15) }, + #endif + #ifdef NRF52833 + { MP_ROM_QSTR(MP_QSTR_P1_00), MP_ROM_PTR(&pin_P1_00) }, + { MP_ROM_QSTR(MP_QSTR_P1_01), MP_ROM_PTR(&pin_P1_01) }, + { MP_ROM_QSTR(MP_QSTR_P1_02), MP_ROM_PTR(&pin_P1_02) }, + { MP_ROM_QSTR(MP_QSTR_P1_03), MP_ROM_PTR(&pin_P1_03) }, + { MP_ROM_QSTR(MP_QSTR_P1_04), MP_ROM_PTR(&pin_P1_04) }, + { MP_ROM_QSTR(MP_QSTR_P1_05), MP_ROM_PTR(&pin_P1_05) }, + { MP_ROM_QSTR(MP_QSTR_P1_06), MP_ROM_PTR(&pin_P1_06) }, + { MP_ROM_QSTR(MP_QSTR_P1_07), MP_ROM_PTR(&pin_P1_07) }, + { MP_ROM_QSTR(MP_QSTR_P1_08), MP_ROM_PTR(&pin_P1_08) }, + { MP_ROM_QSTR(MP_QSTR_P1_09), MP_ROM_PTR(&pin_P1_09) }, + #endif }; MP_DEFINE_CONST_DICT(mcu_pin_globals, mcu_pin_globals_table); diff --git a/ports/nrf/common-hal/neopixel_write/__init__.c b/ports/nrf/common-hal/neopixel_write/__init__.c index 8062937f4b..c8aa44cd12 100644 --- a/ports/nrf/common-hal/neopixel_write/__init__.c +++ b/ports/nrf/common-hal/neopixel_write/__init__.c @@ -53,8 +53,8 @@ // need to set the 15th bit on each register. // WS2812 (rev A) timing is 0.35 and 0.7us -//#define MAGIC_T0H 5UL | (0x8000) // 0.3125us -//#define MAGIC_T1H 12UL | (0x8000) // 0.75us +// #define MAGIC_T0H 5UL | (0x8000) // 0.3125us +// #define MAGIC_T1H 12UL | (0x8000) // 0.75us // WS2812B (rev B) timing is 0.4 and 0.8 us #define MAGIC_T0H 6UL | (0x8000) // 0.375us @@ -78,18 +78,18 @@ // ---------- END of Constants for cycle counter implementation -------- // find a free PWM device, which is not enabled and has no connected pins -static NRF_PWM_Type* find_free_pwm (void) { - NRF_PWM_Type* PWM[] = { - NRF_PWM0, NRF_PWM1, NRF_PWM2 -#ifdef NRF_PWM3 - , NRF_PWM3 -#endif +static NRF_PWM_Type *find_free_pwm(void) { + NRF_PWM_Type *PWM[] = { + NRF_PWM0, NRF_PWM1, NRF_PWM2 + #ifdef NRF_PWM3 + , NRF_PWM3 + #endif }; - for ( size_t device = 0; device < ARRAY_SIZE(PWM); device++ ) { - if ( (PWM[device]->ENABLE == 0) && - (PWM[device]->PSEL.OUT[0] & PWM_PSEL_OUT_CONNECT_Msk) && (PWM[device]->PSEL.OUT[1] & PWM_PSEL_OUT_CONNECT_Msk) && - (PWM[device]->PSEL.OUT[2] & PWM_PSEL_OUT_CONNECT_Msk) && (PWM[device]->PSEL.OUT[3] & PWM_PSEL_OUT_CONNECT_Msk) ) { + for (size_t device = 0; device < ARRAY_SIZE(PWM); device++) { + if ((PWM[device]->ENABLE == 0) && + (PWM[device]->PSEL.OUT[0] & PWM_PSEL_OUT_CONNECT_Msk) && (PWM[device]->PSEL.OUT[1] & PWM_PSEL_OUT_CONNECT_Msk) && + (PWM[device]->PSEL.OUT[2] & PWM_PSEL_OUT_CONNECT_Msk) && (PWM[device]->PSEL.OUT[3] & PWM_PSEL_OUT_CONNECT_Msk)) { return PWM[device]; } } @@ -106,7 +106,7 @@ void neopixel_write_reset(void) { uint64_t next_start_raw_ticks = 0; -void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout, uint8_t *pixels, uint32_t numBytes) { +void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, uint8_t *pixels, uint32_t numBytes) { // To support both the SoftDevice + Neopixels we use the EasyDMA // feature from the NRF52. However this technique implies to // generate a pattern and store it on the memory. The actual @@ -126,22 +126,22 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout // to handle larger NeoPixel rings without malloc'ing. #define STACK_PIXELS 24 uint32_t pattern_size = PATTERN_SIZE(numBytes); - uint16_t* pixels_pattern = NULL; + uint16_t *pixels_pattern = NULL; // Use the stack to store STACK_PIXEL's worth of PWM data. uint32_t to ensure alignment. // It is 3*STACK_PIXELS to handle RGB. // PATTERN_SIZE is a multiple of 4, so we don't need round up to make sure one_pixel is large enough. uint32_t stack_pixels[PATTERN_SIZE(3 * STACK_PIXELS) / sizeof(uint32_t)]; - NRF_PWM_Type* pwm = find_free_pwm(); + NRF_PWM_Type *pwm = find_free_pwm(); // only malloc if there is PWM device available - if ( pwm != NULL ) { + if (pwm != NULL) { if (pattern_size <= sizeof(stack_pixels)) { - pixels_pattern = (uint16_t *) stack_pixels; + pixels_pattern = (uint16_t *)stack_pixels; } else { uint8_t sd_en = 0; - (void) sd_softdevice_is_enabled(&sd_en); + (void)sd_softdevice_is_enabled(&sd_en); if (pixels_pattern_heap_size < pattern_size) { // Current heap buffer is too small. @@ -157,12 +157,12 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout // transmit. This takes a bunch of memory to do so raise an // exception if we can't. MP_STATE_VM(pixels_pattern_heap) = - (uint16_t *) m_realloc(MP_STATE_VM(pixels_pattern_heap), pattern_size); + (uint16_t *)m_realloc(MP_STATE_VM(pixels_pattern_heap), pattern_size); } else { // Might return NULL. MP_STATE_VM(pixels_pattern_heap) = // true means move if necessary. - (uint16_t *) m_realloc_maybe(MP_STATE_VM(pixels_pattern_heap), pattern_size, true); + (uint16_t *)m_realloc_maybe(MP_STATE_VM(pixels_pattern_heap), pattern_size, true); } if (MP_STATE_VM(pixels_pattern_heap)) { pixels_pattern_heap_size = pattern_size; @@ -175,17 +175,18 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout // Wait to make sure we don't append onto the last transmission. This should only be a tick or // two. - while (port_get_raw_ticks(NULL) < next_start_raw_ticks) {} + while (port_get_raw_ticks(NULL) < next_start_raw_ticks) { + } // Use the identified device to choose the implementation // If a PWM device is available and we have a buffer, use DMA. - if ( (pixels_pattern != NULL) && (pwm != NULL) ) { + if ((pixels_pattern != NULL) && (pwm != NULL)) { uint16_t pos = 0; // bit position - for ( uint16_t n = 0; n < numBytes; n++ ) { + for (uint16_t n = 0; n < numBytes; n++) { uint8_t pix = pixels[n]; - for ( uint8_t mask = 0x80; mask > 0; mask >>= 1 ) { + for (uint8_t mask = 0x80; mask > 0; mask >>= 1) { pixels_pattern[pos] = (pix & mask) ? MAGIC_T1H : MAGIC_T0H; pos++; } @@ -227,7 +228,7 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout // pwm->INTEN |= (PWM_INTEN_SEQEND0_Enabled<pin->number, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL} ); + nrf_pwm_pins_set(pwm, (uint32_t[]) {digitalinout->pin->number, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL}); // Enable the PWM nrf_pwm_enable(pwm); @@ -238,7 +239,7 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout nrf_pwm_task_trigger(pwm, NRF_PWM_TASK_SEQSTART0); // But we have to wait for the flag to be set. - while ( !nrf_pwm_event_check(pwm, NRF_PWM_EVENT_SEQEND0) ) { + while (!nrf_pwm_event_check(pwm, NRF_PWM_EVENT_SEQEND0)) { RUN_BACKGROUND_TASKS; } @@ -250,7 +251,7 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout // be selected on the next call. // TODO: Check if disabling the device causes performance issues. nrf_pwm_disable(pwm); - nrf_pwm_pins_set(pwm, (uint32_t[]) {0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL} ); + nrf_pwm_pins_set(pwm, (uint32_t[]) {0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL, 0xFFFFFFFFUL}); } // End of DMA implementation // --------------------------------------------------------------------- @@ -264,9 +265,9 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout __disable_irq(); uint32_t decoded_pin = digitalinout->pin->number; - NRF_GPIO_Type* port = nrf_gpio_pin_port_decode(&decoded_pin); + NRF_GPIO_Type *port = nrf_gpio_pin_port_decode(&decoded_pin); - uint32_t pinMask = ( 1UL << decoded_pin ); + uint32_t pinMask = (1UL << decoded_pin); uint32_t CYCLES_X00 = CYCLES_800; uint32_t CYCLES_X00_T1H = CYCLES_800_T1H; @@ -277,39 +278,43 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; // Tries to re-send the frame if is interrupted by the SoftDevice. - while ( 1 ) { + while (1) { uint8_t *p = pixels; uint32_t cycStart = DWT->CYCCNT; uint32_t cyc = 0; - for ( uint16_t n = 0; n < numBytes; n++ ) { + for (uint16_t n = 0; n < numBytes; n++) { uint8_t pix = *p++; - for ( uint8_t mask = 0x80; mask; mask >>= 1 ) { - while ( DWT->CYCCNT - cyc < CYCLES_X00 ) + for (uint8_t mask = 0x80; mask; mask >>= 1) { + while (DWT->CYCCNT - cyc < CYCLES_X00) { ; + } cyc = DWT->CYCCNT; port->OUTSET |= pinMask; - if ( pix & mask ) { - while ( DWT->CYCCNT - cyc < CYCLES_X00_T1H ) + if (pix & mask) { + while (DWT->CYCCNT - cyc < CYCLES_X00_T1H) { ; + } } else { - while ( DWT->CYCCNT - cyc < CYCLES_X00_T0H ) + while (DWT->CYCCNT - cyc < CYCLES_X00_T0H) { ; + } } port->OUTCLR |= pinMask; } } - while ( DWT->CYCCNT - cyc < CYCLES_X00 ) + while (DWT->CYCCNT - cyc < CYCLES_X00) { ; + } // If total time longer than 25%, resend the whole data. // Since we are likely to be interrupted by SoftDevice - if ( (DWT->CYCCNT - cycStart) < (8 * numBytes * ((CYCLES_X00 * 5) / 4)) ) { + if ((DWT->CYCCNT - cycStart) < (8 * numBytes * ((CYCLES_X00 * 5) / 4))) { break; } diff --git a/ports/nrf/common-hal/nvm/ByteArray.c b/ports/nrf/common-hal/nvm/ByteArray.c index 6b2f04a61b..5af2cc5636 100644 --- a/ports/nrf/common-hal/nvm/ByteArray.c +++ b/ports/nrf/common-hal/nvm/ByteArray.c @@ -51,9 +51,9 @@ static bool write_page(uint32_t page_addr, uint32_t offset, uint32_t len, uint8_ } bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, - uint32_t start_index, uint8_t* values, uint32_t len) { + uint32_t start_index, uint8_t *values, uint32_t len) { - uint32_t address = (uint32_t) self->start_address + start_index; + uint32_t address = (uint32_t)self->start_address + start_index; uint32_t offset = address % FLASH_PAGE_SIZE; uint32_t page_addr = address - offset; @@ -71,6 +71,6 @@ bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, } void common_hal_nvm_bytearray_get_bytes(nvm_bytearray_obj_t *self, - uint32_t start_index, uint32_t len, uint8_t* values) { + uint32_t start_index, uint32_t len, uint8_t *values) { memcpy(values, self->start_address + start_index, len); } diff --git a/ports/nrf/common-hal/nvm/ByteArray.h b/ports/nrf/common-hal/nvm/ByteArray.h index c048d55778..b3609a5925 100644 --- a/ports/nrf/common-hal/nvm/ByteArray.h +++ b/ports/nrf/common-hal/nvm/ByteArray.h @@ -31,7 +31,7 @@ typedef struct { mp_obj_base_t base; - uint8_t* start_address; + uint8_t *start_address; uint32_t len; } nvm_bytearray_obj_t; diff --git a/ports/nrf/common-hal/os/__init__.c b/ports/nrf/common-hal/os/__init__.c index b2ad00a5ca..5a0f10596c 100644 --- a/ports/nrf/common-hal/os/__init__.c +++ b/ports/nrf/common-hal/os/__init__.c @@ -55,16 +55,16 @@ STATIC MP_DEFINE_ATTRTUPLE( (mp_obj_t)&os_uname_info_release_obj, (mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj -); + ); mp_obj_t common_hal_os_uname(void) { return (mp_obj_t)&os_uname_info_obj; } bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { -#ifdef BLUETOOTH_SD + #ifdef BLUETOOTH_SD uint8_t sd_en = 0; - (void) sd_softdevice_is_enabled(&sd_en); + (void)sd_softdevice_is_enabled(&sd_en); if (sd_en) { while (length != 0) { @@ -84,13 +84,15 @@ bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { } return true; } -#endif + #endif nrf_rng_event_clear(NRF_RNG, NRF_RNG_EVENT_VALRDY); nrf_rng_task_trigger(NRF_RNG, NRF_RNG_TASK_START); for (uint32_t i = 0; i < length; i++) { - while (nrf_rng_event_check(NRF_RNG, NRF_RNG_EVENT_VALRDY) == 0); + while (nrf_rng_event_check(NRF_RNG, NRF_RNG_EVENT_VALRDY) == 0) { + ; + } nrf_rng_event_clear(NRF_RNG, NRF_RNG_EVENT_VALRDY); buffer[i] = nrf_rng_random_value_get(NRF_RNG); diff --git a/ports/nrf/common-hal/pulseio/PulseIn.c b/ports/nrf/common-hal/pulseio/PulseIn.c index ca44a20b4a..f8f877d965 100644 --- a/ports/nrf/common-hal/pulseio/PulseIn.c +++ b/ports/nrf/common-hal/pulseio/PulseIn.c @@ -40,7 +40,7 @@ #include "nrfx_gpiote.h" // obj array to map pin -> self since nrfx hide the mapping -static pulseio_pulsein_obj_t* _objs[GPIOTE_CH_NUM]; +static pulseio_pulsein_obj_t *_objs[GPIOTE_CH_NUM]; // A single timer is shared amongst all PulseIn objects as a common high speed clock reference. static uint8_t refcount = 0; @@ -57,9 +57,9 @@ static void timer_overflow_event_handler(nrf_timer_event_t event_type, void *p_c } // return index of the object in array -static int _find_pulsein_obj(pulseio_pulsein_obj_t* obj) { - for(size_t i = 0; i < NRFX_ARRAY_SIZE(_objs); i++ ) { - if ( _objs[i] == obj) { +static int _find_pulsein_obj(pulseio_pulsein_obj_t *obj) { + for (size_t i = 0; i < NRFX_ARRAY_SIZE(_objs); i++) { + if (_objs[i] == obj) { return i; } } @@ -72,22 +72,24 @@ static void _pulsein_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action uint32_t current_overflow = overflow_count; uint32_t current_count = nrfx_timer_capture(timer, 1); - pulseio_pulsein_obj_t* self = NULL; - for(size_t i = 0; i < NRFX_ARRAY_SIZE(_objs); i++ ) { - if ( _objs[i] && _objs[i]->pin == pin ) { + pulseio_pulsein_obj_t *self = NULL; + for (size_t i = 0; i < NRFX_ARRAY_SIZE(_objs); i++) { + if (_objs[i] && _objs[i]->pin == pin) { self = _objs[i]; break; } } - if ( !self ) return; + if (!self) { + return; + } if (self->first_edge) { // first pulse is opposite state from idle bool state = nrf_gpio_pin_read(self->pin); - if ( self->idle_state != state ) { + if (self->idle_state != state) { self->first_edge = false; } - }else { + } else { uint32_t total_diff = current_count + 0xffff * (current_overflow - self->last_overflow) - self->last_count; // Cap duration at 16 bits. @@ -110,7 +112,7 @@ static void _pulsein_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action } void pulsein_reset(void) { - if ( nrfx_gpiote_is_init() ) { + if (nrfx_gpiote_is_init()) { nrfx_gpiote_uninit(); } nrfx_gpiote_init(NRFX_GPIOTE_CONFIG_IRQ_PRIORITY); @@ -123,14 +125,14 @@ void pulsein_reset(void) { memset(_objs, 0, sizeof(_objs)); } -void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu_pin_obj_t* pin, uint16_t maxlen, bool idle_state) { +void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state) { int idx = _find_pulsein_obj(NULL); - if ( idx < 0 ) { + if (idx < 0) { mp_raise_NotImplementedError(NULL); } _objs[idx] = self; - self->buffer = (uint16_t *) m_malloc(maxlen * sizeof(uint16_t), false); + self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t), false); if (self->buffer == NULL) { mp_raise_msg_varg(&mp_type_MemoryError, translate("Failed to allocate RX buffer of %d bytes"), maxlen * sizeof(uint16_t)); } @@ -180,11 +182,11 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu nrfx_gpiote_in_event_enable(self->pin, true); } -bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t* self) { - return self->pin == NO_PIN; +bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self) { + return self->pin == NO_PIN; } -void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { if (common_hal_pulseio_pulsein_deinited(self)) { return; } @@ -194,7 +196,7 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { // mark local array as invalid int idx = _find_pulsein_obj(self); - if ( idx < 0 ) { + if (idx < 0) { mp_raise_NotImplementedError(NULL); } _objs[idx] = NULL; @@ -208,14 +210,14 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { } } -void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self) { nrfx_gpiote_in_event_disable(self->pin); self->paused = true; } -void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, uint16_t trigger_duration) { +void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t *self, uint16_t trigger_duration) { // Make sure we're paused. - if ( !self->paused ) { + if (!self->paused) { common_hal_pulseio_pulsein_pause(self); } @@ -246,21 +248,21 @@ void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, uint16_t tri nrfx_gpiote_in_event_enable(self->pin, true); } -void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t* self) { - if ( !self->paused ) { +void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t *self) { + if (!self->paused) { nrfx_gpiote_in_event_disable(self->pin); } self->start = 0; self->len = 0; - if ( !self->paused ) { + if (!self->paused) { nrfx_gpiote_in_event_enable(self->pin, true); } } -uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, int16_t index) { - if ( !self->paused ) { +uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t *self, int16_t index) { + if (!self->paused) { nrfx_gpiote_in_event_disable(self->pin); } @@ -268,26 +270,26 @@ uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, int16_ index += self->len; } if (index < 0 || index >= self->len) { - if ( !self->paused ) { + if (!self->paused) { nrfx_gpiote_in_event_enable(self->pin, true); } mp_raise_IndexError_varg(translate("%q index out of range"), MP_QSTR_PulseIn); } uint16_t value = self->buffer[(self->start + index) % self->maxlen]; - if ( !self->paused ) { + if (!self->paused) { nrfx_gpiote_in_event_enable(self->pin, true); } return value; } -uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t *self) { if (self->len == 0) { mp_raise_IndexError_varg(translate("pop from empty %q"), MP_QSTR_PulseIn); } - if ( !self->paused ) { + if (!self->paused) { nrfx_gpiote_in_event_disable(self->pin); } @@ -295,21 +297,21 @@ uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { self->start = (self->start + 1) % self->maxlen; self->len--; - if ( !self->paused ) { + if (!self->paused) { nrfx_gpiote_in_event_enable(self->pin, true); } return value; } -uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t *self) { return self->maxlen; } -bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t* self) { +bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t *self) { return self->paused; } -uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t *self) { return self->len; } diff --git a/ports/nrf/common-hal/pulseio/PulseIn.h b/ports/nrf/common-hal/pulseio/PulseIn.h index da5263ac9c..cdd0e66909 100644 --- a/ports/nrf/common-hal/pulseio/PulseIn.h +++ b/ports/nrf/common-hal/pulseio/PulseIn.h @@ -39,7 +39,7 @@ typedef struct { bool paused; volatile bool first_edge; - uint16_t* buffer; + uint16_t *buffer; uint16_t maxlen; volatile uint16_t start; diff --git a/ports/nrf/common-hal/pulseio/PulseOut.c b/ports/nrf/common-hal/pulseio/PulseOut.c index f40dbea5c8..17f498ba8e 100644 --- a/ports/nrf/common-hal/pulseio/PulseOut.c +++ b/ports/nrf/common-hal/pulseio/PulseOut.c @@ -66,7 +66,7 @@ static void start_timer(void) { } static void pulseout_event_handler(nrf_timer_event_t event_type, void *p_context) { - pulseio_pulseout_obj_t *pulseout = (pulseio_pulseout_obj_t*) p_context; + pulseio_pulseout_obj_t *pulseout = (pulseio_pulseout_obj_t *)p_context; if (event_type != NRF_TIMER_EVENT_COMPARE0) { // Spurious event. return; @@ -99,11 +99,11 @@ void pulseout_reset() { refcount = 0; } -void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, - const pwmio_pwmout_obj_t* carrier, - const mcu_pin_obj_t* pin, - uint32_t frequency, - uint16_t duty_cycle) { +void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, + const pwmio_pwmout_obj_t *carrier, + const mcu_pin_obj_t *pin, + uint32_t frequency, + uint16_t duty_cycle) { if (!carrier || pin || frequency) { mp_raise_NotImplementedError(translate("Port does not accept pins or frequency. Construct and pass a PWMOut Carrier instead")); } @@ -128,11 +128,11 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, turn_off(self); } -bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t* self) { +bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t *self) { return self->pwmout == NULL; } -void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { +void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { if (common_hal_pulseio_pulseout_deinited(self)) { return; } @@ -145,7 +145,7 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { } } -void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pulses, uint16_t length) { +void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pulses, uint16_t length) { pulse_array = pulses; pulse_array_index = 0; pulse_array_length = length; @@ -156,7 +156,7 @@ void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pu // Count up to the next given value. start_timer(); - while(pulse_array_index < length) { + while (pulse_array_index < length) { // Do other things while we wait. The interrupts will handle sending the // signal. RUN_BACKGROUND_TASKS; diff --git a/ports/nrf/common-hal/pwmio/PWMOut.c b/ports/nrf/common-hal/pwmio/PWMOut.c index a9d8964883..e49214631b 100644 --- a/ports/nrf/common-hal/pwmio/PWMOut.c +++ b/ports/nrf/common-hal/pwmio/PWMOut.c @@ -36,19 +36,19 @@ #define PWM_MAX_FREQ (16000000) -STATIC NRF_PWM_Type* pwms[] = { -#if NRFX_CHECK(NRFX_PWM0_ENABLED) +STATIC NRF_PWM_Type *pwms[] = { + #if NRFX_CHECK(NRFX_PWM0_ENABLED) NRF_PWM0, -#endif -#if NRFX_CHECK(NRFX_PWM1_ENABLED) + #endif + #if NRFX_CHECK(NRFX_PWM1_ENABLED) NRF_PWM1, -#endif -#if NRFX_CHECK(NRFX_PWM2_ENABLED) + #endif + #if NRFX_CHECK(NRFX_PWM2_ENABLED) NRF_PWM2, -#endif -#if NRFX_CHECK(NRFX_PWM3_ENABLED) + #endif + #if NRFX_CHECK(NRFX_PWM3_ENABLED) NRF_PWM3, -#endif + #endif }; #define CHANNELS_PER_PWM 4 @@ -58,14 +58,17 @@ STATIC uint16_t pwm_seq[MP_ARRAY_SIZE(pwms)][CHANNELS_PER_PWM]; static uint8_t never_reset_pwm[MP_ARRAY_SIZE(pwms)]; STATIC int pwm_idx(NRF_PWM_Type *pwm) { - for(size_t i=0; i < MP_ARRAY_SIZE(pwms); i++) - if(pwms[i] == pwm) return i; + for (size_t i = 0; i < MP_ARRAY_SIZE(pwms); i++) { + if (pwms[i] == pwm) { + return i; + } + } return -1; } void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - for(size_t i=0; i < MP_ARRAY_SIZE(pwms); i++) { - NRF_PWM_Type* pwm = pwms[i]; + for (size_t i = 0; i < MP_ARRAY_SIZE(pwms); i++) { + NRF_PWM_Type *pwm = pwms[i]; if (pwm == self->pwm) { never_reset_pwm[i] += 1; } @@ -75,8 +78,8 @@ void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { } void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { - for(size_t i=0; i < MP_ARRAY_SIZE(pwms); i++) { - NRF_PWM_Type* pwm = pwms[i]; + for (size_t i = 0; i < MP_ARRAY_SIZE(pwms); i++) { + NRF_PWM_Type *pwm = pwms[i]; if (pwm == self->pwm) { never_reset_pwm[i] -= 1; } @@ -84,32 +87,32 @@ void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { } void reset_single_pwmout(uint8_t i) { - NRF_PWM_Type* pwm = pwms[i]; + NRF_PWM_Type *pwm = pwms[i]; - pwm->ENABLE = 0; - pwm->MODE = PWM_MODE_UPDOWN_Up; - pwm->DECODER = PWM_DECODER_LOAD_Individual; - pwm->LOOP = 0; - pwm->PRESCALER = PWM_PRESCALER_PRESCALER_DIV_1; // default is 500 hz - pwm->COUNTERTOP = (PWM_MAX_FREQ/500); // default is 500 hz + pwm->ENABLE = 0; + pwm->MODE = PWM_MODE_UPDOWN_Up; + pwm->DECODER = PWM_DECODER_LOAD_Individual; + pwm->LOOP = 0; + pwm->PRESCALER = PWM_PRESCALER_PRESCALER_DIV_1; // default is 500 hz + pwm->COUNTERTOP = (PWM_MAX_FREQ / 500); // default is 500 hz - pwm->SEQ[0].PTR = (uint32_t) pwm_seq[i]; - pwm->SEQ[0].CNT = CHANNELS_PER_PWM; // default mode is Individual --> count must be 4 - pwm->SEQ[0].REFRESH = 0; + pwm->SEQ[0].PTR = (uint32_t)pwm_seq[i]; + pwm->SEQ[0].CNT = CHANNELS_PER_PWM; // default mode is Individual --> count must be 4 + pwm->SEQ[0].REFRESH = 0; pwm->SEQ[0].ENDDELAY = 0; - pwm->SEQ[1].PTR = 0; - pwm->SEQ[1].CNT = 0; - pwm->SEQ[1].REFRESH = 0; + pwm->SEQ[1].PTR = 0; + pwm->SEQ[1].CNT = 0; + pwm->SEQ[1].REFRESH = 0; pwm->SEQ[1].ENDDELAY = 0; - for(int ch =0; ch < CHANNELS_PER_PWM; ch++) { + for (int ch = 0; ch < CHANNELS_PER_PWM; ch++) { pwm_seq[i][ch] = (1 << 15); // polarity = 0 } } void pwmout_reset(void) { - for(size_t i=0; i < MP_ARRAY_SIZE(pwms); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(pwms); i++) { if (never_reset_pwm[i] > 0) { continue; } @@ -143,8 +146,8 @@ bool convert_frequency(uint32_t frequency, uint16_t *countertop, nrf_pwm_clk_t * static IRQn_Type pwm_irqs[4] = {PWM0_IRQn, PWM1_IRQn, PWM2_IRQn, PWM3_IRQn}; NRF_PWM_Type *pwmout_allocate(uint16_t countertop, nrf_pwm_clk_t base_clock, - bool variable_frequency, int8_t *channel_out, bool *pwm_already_in_use_out, - IRQn_Type* irq) { + bool variable_frequency, int8_t *channel_out, bool *pwm_already_in_use_out, + IRQn_Type *irq) { for (size_t pwm_index = 0; pwm_index < MP_ARRAY_SIZE(pwms); pwm_index++) { NRF_PWM_Type *pwm = pwms[pwm_index]; bool pwm_already_in_use = pwm->ENABLE & PWM_ENABLE_ENABLE_Msk; @@ -194,7 +197,7 @@ void pwmout_free_channel(NRF_PWM_Type *pwm, int8_t channel) { // Disconnect pin from channel. pwm->PSEL.OUT[channel] = 0xFFFFFFFF; - for(int i=0; i < CHANNELS_PER_PWM; i++) { + for (int i = 0; i < CHANNELS_PER_PWM; i++) { if (pwm->PSEL.OUT[i] != 0xFFFFFFFF) { // Some channel is still being used, so don't disable. return; @@ -204,11 +207,11 @@ void pwmout_free_channel(NRF_PWM_Type *pwm, int8_t channel) { nrf_pwm_disable(pwm); } -pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, - const mcu_pin_obj_t* pin, - uint16_t duty, - uint32_t frequency, - bool variable_frequency) { +pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, + const mcu_pin_obj_t *pin, + uint16_t duty, + uint32_t frequency, + bool variable_frequency) { // We don't use the nrfx driver here because we want to dynamically allocate channels // as needed in an already-enabled PWM. @@ -255,18 +258,18 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, return PWMOUT_OK; } -bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { return self->pwm == NULL; } -void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { +void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { if (common_hal_pwmio_pwmout_deinited(self)) { return; } nrf_gpio_cfg_default(self->pin_number); - NRF_PWM_Type* pwm = self->pwm; + NRF_PWM_Type *pwm = self->pwm; self->pwm = NULL; pwmout_free_channel(pwm, self->channel); @@ -275,20 +278,20 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { self->pin_number = NO_PIN; } -void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t* self, uint16_t duty_cycle) { +void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty_cycle) { self->duty_cycle = duty_cycle; - uint16_t* p_value = ((uint16_t*)self->pwm->SEQ[0].PTR) + self->channel; + uint16_t *p_value = ((uint16_t *)self->pwm->SEQ[0].PTR) + self->channel; *p_value = ((duty_cycle * self->pwm->COUNTERTOP) / 0xFFFF) | (1 << 15); self->pwm->TASKS_SEQSTART[0] = 1; } -uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t* self) { +uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t *self) { return self->duty_cycle; } -void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t frequency) { +void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, uint32_t frequency) { // COUNTERTOP is 3..32767, so highest available frequency is PWM_MAX_FREQ / 3. uint16_t countertop; nrf_pwm_clk_t base_clock; @@ -303,10 +306,10 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t fr common_hal_pwmio_pwmout_set_duty_cycle(self, self->duty_cycle); } -uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t* self) { +uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t *self) { return self->frequency; } -bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *self) { return self->variable_frequency; } diff --git a/ports/nrf/common-hal/pwmio/PWMOut.h b/ports/nrf/common-hal/pwmio/PWMOut.h index e910baa765..f96c5e4f81 100644 --- a/ports/nrf/common-hal/pwmio/PWMOut.h +++ b/ports/nrf/common-hal/pwmio/PWMOut.h @@ -32,10 +32,10 @@ typedef struct { mp_obj_base_t base; - NRF_PWM_Type* pwm; + NRF_PWM_Type *pwm; uint8_t pin_number; - uint8_t channel: 7; - bool variable_frequency: 1; + uint8_t channel : 7; + bool variable_frequency : 1; uint16_t duty_cycle; uint32_t frequency; } pwmio_pwmout_obj_t; diff --git a/ports/nrf/common-hal/rgbmatrix/RGBMatrix.c b/ports/nrf/common-hal/rgbmatrix/RGBMatrix.c index d8289f56ff..238fee9764 100644 --- a/ports/nrf/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/nrf/common-hal/rgbmatrix/RGBMatrix.c @@ -43,7 +43,7 @@ static void rgbmatrix_event_handler(nrf_timer_event_t event_type, void *p_contex _PM_IRQ_HANDLER(); } -void common_hal_rgbmatrix_timer_enable(void* ptr) { +void common_hal_rgbmatrix_timer_enable(void *ptr) { nrfx_timer_t *timer = nrf_peripherals_timer_from_reg(ptr); static const nrfx_timer_config_t timer_config = { .frequency = NRF_TIMER_FREQ_16MHz, @@ -55,12 +55,12 @@ void common_hal_rgbmatrix_timer_enable(void* ptr) { nrfx_timer_init(timer, &timer_config, &rgbmatrix_event_handler); } -void common_hal_rgbmatrix_timer_disable(void* ptr) { +void common_hal_rgbmatrix_timer_disable(void *ptr) { nrfx_timer_t *timer = nrf_peripherals_timer_from_reg(ptr); nrfx_timer_uninit(timer); } -void common_hal_rgbmatrix_timer_free(void* ptr) { +void common_hal_rgbmatrix_timer_free(void *ptr) { nrfx_timer_t *timer = nrf_peripherals_timer_from_reg(ptr); nrf_peripherals_free_timer(timer); } diff --git a/ports/nrf/common-hal/rgbmatrix/RGBMatrix.h b/ports/nrf/common-hal/rgbmatrix/RGBMatrix.h index 6cf7354fc2..8101b9c6bc 100644 --- a/ports/nrf/common-hal/rgbmatrix/RGBMatrix.h +++ b/ports/nrf/common-hal/rgbmatrix/RGBMatrix.h @@ -30,8 +30,8 @@ #include "shared-module/rgbmatrix/RGBMatrix.h" void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self); -void common_hal_rgbmatrix_timer_enable(void*); -void common_hal_rgbmatrix_timer_disable(void*); -void common_hal_rgbmatrix_timer_free(void*); +void common_hal_rgbmatrix_timer_enable(void *); +void common_hal_rgbmatrix_timer_disable(void *); +void common_hal_rgbmatrix_timer_free(void *); #endif diff --git a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c index 28f563da6f..ef5e9ee5ae 100644 --- a/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/nrf/common-hal/rotaryio/IncrementalEncoder.c @@ -36,15 +36,20 @@ static rotaryio_incrementalencoder_obj_t *_objs[NUMBER_OF_PINS]; static void _intr_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action) { rotaryio_incrementalencoder_obj_t *self = _objs[pin]; - if (!self) return; + if (!self) { + return; + } // reads a state 0 .. 3 *in order*. uint8_t new_state = nrf_gpio_pin_read(self->pin_a); new_state = (new_state << 1) + (new_state ^ nrf_gpio_pin_read(self->pin_b)); uint8_t change = (new_state - self->state) & 0x03; - if (change == 1) self->quarter++; - else if (change == 3) self->quarter--; + if (change == 1) { + self->quarter++; + } else if (change == 3) { + self->quarter--; + } // ignore other state transitions self->state = new_state; @@ -60,8 +65,8 @@ static void _intr_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action) { } } -void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t* self, - const mcu_pin_obj_t* pin_a, const mcu_pin_obj_t* pin_b) { +void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self, + const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b) { self->pin_a = pin_a->number; self->pin_b = pin_b->number; @@ -85,11 +90,11 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode claim_pin(pin_b); } -bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t* self) { +bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t *self) { return self->pin_a == NO_PIN; } -void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t* self) { +void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t *self) { if (common_hal_rotaryio_incrementalencoder_deinited(self)) { return; } @@ -106,11 +111,11 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o self->pin_b = NO_PIN; } -mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t* self) { +mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self) { return self->position; } -void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t* self, - mp_int_t new_position) { +void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, + mp_int_t new_position) { self->position = new_position; } diff --git a/ports/nrf/common-hal/rtc/RTC.c b/ports/nrf/common-hal/rtc/RTC.c index 93ba007c83..cdffe094a4 100644 --- a/ports/nrf/common-hal/rtc/RTC.c +++ b/ports/nrf/common-hal/rtc/RTC.c @@ -49,8 +49,9 @@ __attribute__((section(".uninitialized"))) static uint32_t rtc_offset[3]; void common_hal_rtc_init(void) { // If the prefix and suffix are not valid, zero-initialize the RTC offset. - if ((rtc_offset[0] != RTC_OFFSET_CHECK_PREFIX) || (rtc_offset[2] != RTC_OFFSET_CHECK_SUFFIX)) + if ((rtc_offset[0] != RTC_OFFSET_CHECK_PREFIX) || (rtc_offset[2] != RTC_OFFSET_CHECK_SUFFIX)) { rtc_offset[1] = 0; + } } void common_hal_rtc_get_time(timeutils_struct_time_t *tm) { @@ -62,7 +63,7 @@ void common_hal_rtc_set_time(timeutils_struct_time_t *tm) { uint64_t ticks_s = port_get_raw_ticks(NULL) / 1024; uint32_t epoch_s = timeutils_seconds_since_2000( tm->tm_year, tm->tm_mon, tm->tm_mday, tm->tm_hour, tm->tm_min, tm->tm_sec - ); + ); rtc_offset[1] = epoch_s - ticks_s; // Set the prefix and suffix in order to indicate the time is valid. This diff --git a/ports/nrf/common-hal/supervisor/Runtime.c b/ports/nrf/common-hal/supervisor/Runtime.c old mode 100755 new mode 100644 index a24e86cdf0..f827651781 --- a/ports/nrf/common-hal/supervisor/Runtime.c +++ b/ports/nrf/common-hal/supervisor/Runtime.c @@ -29,9 +29,9 @@ #include "supervisor/serial.h" bool common_hal_supervisor_runtime_get_serial_connected(void) { - return (bool) serial_connected(); + return (bool)serial_connected(); } bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); + return (bool)serial_bytes_available(); } diff --git a/ports/nrf/common-hal/watchdog/WatchDogTimer.c b/ports/nrf/common-hal/watchdog/WatchDogTimer.c index 539b43e762..3423d3466b 100644 --- a/ports/nrf/common-hal/watchdog/WatchDogTimer.c +++ b/ports/nrf/common-hal/watchdog/WatchDogTimer.c @@ -62,11 +62,11 @@ STATIC void watchdogtimer_timer_event_handler(nrf_timer_event_t event_type, void self->mode = WATCHDOGMODE_NONE; mp_obj_exception_clear_traceback(MP_OBJ_FROM_PTR(&mp_watchdog_timeout_exception)); MP_STATE_VM(mp_pending_exception) = &mp_watchdog_timeout_exception; -#if MICROPY_ENABLE_SCHEDULER + #if MICROPY_ENABLE_SCHEDULER if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) { MP_STATE_VM(sched_state) = MP_SCHED_PENDING; } -#endif + #endif } static void timer_free(void) { diff --git a/ports/nrf/common-hal/watchdog/WatchDogTimer.h b/ports/nrf/common-hal/watchdog/WatchDogTimer.h index 8d6df934e4..1ff654c321 100644 --- a/ports/nrf/common-hal/watchdog/WatchDogTimer.h +++ b/ports/nrf/common-hal/watchdog/WatchDogTimer.h @@ -32,9 +32,9 @@ #include "shared-bindings/watchdog/WatchDogTimer.h" struct _watchdog_watchdogtimer_obj_t { - mp_obj_base_t base; - mp_float_t timeout; - watchdog_watchdogmode_t mode; + mp_obj_base_t base; + mp_float_t timeout; + watchdog_watchdogmode_t mode; }; // This needs to be called in order to disable the watchdog if it's set to diff --git a/ports/nrf/device/nrf52/startup_nrf52.c b/ports/nrf/device/nrf52/startup_nrf52.c index 614b8c2d32..81eaa4e329 100644 --- a/ports/nrf/device/nrf52/startup_nrf52.c +++ b/ports/nrf/device/nrf52/startup_nrf52.c @@ -41,19 +41,21 @@ extern void _start(void) __attribute__((noreturn)); extern void SystemInit(void); void Default_Handler(void) { - while (1); + while (1) { + ; + } } void Reset_Handler(void) { - uint32_t * p_src = &_sidata; - uint32_t * p_dest = &_sdata; + uint32_t *p_src = &_sidata; + uint32_t *p_dest = &_sdata; while (p_dest < &_edata) { - *p_dest++ = *p_src++; + *p_dest++ = *p_src++; } - uint32_t * p_bss = &_sbss; - uint32_t * p_bss_end = &_ebss; + uint32_t *p_bss = &_sbss; + uint32_t *p_bss_end = &_ebss; while (p_bss < p_bss_end) { *p_bss++ = 0ul; } @@ -62,55 +64,55 @@ void Reset_Handler(void) { _start(); } -void NMI_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void HardFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void MemoryManagement_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void BusFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void UsageFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SVC_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void DebugMon_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PendSV_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SysTick_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); +void NMI_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void HardFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void MemoryManagement_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void BusFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void UsageFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SVC_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void DebugMon_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PendSV_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SysTick_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); -void POWER_CLOCK_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RADIO_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void UARTE0_UART0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void NFCT_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void GPIOTE_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SAADC_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TEMP_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RNG_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void ECB_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void CCM_AAR_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void WDT_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void QDEC_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void COMP_LPCOMP_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI0_EGU0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI1_EGU1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI2_EGU2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI3_EGU3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI4_EGU4_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI5_EGU5_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER4_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PDM_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void MWU_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM2_SPIS2_SPI2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void I2S_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); +void POWER_CLOCK_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RADIO_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void UARTE0_UART0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void NFCT_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void GPIOTE_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SAADC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TEMP_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RNG_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void ECB_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void CCM_AAR_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void WDT_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void QDEC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void COMP_LPCOMP_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI0_EGU0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI1_EGU1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI2_EGU2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI3_EGU3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI4_EGU4_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI5_EGU5_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER4_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PDM_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void MWU_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM2_SPIS2_SPI2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void I2S_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); const func __Vectors[] __attribute__ ((section(".isr_vector"))) = { - (func)&_estack, + (func) & _estack, Reset_Handler, NMI_Handler, HardFault_Handler, diff --git a/ports/nrf/device/nrf52/startup_nrf52833.c b/ports/nrf/device/nrf52/startup_nrf52833.c index ad875dceed..ad60839520 100644 --- a/ports/nrf/device/nrf52/startup_nrf52833.c +++ b/ports/nrf/device/nrf52/startup_nrf52833.c @@ -41,19 +41,21 @@ extern void _start(void) __attribute__((noreturn)); extern void SystemInit(void); void Default_Handler(void) { - while (1); + while (1) { + ; + } } void Reset_Handler(void) { - uint32_t * p_src = &_sidata; - uint32_t * p_dest = &_sdata; + uint32_t *p_src = &_sidata; + uint32_t *p_dest = &_sdata; while (p_dest < &_edata) { - *p_dest++ = *p_src++; + *p_dest++ = *p_src++; } - uint32_t * p_bss = &_sbss; - uint32_t * p_bss_end = &_ebss; + uint32_t *p_bss = &_sbss; + uint32_t *p_bss_end = &_ebss; while (p_bss < p_bss_end) { *p_bss++ = 0ul; } @@ -62,60 +64,60 @@ void Reset_Handler(void) { _start(); } -void NMI_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void HardFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void MemoryManagement_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void BusFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void UsageFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SVC_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void DebugMon_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PendSV_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SysTick_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); +void NMI_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void HardFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void MemoryManagement_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void BusFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void UsageFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SVC_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void DebugMon_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PendSV_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SysTick_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); -void POWER_CLOCK_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RADIO_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void UARTE0_UART0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void NFCT_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void GPIOTE_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SAADC_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TEMP_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RNG_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void ECB_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void CCM_AAR_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void WDT_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void QDEC_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void COMP_LPCOMP_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI0_EGU0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI1_EGU1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI2_EGU2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI3_EGU3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI4_EGU4_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI5_EGU5_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER4_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PDM_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void MWU_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM2_SPIS2_SPI2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void I2S_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void FPU_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void USBD_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void UARTE1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); +void POWER_CLOCK_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RADIO_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void UARTE0_UART0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void NFCT_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void GPIOTE_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SAADC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TEMP_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RNG_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void ECB_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void CCM_AAR_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void WDT_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void QDEC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void COMP_LPCOMP_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI0_EGU0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI1_EGU1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI2_EGU2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI3_EGU3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI4_EGU4_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI5_EGU5_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER4_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PDM_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void MWU_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM2_SPIS2_SPI2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void I2S_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void FPU_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void USBD_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void UARTE1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); const func __Vectors[] __attribute__ ((used, section(".isr_vector"))) = { - (func)&_estack, + (func) & _estack, Reset_Handler, NMI_Handler, HardFault_Handler, diff --git a/ports/nrf/device/nrf52/startup_nrf52840.c b/ports/nrf/device/nrf52/startup_nrf52840.c index 8e1c360128..67380303d6 100644 --- a/ports/nrf/device/nrf52/startup_nrf52840.c +++ b/ports/nrf/device/nrf52/startup_nrf52840.c @@ -41,19 +41,21 @@ extern void _start(void) __attribute__((noreturn)); extern void SystemInit(void); void Default_Handler(void) { - while (1); + while (1) { + ; + } } void Reset_Handler(void) { - uint32_t * p_src = &_sidata; - uint32_t * p_dest = &_sdata; + uint32_t *p_src = &_sidata; + uint32_t *p_dest = &_sdata; while (p_dest < &_edata) { - *p_dest++ = *p_src++; + *p_dest++ = *p_src++; } - uint32_t * p_bss = &_sbss; - uint32_t * p_bss_end = &_ebss; + uint32_t *p_bss = &_sbss; + uint32_t *p_bss_end = &_ebss; while (p_bss < p_bss_end) { *p_bss++ = 0ul; } @@ -62,62 +64,62 @@ void Reset_Handler(void) { _start(); } -void NMI_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void HardFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void MemoryManagement_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void BusFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void UsageFault_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SVC_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void DebugMon_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PendSV_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SysTick_Handler (void) __attribute__ ((weak, alias("Default_Handler"))); +void NMI_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void HardFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void MemoryManagement_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void BusFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void UsageFault_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SVC_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void DebugMon_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PendSV_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SysTick_Handler(void) __attribute__ ((weak, alias("Default_Handler"))); -void POWER_CLOCK_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RADIO_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void UARTE0_UART0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void NFCT_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void GPIOTE_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SAADC_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TEMP_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RNG_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void ECB_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void CCM_AAR_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void WDT_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void QDEC_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void COMP_LPCOMP_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI0_EGU0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI1_EGU1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI2_EGU2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI3_EGU3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI4_EGU4_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SWI5_EGU5_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void TIMER4_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM0_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PDM_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void MWU_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM2_SPIS2_SPI2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void RTC2_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void I2S_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void FPU_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void USBD_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void UARTE1_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void QSPI_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void CRYPTOCELL_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void SPIM3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); -void PWM3_IRQHandler (void) __attribute__ ((weak, alias("Default_Handler"))); +void POWER_CLOCK_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RADIO_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void UARTE0_UART0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM0_SPIS0_TWIM0_TWIS0_SPI0_TWI0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM1_SPIS1_TWIM1_TWIS1_SPI1_TWI1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void NFCT_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void GPIOTE_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SAADC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TEMP_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RNG_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void ECB_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void CCM_AAR_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void WDT_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void QDEC_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void COMP_LPCOMP_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI0_EGU0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI1_EGU1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI2_EGU2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI3_EGU3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI4_EGU4_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SWI5_EGU5_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void TIMER4_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM0_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PDM_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void MWU_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM2_SPIS2_SPI2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void RTC2_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void I2S_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void FPU_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void USBD_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void UARTE1_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void QSPI_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void CRYPTOCELL_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void SPIM3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); +void PWM3_IRQHandler(void) __attribute__ ((weak, alias("Default_Handler"))); const func __Vectors[] __attribute__ ((used, section(".isr_vector"))) = { - (func)&_estack, + (func) & _estack, Reset_Handler, NMI_Handler, HardFault_Handler, diff --git a/ports/nrf/examples/ubluepy_eddystone.py b/ports/nrf/examples/ubluepy_eddystone.py index 426a4aa55f..96818d01c2 100644 --- a/ports/nrf/examples/ubluepy_eddystone.py +++ b/ports/nrf/examples/ubluepy_eddystone.py @@ -1,13 +1,16 @@ from ubluepy import Peripheral, constants -BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE = const(0x02) -BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED = const(0x04) +BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE = const(0x02) +BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED = const(0x04) -BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE = const(BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED) +BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE = const( + BLE_GAP_ADV_FLAG_LE_GENERAL_DISC_MODE | BLE_GAP_ADV_FLAG_BR_EDR_NOT_SUPPORTED +) + +EDDYSTONE_FRAME_TYPE_URL = const(0x10) +EDDYSTONE_URL_PREFIX_HTTP_WWW = const(0x00) # "http://www". +EDDYSTONE_URL_SUFFIX_DOT_COM = const(0x01) # ".com" -EDDYSTONE_FRAME_TYPE_URL = const(0x10) -EDDYSTONE_URL_PREFIX_HTTP_WWW = const(0x00) # "http://www". -EDDYSTONE_URL_SUFFIX_DOT_COM = const(0x01) # ".com" def string_to_binarray(text): b = bytearray([]) @@ -15,6 +18,7 @@ def string_to_binarray(text): b.append(ord(c)) return b + def gen_ad_type_content(ad_type, data): b = bytearray(1) b.append(ad_type) @@ -22,6 +26,7 @@ def gen_ad_type_content(ad_type, data): b[0] = len(b) - 1 return b + def generate_eddystone_adv_packet(url): # flags disc_mode = bytearray([BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE]) @@ -29,10 +34,12 @@ def generate_eddystone_adv_packet(url): # 16-bit uuid uuid = bytearray([0xAA, 0xFE]) - packet_uuid16 = gen_ad_type_content(constants.ad_types.AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, uuid) + packet_uuid16 = gen_ad_type_content( + constants.ad_types.AD_TYPE_16BIT_SERVICE_UUID_COMPLETE, uuid + ) # eddystone data - rssi = 0xEE # -18 dB, approx signal strength at 0m. + rssi = 0xEE # -18 dB, approx signal strength at 0m. eddystone_data = bytearray([]) eddystone_data.append(EDDYSTONE_FRAME_TYPE_URL) eddystone_data.append(rssi) @@ -42,7 +49,9 @@ def generate_eddystone_adv_packet(url): # service data service_data = uuid + eddystone_data - packet_service_data = gen_ad_type_content(constants.ad_types.AD_TYPE_SERVICE_DATA, service_data) + packet_service_data = gen_ad_type_content( + constants.ad_types.AD_TYPE_SERVICE_DATA, service_data + ) # generate advertisement packet packet = bytearray([]) @@ -52,6 +61,7 @@ def generate_eddystone_adv_packet(url): return packet + def start(): adv_packet = generate_eddystone_adv_packet("micropython") p = Peripheral() diff --git a/ports/nrf/examples/ubluepy_scan.py b/ports/nrf/examples/ubluepy_scan.py index c0a7d05a37..37daa6c69b 100644 --- a/ports/nrf/examples/ubluepy_scan.py +++ b/ports/nrf/examples/ubluepy_scan.py @@ -1,21 +1,24 @@ from ubluepy import Scanner, constants + def bytes_to_str(bytes): string = "" for b in bytes: string += chr(b) return string + def get_device_names(scan_entries): dev_names = [] for e in scan_entries: scan = e.getScanData() if scan: for s in scan: - if s[0] == constants.ad_types.AD_TYPE_COMPLETE_LOCAL_NAME: - dev_names.append((e, bytes_to_str(s[2]))) + if s[0] == constants.ad_types.AD_TYPE_COMPLETE_LOCAL_NAME: + dev_names.append((e, bytes_to_str(s[2]))) return dev_names + def find_device_by_name(name): s = Scanner() scan_res = s.scan(100) @@ -25,6 +28,7 @@ def find_device_by_name(name): if name == dev[1]: return dev[0] + # >>> res = find_device_by_name("micr") # >>> if res: # ... print("address:", res.addr()) diff --git a/ports/nrf/examples/ubluepy_temp.py b/ports/nrf/examples/ubluepy_temp.py index 405f77c4b0..c70235c4a3 100644 --- a/ports/nrf/examples/ubluepy_temp.py +++ b/ports/nrf/examples/ubluepy_temp.py @@ -26,6 +26,7 @@ from pyb import LED from machine import RTC, Temp from ubluepy import Service, Characteristic, UUID, Peripheral, constants + def event_handler(id, handle, data): global rtc global periph @@ -55,6 +56,7 @@ def event_handler(id, handle, data): # stop low power timer rtc.stop() + def send_temp(timer_id): global notif_enabled global char_temp @@ -62,9 +64,10 @@ def send_temp(timer_id): if notif_enabled: # measure chip temperature temp = Temp.read() - temp = temp * 100 + temp = temp * 100 char_temp.write(bytearray([temp & 0xFF, temp >> 8])) + # start off with LED(1) off LED(1).off() @@ -74,14 +77,14 @@ rtc = RTC(1, period=5, mode=RTC.PERIODIC, callback=send_temp) notif_enabled = False -uuid_env_sense = UUID("0x181A") # Environmental Sensing service -uuid_temp = UUID("0x2A6E") # Temperature characteristic +uuid_env_sense = UUID("0x181A") # Environmental Sensing service +uuid_temp = UUID("0x2A6E") # Temperature characteristic serv_env_sense = Service(uuid_env_sense) temp_props = Characteristic.PROP_NOTIFY | Characteristic.PROP_READ temp_attrs = Characteristic.ATTR_CCCD -char_temp = Characteristic(uuid_temp, props = temp_props, attrs = temp_attrs) +char_temp = Characteristic(uuid_temp, props=temp_props, attrs=temp_attrs) serv_env_sense.addCharacteristic(char_temp) diff --git a/ports/nrf/fatfs_port.c b/ports/nrf/fatfs_port.c index 2b741f993a..5347af4177 100644 --- a/ports/nrf/fatfs_port.c +++ b/ports/nrf/fatfs_port.c @@ -31,12 +31,12 @@ #include "shared-bindings/time/__init__.h" DWORD get_fattime(void) { -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC timeutils_struct_time_t tm; common_hal_rtc_get_time(&tm); return ((tm.tm_year - 1980) << 25) | (tm.tm_mon << 21) | (tm.tm_mday << 16) | - (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1); -#else + (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1); + #else return ((2016 - 1980) << 25) | ((9) << 21) | ((1) << 16) | ((16) << 11) | ((43) << 5) | (35 / 2); -#endif + #endif } diff --git a/ports/nrf/freeze/test.py b/ports/nrf/freeze/test.py index e64bbc9f52..ba05ae1020 100644 --- a/ports/nrf/freeze/test.py +++ b/ports/nrf/freeze/test.py @@ -1,4 +1,5 @@ import sys + def hello(): print("Hello %s!" % sys.platform) diff --git a/ports/nrf/gccollect.c b/ports/nrf/gccollect.c index 3661daa535..453bc61f2b 100644 --- a/ports/nrf/gccollect.c +++ b/ports/nrf/gccollect.c @@ -31,11 +31,10 @@ #include "py/gc.h" #include "gccollect.h" -static inline uint32_t get_msp(void) -{ - register uint32_t result; - __asm volatile ("MRS %0, msp\n" : "=r" (result) ); - return(result); +static inline uint32_t get_msp(void) { + register uint32_t result; + __asm volatile ("MRS %0, msp\n" : "=r" (result)); + return result; } void gc_collect(void) { @@ -45,7 +44,7 @@ void gc_collect(void) { mp_uint_t sp = get_msp(); // Get stack pointer // trace the stack, including the registers (since they live on the stack in this function) - gc_collect_root((void**)sp, ((uint32_t)&_ram_end - sp) / sizeof(uint32_t)); + gc_collect_root((void **)sp, ((uint32_t)&_ram_end - sp) / sizeof(uint32_t)); // end the GC gc_collect_end(); diff --git a/ports/nrf/ld_defines.c b/ports/nrf/ld_defines.c index 6e266e4f7a..7a59531b0e 100644 --- a/ports/nrf/ld_defines.c +++ b/ports/nrf/ld_defines.c @@ -9,44 +9,44 @@ // The next line is a marker to start looking for definitions. Lines above the next line are ignored. // START_LD_DEFINES -/*FLASH_SIZE=*/ FLASH_SIZE; -/*RAM_START_ADDR=*/ RAM_START_ADDR; -/*RAM_SIZE=*/ RAM_SIZE; +/*FLASH_SIZE=*/ FLASH_SIZE; +/*RAM_START_ADDR=*/ RAM_START_ADDR; +/*RAM_SIZE=*/ RAM_SIZE; -/*MBR_START_ADDR=*/ MBR_START_ADDR; -/*MBR_SIZE=*/ MBR_SIZE; +/*MBR_START_ADDR=*/ MBR_START_ADDR; +/*MBR_SIZE=*/ MBR_SIZE; -/*SD_FLASH_START_ADDR=*/ SD_FLASH_START_ADDR; -/*SD_FLASH_SIZE=*/ SD_FLASH_SIZE; +/*SD_FLASH_START_ADDR=*/ SD_FLASH_START_ADDR; +/*SD_FLASH_SIZE=*/ SD_FLASH_SIZE; -/*ISR_START_ADDR=*/ ISR_START_ADDR; -/*ISR_SIZE=*/ ISR_SIZE; +/*ISR_START_ADDR=*/ ISR_START_ADDR; +/*ISR_SIZE=*/ ISR_SIZE; -/*CIRCUITPY_DEFAULT_STACK_SIZE=*/ CIRCUITPY_DEFAULT_STACK_SIZE; +/*CIRCUITPY_DEFAULT_STACK_SIZE=*/ CIRCUITPY_DEFAULT_STACK_SIZE; -/*CIRCUITPY_FIRMWARE_START_ADDR=*/ CIRCUITPY_FIRMWARE_START_ADDR; -/*CIRCUITPY_FIRMWARE_SIZE=*/ CIRCUITPY_FIRMWARE_SIZE; +/*CIRCUITPY_FIRMWARE_START_ADDR=*/ CIRCUITPY_FIRMWARE_START_ADDR; +/*CIRCUITPY_FIRMWARE_SIZE=*/ CIRCUITPY_FIRMWARE_SIZE; -/*CIRCUITPY_BLE_CONFIG_START_ADDR=*/ CIRCUITPY_BLE_CONFIG_START_ADDR; -/*CIRCUITPY_BLE_CONFIG_SIZE=*/ CIRCUITPY_BLE_CONFIG_SIZE; +/*CIRCUITPY_BLE_CONFIG_START_ADDR=*/ CIRCUITPY_BLE_CONFIG_START_ADDR; +/*CIRCUITPY_BLE_CONFIG_SIZE=*/ CIRCUITPY_BLE_CONFIG_SIZE; -/*CIRCUITPY_INTERNAL_NVM_START_ADDR=*/ CIRCUITPY_INTERNAL_NVM_START_ADDR; -/*CIRCUITPY_INTERNAL_NVM_SIZE=*/ CIRCUITPY_INTERNAL_NVM_SIZE; +/*CIRCUITPY_INTERNAL_NVM_START_ADDR=*/ CIRCUITPY_INTERNAL_NVM_START_ADDR; +/*CIRCUITPY_INTERNAL_NVM_SIZE=*/ CIRCUITPY_INTERNAL_NVM_SIZE; /*CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_START_ADDR=*/ CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_START_ADDR; -/*CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE=*/ CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE; +/*CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE=*/ CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE; -/*BOOTLOADER_START_ADDR=*/ BOOTLOADER_START_ADDR; -/*BOOTLOADER_SIZE=*/ BOOTLOADER_SIZE; +/*BOOTLOADER_START_ADDR=*/ BOOTLOADER_START_ADDR; +/*BOOTLOADER_SIZE=*/ BOOTLOADER_SIZE; -/*BOOTLOADER_SETTINGS_START_ADDR=*/ BOOTLOADER_SETTINGS_START_ADDR; -/*BOOTLOADER_SETTINGS_SIZE=*/ BOOTLOADER_SETTINGS_SIZE; +/*BOOTLOADER_SETTINGS_START_ADDR=*/ BOOTLOADER_SETTINGS_START_ADDR; +/*BOOTLOADER_SETTINGS_SIZE=*/ BOOTLOADER_SETTINGS_SIZE; -/*SOFTDEVICE_RAM_START_ADDR=*/ SOFTDEVICE_RAM_START_ADDR; -/*SOFTDEVICE_RAM_SIZE=*/ SOFTDEVICE_RAM_SIZE; +/*SOFTDEVICE_RAM_START_ADDR=*/ SOFTDEVICE_RAM_START_ADDR; +/*SOFTDEVICE_RAM_SIZE=*/ SOFTDEVICE_RAM_SIZE; -/*SPIM3_BUFFER_RAM_START_ADDR=*/ SPIM3_BUFFER_RAM_START_ADDR; -/*SPIM3_BUFFER_RAM_SIZE=*/ SPIM3_BUFFER_RAM_SIZE; +/*SPIM3_BUFFER_RAM_START_ADDR=*/ SPIM3_BUFFER_RAM_START_ADDR; +/*SPIM3_BUFFER_RAM_SIZE=*/ SPIM3_BUFFER_RAM_SIZE; -/*APP_RAM_START_ADDR=*/ APP_RAM_START_ADDR; -/*APP_RAM_SIZE=*/ APP_RAM_SIZE; +/*APP_RAM_START_ADDR=*/ APP_RAM_START_ADDR; +/*APP_RAM_SIZE=*/ APP_RAM_SIZE; diff --git a/ports/nrf/mpconfigport.h b/ports/nrf/mpconfigport.h index 3ac41a5e47..99effcea2f 100644 --- a/ports/nrf/mpconfigport.h +++ b/ports/nrf/mpconfigport.h @@ -39,21 +39,21 @@ #define MICROPY_PY_SYS_STDIO_BUFFER (1) // 24kiB stack -#define CIRCUITPY_DEFAULT_STACK_SIZE (24*1024) +#define CIRCUITPY_DEFAULT_STACK_SIZE (24 * 1024) #ifdef NRF52840 #define MICROPY_PY_SYS_PLATFORM "nRF52840" -#define FLASH_SIZE (1024*1024) // 1MiB -#define RAM_SIZE (256*1024) // 256 KiB +#define FLASH_SIZE (1024 * 1024) // 1MiB +#define RAM_SIZE (256 * 1024) // 256 KiB // Special RAM area for SPIM3 transmit buffer, to work around hardware bug. // See common.template.ld. -#define SPIM3_BUFFER_RAM_SIZE (8*1024) // 8 KiB +#define SPIM3_BUFFER_RAM_SIZE (8 * 1024) // 8 KiB #endif #ifdef NRF52833 #define MICROPY_PY_SYS_PLATFORM "nRF52833" -#define FLASH_SIZE (512*1024) // 512 KiB -#define RAM_SIZE (128*1024) // 128 KiB +#define FLASH_SIZE (512 * 1024) // 512 KiB +#define RAM_SIZE (128 * 1024) // 128 KiB // SPIM3 buffer is not needed on nRF52833: the SPIM3 hw bug is not present. #ifndef SPIM3_BUFFER_RAM_SIZE #define SPIM3_BUFFER_RAM_SIZE (0) @@ -68,7 +68,7 @@ // Definitions that might be overriden by mpconfigboard.h #ifndef CIRCUITPY_INTERNAL_NVM_SIZE -#define CIRCUITPY_INTERNAL_NVM_SIZE (8*1024) +#define CIRCUITPY_INTERNAL_NVM_SIZE (8 * 1024) #endif #ifndef BOARD_HAS_32KHZ_XTAL @@ -78,7 +78,7 @@ #if INTERNAL_FLASH_FILESYSTEM #ifndef CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE -#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (256*1024) +#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (256 * 1024) #endif #else #define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (0) @@ -105,7 +105,7 @@ // SD_FLASH_SIZE is from nrf_sdm.h #define ISR_START_ADDR (SD_FLASH_START_ADDR + SD_FLASH_SIZE) -#define ISR_SIZE (4*1024) // 4kiB +#define ISR_SIZE (4 * 1024) // 4kiB // Smallest unit of flash that can be erased. #define FLASH_ERASE_SIZE FLASH_PAGE_SIZE @@ -116,12 +116,12 @@ // Bootloader values from https://github.com/adafruit/Adafruit_nRF52_Bootloader/blob/master/src/linker/s140_v6.ld #define BOOTLOADER_START_ADDR (FLASH_SIZE - BOOTLOADER_SIZE - BOOTLOADER_SETTINGS_SIZE - BOOTLOADER_MBR_SIZE) -#define BOOTLOADER_MBR_SIZE (4*1024) // 4kib +#define BOOTLOADER_MBR_SIZE (4 * 1024) // 4kib #ifndef BOOTLOADER_SIZE -#define BOOTLOADER_SIZE (40*1024) // 40kiB +#define BOOTLOADER_SIZE (40 * 1024) // 40kiB #endif #define BOOTLOADER_SETTINGS_START_ADDR (FLASH_SIZE - BOOTLOADER_SETTINGS_SIZE) -#define BOOTLOADER_SETTINGS_SIZE (4*1024) // 4kiB +#define BOOTLOADER_SETTINGS_SIZE (4 * 1024) // 4kiB #define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_START_ADDR (BOOTLOADER_START_ADDR - CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE) @@ -133,7 +133,7 @@ // 32kiB for bonding, etc. #ifndef CIRCUITPY_BLE_CONFIG_SIZE -#define CIRCUITPY_BLE_CONFIG_SIZE (32*1024) +#define CIRCUITPY_BLE_CONFIG_SIZE (32 * 1024) #endif #define CIRCUITPY_BLE_CONFIG_START_ADDR (CIRCUITPY_INTERNAL_NVM_START_ADDR - CIRCUITPY_BLE_CONFIG_SIZE) @@ -182,7 +182,7 @@ // high enough to work and then check the mutation of the value done by sd_ble_enable(). // See common.template.ld. #ifndef SOFTDEVICE_RAM_SIZE -#define SOFTDEVICE_RAM_SIZE (56*1024) +#define SOFTDEVICE_RAM_SIZE (56 * 1024) #endif @@ -192,7 +192,7 @@ #define APP_RAM_START_ADDR (SPIM3_BUFFER_RAM_START_ADDR + SPIM3_BUFFER_RAM_SIZE) #define APP_RAM_SIZE (RAM_START_ADDR + RAM_SIZE - APP_RAM_START_ADDR) -#if SPIM3_BUFFER_RAM_SIZE > 0 && SOFTDEVICE_RAM_SIZE + SPIM3_BUFFER_RAM_SIZE > (64*1024) +#if SPIM3_BUFFER_RAM_SIZE > 0 && SOFTDEVICE_RAM_SIZE + SPIM3_BUFFER_RAM_SIZE > (64 * 1024) #error SPIM3 buffer must be in the first 64kB of RAM. #endif @@ -207,8 +207,8 @@ #define MICROPY_PORT_ROOT_POINTERS \ CIRCUITPY_COMMON_ROOT_POINTERS \ - uint16_t* pixels_pattern_heap; \ - ble_drv_evt_handler_entry_t* ble_drv_evt_handler_entries; \ + uint16_t *pixels_pattern_heap; \ + ble_drv_evt_handler_entry_t *ble_drv_evt_handler_entries; \ #endif // NRF5_MPCONFIGPORT_H__ diff --git a/ports/nrf/mphalport.h b/ports/nrf/mphalport.h index 8bb351401a..2b13f82db1 100644 --- a/ports/nrf/mphalport.h +++ b/ports/nrf/mphalport.h @@ -37,8 +37,8 @@ extern nrfx_uarte_t serial_instance; -#define mp_hal_ticks_ms() ((mp_uint_t) supervisor_ticks_ms32()) -#define mp_hal_delay_us(us) NRFX_DELAY_US((uint32_t) (us)) +#define mp_hal_ticks_ms() ((mp_uint_t)supervisor_ticks_ms32()) +#define mp_hal_delay_us(us) NRFX_DELAY_US((uint32_t)(us)) bool mp_hal_stdin_any(void); diff --git a/ports/nrf/nrfx_config.h b/ports/nrf/nrfx_config.h index 94812d5913..2c31263c58 100644 --- a/ports/nrf/nrfx_config.h +++ b/ports/nrf/nrfx_config.h @@ -32,7 +32,7 @@ #endif #if CIRCUITPY_NRF_NUM_I2C != 0 && CIRCUITPY_NRF_NUM_I2C != 1 && CIRCUITPY_NRF_NUM_I2C != 2 -# error CIRCUITPY_NRF_NUM_I2C must be 0, 1, or 2 +#error CIRCUITPY_NRF_NUM_I2C must be 0, 1, or 2 #endif // Enable SPIM1, SPIM2 and SPIM3 (if available) diff --git a/ports/nrf/nrfx_glue.h b/ports/nrf/nrfx_glue.h index 9f91b72a14..c54f8e2c13 100644 --- a/ports/nrf/nrfx_glue.h +++ b/ports/nrf/nrfx_glue.h @@ -60,7 +60,7 @@ extern "C" { void __assert_func(const char *file, int line, const char *func, const char *expr); -//------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------ /** * @brief Macro for placing a runtime assertion. @@ -85,14 +85,14 @@ void __assert_func(const char *file, int line, const char *func, const char *exp #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) #endif -//------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------ #ifdef SOFTDEVICE_PRESENT #define INTERRUPT_PRIORITY_IS_VALID(pri) ((((pri) > 1) && ((pri) < 4)) || \ - (((pri) > 4) && ((pri) < 8))) + (((pri) > 4) && ((pri) < 8))) #else #define INTERRUPT_PRIORITY_IS_VALID(pri) ((pri) < 8) -#endif //SOFTDEVICE_PRESENT +#endif // SOFTDEVICE_PRESENT /** * @brief Macro for setting the priority of a specific IRQ. @@ -103,9 +103,8 @@ void __assert_func(const char *file, int line, const char *func, const char *exp #define NRFX_IRQ_PRIORITY_SET(irq_number, priority) \ _NRFX_IRQ_PRIORITY_SET(irq_number, priority) static inline void _NRFX_IRQ_PRIORITY_SET(IRQn_Type irq_number, - uint8_t priority) -{ - //ASSERT(INTERRUPT_PRIORITY_IS_VALID(priority)); + uint8_t priority) { + // ASSERT(INTERRUPT_PRIORITY_IS_VALID(priority)); NVIC_SetPriority(irq_number, priority); } @@ -115,8 +114,7 @@ static inline void _NRFX_IRQ_PRIORITY_SET(IRQn_Type irq_number, * @param irq_number IRQ number. */ #define NRFX_IRQ_ENABLE(irq_number) _NRFX_IRQ_ENABLE(irq_number) -static inline void _NRFX_IRQ_ENABLE(IRQn_Type irq_number) -{ +static inline void _NRFX_IRQ_ENABLE(IRQn_Type irq_number) { NVIC_ClearPendingIRQ(irq_number); NVIC_EnableIRQ(irq_number); } @@ -130,8 +128,7 @@ static inline void _NRFX_IRQ_ENABLE(IRQn_Type irq_number) * @retval false Otherwise. */ #define NRFX_IRQ_IS_ENABLED(irq_number) _NRFX_IRQ_IS_ENABLED(irq_number) -static inline bool _NRFX_IRQ_IS_ENABLED(IRQn_Type irq_number) -{ +static inline bool _NRFX_IRQ_IS_ENABLED(IRQn_Type irq_number) { return 0 != (NVIC->ISER[irq_number / 32] & (1UL << (irq_number % 32))); } @@ -141,8 +138,7 @@ static inline bool _NRFX_IRQ_IS_ENABLED(IRQn_Type irq_number) * @param irq_number IRQ number. */ #define NRFX_IRQ_DISABLE(irq_number) _NRFX_IRQ_DISABLE(irq_number) -static inline void _NRFX_IRQ_DISABLE(IRQn_Type irq_number) -{ +static inline void _NRFX_IRQ_DISABLE(IRQn_Type irq_number) { NVIC_DisableIRQ(irq_number); } @@ -152,8 +148,7 @@ static inline void _NRFX_IRQ_DISABLE(IRQn_Type irq_number) * @param irq_number IRQ number. */ #define NRFX_IRQ_PENDING_SET(irq_number) _NRFX_IRQ_PENDING_SET(irq_number) -static inline void _NRFX_IRQ_PENDING_SET(IRQn_Type irq_number) -{ +static inline void _NRFX_IRQ_PENDING_SET(IRQn_Type irq_number) { NVIC_SetPendingIRQ(irq_number); } @@ -163,8 +158,7 @@ static inline void _NRFX_IRQ_PENDING_SET(IRQn_Type irq_number) * @param irq_number IRQ number. */ #define NRFX_IRQ_PENDING_CLEAR(irq_number) _NRFX_IRQ_PENDING_CLEAR(irq_number) -static inline void _NRFX_IRQ_PENDING_CLEAR(IRQn_Type irq_number) -{ +static inline void _NRFX_IRQ_PENDING_CLEAR(IRQn_Type irq_number) { NVIC_ClearPendingIRQ(irq_number); } @@ -175,9 +169,8 @@ static inline void _NRFX_IRQ_PENDING_CLEAR(IRQn_Type irq_number) * @retval false Otherwise. */ #define NRFX_IRQ_IS_PENDING(irq_number) _NRFX_IRQ_IS_PENDING(irq_number) -static inline bool _NRFX_IRQ_IS_PENDING(IRQn_Type irq_number) -{ - return (NVIC_GetPendingIRQ(irq_number) == 1); +static inline bool _NRFX_IRQ_IS_PENDING(IRQn_Type irq_number) { + return NVIC_GetPendingIRQ(irq_number) == 1; } void common_hal_mcu_disable_interrupts(void); @@ -192,7 +185,7 @@ void common_hal_mcu_enable_interrupts(void); */ #define NRFX_CRITICAL_SECTION_EXIT() common_hal_mcu_enable_interrupts() -//------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------ /** * @brief When set to a non-zero value, this macro specifies that @@ -206,7 +199,7 @@ void common_hal_mcu_enable_interrupts(void); #define NRFX_DELAY_US(us_time) nrfx_coredep_delay_us(us_time) -//------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------ /** * @brief When set to a non-zero value, this macro specifies that the @@ -216,7 +209,7 @@ void common_hal_mcu_enable_interrupts(void); */ #define NRFX_CUSTOM_ERROR_CODES 0 -//------------------------------------------------------------------------------ +// ------------------------------------------------------------------------------ /** * @brief Bitmask defining PPI channels reserved to be used outside of nrfx. diff --git a/ports/nrf/peripherals/nrf/clocks.c b/ports/nrf/peripherals/nrf/clocks.c index 269365cc94..aef956f2da 100644 --- a/ports/nrf/peripherals/nrf/clocks.c +++ b/ports/nrf/peripherals/nrf/clocks.c @@ -30,13 +30,14 @@ void nrf_peripherals_clocks_init(void) { -#if BOARD_HAS_32KHZ_XTAL + #if BOARD_HAS_32KHZ_XTAL NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_Xtal << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk); -#else + #else NRF_CLOCK->LFCLKSRC = (uint32_t)((CLOCK_LFCLKSRC_SRC_RC << CLOCK_LFCLKSRC_SRC_Pos) & CLOCK_LFCLKSRC_SRC_Msk); -#endif + #endif NRF_CLOCK->TASKS_LFCLKSTART = 1UL; // Wait for clocks to start. - while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0) {} + while (NRF_CLOCK->EVENTS_LFCLKSTARTED == 0) { + } } diff --git a/ports/nrf/peripherals/nrf/nrf52833/power.c b/ports/nrf/peripherals/nrf/nrf52833/power.c index d64c536bb3..192a49acca 100644 --- a/ports/nrf/peripherals/nrf/nrf52833/power.c +++ b/ports/nrf/peripherals/nrf/nrf52833/power.c @@ -38,10 +38,12 @@ void nrf_peripherals_power_init(void) { // checking which prevents writes to UICR. // Reported: https://devzone.nordicsemi.com/f/nordic-q-a/57243/nrfx_nvmc-h-api-cannot-write-to-uicr NRF_NVMC->CONFIG = NRF_NVMC_MODE_WRITE; - while (!(NRF_NVMC->READY & NVMC_READY_READY_Msk)) {} + while (!(NRF_NVMC->READY & NVMC_READY_READY_Msk)) { + } NRF_UICR->REGOUT0 = UICR_REGOUT0_VOUT_3V3 << UICR_REGOUT0_VOUT_Pos; __DMB(); - while (NRF_NVMC->READY == NVMC_READY_READY_Busy) {} + while (NRF_NVMC->READY == NVMC_READY_READY_Busy) { + } NRF_NVMC->CONFIG = NRF_NVMC_MODE_READONLY; // Must reset to enable change. diff --git a/ports/nrf/peripherals/nrf/nrf52840/power.c b/ports/nrf/peripherals/nrf/nrf52840/power.c index d64c536bb3..192a49acca 100644 --- a/ports/nrf/peripherals/nrf/nrf52840/power.c +++ b/ports/nrf/peripherals/nrf/nrf52840/power.c @@ -38,10 +38,12 @@ void nrf_peripherals_power_init(void) { // checking which prevents writes to UICR. // Reported: https://devzone.nordicsemi.com/f/nordic-q-a/57243/nrfx_nvmc-h-api-cannot-write-to-uicr NRF_NVMC->CONFIG = NRF_NVMC_MODE_WRITE; - while (!(NRF_NVMC->READY & NVMC_READY_READY_Msk)) {} + while (!(NRF_NVMC->READY & NVMC_READY_READY_Msk)) { + } NRF_UICR->REGOUT0 = UICR_REGOUT0_VOUT_3V3 << UICR_REGOUT0_VOUT_Pos; __DMB(); - while (NRF_NVMC->READY == NVMC_READY_READY_Busy) {} + while (NRF_NVMC->READY == NVMC_READY_READY_Busy) { + } NRF_NVMC->CONFIG = NRF_NVMC_MODE_READONLY; // Must reset to enable change. diff --git a/ports/nrf/peripherals/nrf/nvm.c b/ports/nrf/peripherals/nrf/nvm.c index ce47d73c77..06a6429227 100644 --- a/ports/nrf/peripherals/nrf/nvm.c +++ b/ports/nrf/peripherals/nrf/nvm.c @@ -40,9 +40,10 @@ STATIC bool sd_is_enabled(void) { uint8_t sd_en = 0; - if (__get_PRIMASK()) + if (__get_PRIMASK()) { return false; - (void) sd_softdevice_is_enabled(&sd_en); + } + (void)sd_softdevice_is_enabled(&sd_en); return sd_en; } @@ -74,7 +75,7 @@ bool sd_flash_page_erase_sync(uint32_t page_number) { return true; } -bool sd_flash_write_sync(uint32_t *dest_words, uint32_t* src_words, uint32_t num_words) { +bool sd_flash_write_sync(uint32_t *dest_words, uint32_t *src_words, uint32_t num_words) { sd_flash_operation_start(); if (sd_flash_write(dest_words, src_words, num_words) != NRF_SUCCESS) { return false; @@ -95,12 +96,29 @@ bool sd_flash_write_sync(uint32_t *dest_words, uint32_t* src_words, uint32_t num bool nrf_nvm_safe_flash_page_write(uint32_t page_addr, uint8_t *data) { #ifdef BLUETOOTH_SD - if (sd_is_enabled()) { - uint32_t err_code; - sd_flash_operation_status_t status; + if (sd_is_enabled()) { + uint32_t err_code; + sd_flash_operation_status_t status; + sd_flash_operation_start(); + err_code = sd_flash_page_erase(page_addr / FLASH_PAGE_SIZE); + if (err_code != NRF_SUCCESS) { + return false; + } + status = sd_flash_operation_wait_until_done(); + if (status == SD_FLASH_OPERATION_ERROR) { + return false; + } + + // Divide a full page into parts, because writing a full page causes an assertion failure. + // See https://devzone.nordicsemi.com/f/nordic-q-a/40088/sd_flash_write-cause-nrf_fault_id_sd_assert/ + const size_t BLOCK_PARTS = 2; + size_t words_to_write = FLASH_PAGE_SIZE / sizeof(uint32_t) / BLOCK_PARTS; + for (size_t i = 0; i < BLOCK_PARTS; i++) { sd_flash_operation_start(); - err_code = sd_flash_page_erase(page_addr / FLASH_PAGE_SIZE); + err_code = sd_flash_write(((uint32_t *)page_addr) + i * words_to_write, + (uint32_t *)data + i * words_to_write, + words_to_write); if (err_code != NRF_SUCCESS) { return false; } @@ -108,27 +126,10 @@ bool nrf_nvm_safe_flash_page_write(uint32_t page_addr, uint8_t *data) { if (status == SD_FLASH_OPERATION_ERROR) { return false; } - - // Divide a full page into parts, because writing a full page causes an assertion failure. - // See https://devzone.nordicsemi.com/f/nordic-q-a/40088/sd_flash_write-cause-nrf_fault_id_sd_assert/ - const size_t BLOCK_PARTS = 2; - size_t words_to_write = FLASH_PAGE_SIZE / sizeof(uint32_t) / BLOCK_PARTS; - for (size_t i = 0; i < BLOCK_PARTS; i++) { - sd_flash_operation_start(); - err_code = sd_flash_write(((uint32_t *)page_addr) + i * words_to_write, - (uint32_t *)data + i * words_to_write, - words_to_write); - if (err_code != NRF_SUCCESS) { - return false; - } - status = sd_flash_operation_wait_until_done(); - if (status == SD_FLASH_OPERATION_ERROR) { - return false; - } - } - - return true; } + + return true; + } #endif nrfx_nvmc_page_erase(page_addr); diff --git a/ports/nrf/peripherals/nrf/nvm.h b/ports/nrf/peripherals/nrf/nvm.h index 9e144d802a..da8080f0af 100644 --- a/ports/nrf/peripherals/nrf/nvm.h +++ b/ports/nrf/peripherals/nrf/nvm.h @@ -29,7 +29,7 @@ #if BLUETOOTH_SD bool sd_flash_page_erase_sync(uint32_t page_number); -bool sd_flash_write_sync(uint32_t *dest_words, uint32_t* src_words, uint32_t num_words); +bool sd_flash_write_sync(uint32_t *dest_words, uint32_t *src_words, uint32_t num_words); #endif bool nrf_nvm_safe_flash_page_write(uint32_t page_addr, uint8_t *data); diff --git a/ports/nrf/peripherals/nrf/pins.h b/ports/nrf/peripherals/nrf/pins.h index efdc8892a4..e3f947ca27 100644 --- a/ports/nrf/peripherals/nrf/pins.h +++ b/ports/nrf/peripherals/nrf/pins.h @@ -47,11 +47,11 @@ extern const mp_obj_type_t mcu_pin_type; // Used in device-specific pins.c #define PIN(p_name, p_port, p_pin, p_adc_channel) \ -{ \ - { &mcu_pin_type }, \ - .number = NRF_GPIO_PIN_MAP(p_port, p_pin), \ - .adc_channel = (p_adc_channel), \ -} + { \ + { &mcu_pin_type }, \ + .number = NRF_GPIO_PIN_MAP(p_port, p_pin), \ + .adc_channel = (p_adc_channel), \ + } // Use illegal pin value to mark unassigned pins. #define NO_PIN 0xff diff --git a/ports/nrf/peripherals/nrf/timers.c b/ports/nrf/peripherals/nrf/timers.c index fd814968dc..f3a16b7e11 100644 --- a/ports/nrf/peripherals/nrf/timers.c +++ b/ports/nrf/peripherals/nrf/timers.c @@ -36,29 +36,29 @@ #include "py/runtime.h" STATIC nrfx_timer_t nrfx_timers[] = { -#if NRFX_CHECK(NRFX_TIMER0_ENABLED) + #if NRFX_CHECK(NRFX_TIMER0_ENABLED) #error NRFX_TIMER0_ENABLED should not be on: TIMER0 is used by the SoftDevice NRFX_TIMER_INSTANCE(0), -#endif -#if NRFX_CHECK(NRFX_TIMER1_ENABLED) + #endif + #if NRFX_CHECK(NRFX_TIMER1_ENABLED) NRFX_TIMER_INSTANCE(1), -#endif -#if NRFX_CHECK(NRFX_TIMER2_ENABLED) + #endif + #if NRFX_CHECK(NRFX_TIMER2_ENABLED) NRFX_TIMER_INSTANCE(2), -#endif -#if NRFX_CHECK(NRFX_TIMER3_ENABLED) + #endif + #if NRFX_CHECK(NRFX_TIMER3_ENABLED) NRFX_TIMER_INSTANCE(3), -#endif -#if NRFX_CHECK(NRFX_TIMER4_ENABLED) + #endif + #if NRFX_CHECK(NRFX_TIMER4_ENABLED) NRFX_TIMER_INSTANCE(4), -#endif + #endif }; static bool nrfx_timer_allocated[ARRAY_SIZE(nrfx_timers)]; static bool nrfx_timer_never_reset[ARRAY_SIZE(nrfx_timers)]; void timers_reset(void) { - for (size_t i = 0; i < ARRAY_SIZE(nrfx_timers); i ++) { + for (size_t i = 0; i < ARRAY_SIZE(nrfx_timers); i++) { if (nrfx_timer_never_reset[i]) { continue; } @@ -67,18 +67,18 @@ void timers_reset(void) { } } -void nrf_peripherals_timer_never_reset(nrfx_timer_t* timer) { +void nrf_peripherals_timer_never_reset(nrfx_timer_t *timer) { int idx = nrf_peripherals_timer_idx_from_timer(timer); nrfx_timer_never_reset[idx] = true; } -void nrf_peripherals_timer_reset_ok(nrfx_timer_t* timer) { +void nrf_peripherals_timer_reset_ok(nrfx_timer_t *timer) { int idx = nrf_peripherals_timer_idx_from_timer(timer); nrfx_timer_never_reset[idx] = false; } -nrfx_timer_t* nrf_peripherals_timer_from_reg(NRF_TIMER_Type* ptr) { - for (size_t i = 0; i < ARRAY_SIZE(nrfx_timers); i ++) { +nrfx_timer_t *nrf_peripherals_timer_from_reg(NRF_TIMER_Type *ptr) { + for (size_t i = 0; i < ARRAY_SIZE(nrfx_timers); i++) { if (nrfx_timers[i].p_reg == ptr) { return &nrfx_timers[i]; } @@ -86,8 +86,8 @@ nrfx_timer_t* nrf_peripherals_timer_from_reg(NRF_TIMER_Type* ptr) { return NULL; } -size_t nrf_peripherals_timer_idx_from_timer(nrfx_timer_t* ptr) { - for (size_t i = 0; i < ARRAY_SIZE(nrfx_timers); i ++) { +size_t nrf_peripherals_timer_idx_from_timer(nrfx_timer_t *ptr) { + for (size_t i = 0; i < ARRAY_SIZE(nrfx_timers); i++) { if (&nrfx_timers[i] == ptr) { return i; } @@ -99,8 +99,8 @@ size_t nrf_peripherals_timer_idx_from_timer(nrfx_timer_t* ptr) { // Returns a free nrfx_timer instance, and marks it as allocated. // The caller should init as with the desired config. // Returns NULL if no timer is available. -nrfx_timer_t* nrf_peripherals_allocate_timer(void) { - for (size_t i = 0; i < ARRAY_SIZE(nrfx_timers); i ++) { +nrfx_timer_t *nrf_peripherals_allocate_timer(void) { + for (size_t i = 0; i < ARRAY_SIZE(nrfx_timers); i++) { if (!nrfx_timer_allocated[i]) { nrfx_timer_allocated[i] = true; return &nrfx_timers[i]; @@ -109,8 +109,8 @@ nrfx_timer_t* nrf_peripherals_allocate_timer(void) { return NULL; } -nrfx_timer_t* nrf_peripherals_allocate_timer_or_throw(void) { - nrfx_timer_t* result = nrf_peripherals_allocate_timer(); +nrfx_timer_t *nrf_peripherals_allocate_timer_or_throw(void) { + nrfx_timer_t *result = nrf_peripherals_allocate_timer(); if (!result) { mp_raise_RuntimeError(translate("All timers in use")); } @@ -118,7 +118,7 @@ nrfx_timer_t* nrf_peripherals_allocate_timer_or_throw(void) { } // Free a timer, which may or may not have been initialized. -void nrf_peripherals_free_timer(nrfx_timer_t* timer) { +void nrf_peripherals_free_timer(nrfx_timer_t *timer) { size_t idx = nrf_peripherals_timer_idx_from_timer(timer); if (idx != ~(size_t)0) { nrfx_timer_allocated[idx] = false; diff --git a/ports/nrf/peripherals/nrf/timers.h b/ports/nrf/peripherals/nrf/timers.h index cf96c6273b..0fb529d73b 100644 --- a/ports/nrf/peripherals/nrf/timers.h +++ b/ports/nrf/peripherals/nrf/timers.h @@ -28,10 +28,10 @@ #include "nrfx_timer.h" void timers_reset(void); -nrfx_timer_t* nrf_peripherals_allocate_timer(void); -nrfx_timer_t* nrf_peripherals_allocate_timer_or_throw(void); -void nrf_peripherals_free_timer(nrfx_timer_t* timer); -void nrf_peripherals_timer_never_reset(nrfx_timer_t* timer); -void nrf_peripherals_timer_reset_ok(nrfx_timer_t* timer); -nrfx_timer_t* nrf_peripherals_timer_from_reg(NRF_TIMER_Type* ptr); -size_t nrf_peripherals_timer_idx_from_timer(nrfx_timer_t* ptr); +nrfx_timer_t *nrf_peripherals_allocate_timer(void); +nrfx_timer_t *nrf_peripherals_allocate_timer_or_throw(void); +void nrf_peripherals_free_timer(nrfx_timer_t *timer); +void nrf_peripherals_timer_never_reset(nrfx_timer_t *timer); +void nrf_peripherals_timer_reset_ok(nrfx_timer_t *timer); +nrfx_timer_t *nrf_peripherals_timer_from_reg(NRF_TIMER_Type *ptr); +size_t nrf_peripherals_timer_idx_from_timer(nrfx_timer_t *ptr); diff --git a/ports/nrf/sd_mutex.c b/ports/nrf/sd_mutex.c index b3162e6af9..2ae490288d 100644 --- a/ports/nrf/sd_mutex.c +++ b/ports/nrf/sd_mutex.c @@ -28,25 +28,25 @@ #include "py/runtime.h" #include "nrf_soc.h" -void sd_mutex_acquire_check(nrf_mutex_t* p_mutex) { +void sd_mutex_acquire_check(nrf_mutex_t *p_mutex) { uint32_t err_code = sd_mutex_acquire(p_mutex); if (err_code != NRF_SUCCESS) { mp_raise_OSError_msg_varg(translate("Failed to acquire mutex, err 0x%04x"), err_code); } } -void sd_mutex_acquire_wait(nrf_mutex_t* p_mutex) { +void sd_mutex_acquire_wait(nrf_mutex_t *p_mutex) { while (sd_mutex_acquire(p_mutex) == NRF_ERROR_SOC_MUTEX_ALREADY_TAKEN) { RUN_BACKGROUND_TASKS; } } -void sd_mutex_acquire_wait_no_vm(nrf_mutex_t* p_mutex) { +void sd_mutex_acquire_wait_no_vm(nrf_mutex_t *p_mutex) { while (sd_mutex_acquire(p_mutex) == NRF_ERROR_SOC_MUTEX_ALREADY_TAKEN) { } } -void sd_mutex_release_check(nrf_mutex_t* p_mutex) { +void sd_mutex_release_check(nrf_mutex_t *p_mutex) { uint32_t err_code = sd_mutex_release(p_mutex); if (err_code != NRF_SUCCESS) { mp_raise_OSError_msg_varg(translate("Failed to release mutex, err 0x%04x"), err_code); diff --git a/ports/nrf/sd_mutex.h b/ports/nrf/sd_mutex.h index ca46917205..2999dc774a 100644 --- a/ports/nrf/sd_mutex.h +++ b/ports/nrf/sd_mutex.h @@ -32,15 +32,15 @@ // Helpers for common usage of nrf_mutex. // Try to acquire a mutex right now. Raise exception if we can't get it. -void sd_mutex_acquire_check(nrf_mutex_t* p_mutex); +void sd_mutex_acquire_check(nrf_mutex_t *p_mutex); // Wait for a mutex to become available. Run VM background tasks while waiting. -void sd_mutex_acquire_wait(nrf_mutex_t* p_mutex); +void sd_mutex_acquire_wait(nrf_mutex_t *p_mutex); // Wait for a mutex to become available.. Block VM while waiting. -void sd_mutex_acquire_wait_no_vm(nrf_mutex_t* p_mutex); +void sd_mutex_acquire_wait_no_vm(nrf_mutex_t *p_mutex); // Release a mutex, and raise exception on error. -void sd_mutex_release_check(nrf_mutex_t* p_mutex); +void sd_mutex_release_check(nrf_mutex_t *p_mutex); #endif // MICROPY_INCLUDED_NRF_SD_MUTEX_H diff --git a/ports/nrf/supervisor/bluetooth.c b/ports/nrf/supervisor/bluetooth.c index 8d89d62723..5ce737f6ad 100644 --- a/ports/nrf/supervisor/bluetooth.c +++ b/ports/nrf/supervisor/bluetooth.c @@ -29,7 +29,7 @@ // This happens in an interrupt so we need to be quick. bool supervisor_bluetooth_hook(ble_evt_t *ble_evt) { -#if CIRCUITPY_BLE_FILE_SERVICE + #if CIRCUITPY_BLE_FILE_SERVICE // Catch writes to filename or contents. Length is read-only. bool done = false; @@ -49,12 +49,12 @@ bool supervisor_bluetooth_hook(ble_evt_t *ble_evt) { // Event handle must match the handle for my characteristic. if (evt_write->handle == supervisor_ble_contents_characteristic.handle) { // Handle events - //write_to_ringbuf(self, evt_write->data, evt_write->len); + // write_to_ringbuf(self, evt_write->data, evt_write->len); // First packet includes a uint16_t le for length at the start. - uint16_t current_length = ((uint16_t*) current_command)[0]; - memcpy(((uint8_t*) current_command) + current_offset, evt_write->data, evt_write->len); + uint16_t current_length = ((uint16_t *)current_command)[0]; + memcpy(((uint8_t *)current_command) + current_offset, evt_write->data, evt_write->len); current_offset += evt_write->len; - current_length = ((uint16_t*) current_command)[0]; + current_length = ((uint16_t *)current_command)[0]; if (current_offset == current_length) { run_ble_background = true; done = true; @@ -75,7 +75,7 @@ bool supervisor_bluetooth_hook(ble_evt_t *ble_evt) { break; } return done; -#else + #else return false; -#endif + #endif } diff --git a/ports/nrf/supervisor/internal_flash.c b/ports/nrf/supervisor/internal_flash.c index 93de0b2c49..cce48a4c32 100644 --- a/ports/nrf/supervisor/internal_flash.c +++ b/ports/nrf/supervisor/internal_flash.c @@ -45,7 +45,7 @@ #define NO_CACHE 0xffffffff -uint8_t _flash_cache[FLASH_PAGE_SIZE] __attribute__((aligned(4))); +uint8_t _flash_cache[FLASH_PAGE_SIZE] __attribute__((aligned(4))); uint32_t _flash_page_addr = NO_CACHE; @@ -64,11 +64,13 @@ uint32_t supervisor_flash_get_block_size(void) { } uint32_t supervisor_flash_get_block_count(void) { - return CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE / FILESYSTEM_BLOCK_SIZE ; + return CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE / FILESYSTEM_BLOCK_SIZE; } void port_internal_flash_flush(void) { - if (_flash_page_addr == NO_CACHE) return; + if (_flash_page_addr == NO_CACHE) { + return; + } // Skip if data is the same if (memcmp(_flash_cache, (void *)_flash_page_addr, FLASH_PAGE_SIZE) != 0) { @@ -83,13 +85,13 @@ mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t n supervisor_flash_flush(); uint32_t src = lba2addr(block); - memcpy(dest, (uint8_t*) src, FILESYSTEM_BLOCK_SIZE*num_blocks); + memcpy(dest, (uint8_t *)src, FILESYSTEM_BLOCK_SIZE * num_blocks); return 0; // success } mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32_t num_blocks) { while (num_blocks) { - uint32_t const addr = lba2addr(lba); + uint32_t const addr = lba2addr(lba); uint32_t const page_addr = addr & ~(FLASH_PAGE_SIZE - 1); uint32_t count = 8 - (lba % 8); // up to page boundary @@ -109,8 +111,8 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 memcpy(_flash_cache + (addr & (FLASH_PAGE_SIZE - 1)), src, count * FILESYSTEM_BLOCK_SIZE); // adjust for next run - lba += count; - src += count * FILESYSTEM_BLOCK_SIZE; + lba += count; + src += count * FILESYSTEM_BLOCK_SIZE; num_blocks -= count; } diff --git a/ports/nrf/supervisor/port.c b/ports/nrf/supervisor/port.c index 78bb20ce6c..9a2acd5cab 100644 --- a/ports/nrf/supervisor/port.c +++ b/ports/nrf/supervisor/port.c @@ -94,7 +94,7 @@ void rtc_handler(nrfx_rtc_int_type_t int_type) { if (int_type == NRFX_RTC_INT_OVERFLOW) { // Our RTC is 24 bits and we're clocking it at 32.768khz which is 32 (2 ** 5) subticks per // tick. - overflow_tracker.overflowed_ticks += (1L<< (24 - 5)); + overflow_tracker.overflowed_ticks += (1L << (24 - 5)); } else if (int_type == NRFX_RTC_INT_TICK && nrfx_rtc_counter_get(&rtc_instance) % 32 == 0) { // Do things common to all ports when the tick occurs supervisor_tick(); @@ -145,13 +145,13 @@ safe_mode_t port_init(void) { // Configure millisecond timer initialization. tick_init(); -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC common_hal_rtc_init(); -#endif + #endif -#if CIRCUITPY_ANALOGIO + #if CIRCUITPY_ANALOGIO analogin_init(); -#endif + #endif // If the board was reset by the WatchDogTimer, we may // need to boot into safe mode. Reset the RESETREAS bit @@ -172,51 +172,51 @@ safe_mode_t port_init(void) { } void reset_port(void) { -#ifdef CIRCUITPY_GAMEPAD_TICKS + #ifdef CIRCUITPY_GAMEPAD_TICKS gamepad_reset(); -#endif + #endif -#if CIRCUITPY_BUSIO + #if CIRCUITPY_BUSIO i2c_reset(); spi_reset(); uart_reset(); -#endif + #endif -#if CIRCUITPY_NEOPIXEL_WRITE + #if CIRCUITPY_NEOPIXEL_WRITE neopixel_write_reset(); -#endif + #endif -#if CIRCUITPY_AUDIOBUSIO + #if CIRCUITPY_AUDIOBUSIO i2s_reset(); -#endif + #endif -#if CIRCUITPY_AUDIOPWMIO + #if CIRCUITPY_AUDIOPWMIO audiopwmout_reset(); -#endif + #endif -#if CIRCUITPY_PULSEIO + #if CIRCUITPY_PULSEIO pulseout_reset(); pulsein_reset(); -#endif + #endif -#if CIRCUITPY_PWMIO + #if CIRCUITPY_PWMIO pwmout_reset(); -#endif + #endif -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC rtc_reset(); -#endif + #endif timers_reset(); -#if CIRCUITPY_BLEIO + #if CIRCUITPY_BLEIO bleio_reset(); -#endif + #endif -#if CIRCUITPY_WATCHDOG + #if CIRCUITPY_WATCHDOG watchdog_reset(); -#endif + #endif reset_all_pins(); } @@ -273,7 +273,7 @@ uint32_t port_get_saved_word(void) { return _saved_word; } -uint64_t port_get_raw_ticks(uint8_t* subticks) { +uint64_t port_get_raw_ticks(uint8_t *subticks) { common_hal_mcu_disable_interrupts(); uint32_t rtc = nrfx_rtc_counter_get(&rtc_instance); uint64_t overflow_count = overflow_tracker.overflowed_ticks; @@ -308,14 +308,14 @@ void port_interrupt_after_ticks(uint32_t ticks) { } void port_idle_until_interrupt(void) { -#if defined(MICROPY_QSPI_CS) + #if defined(MICROPY_QSPI_CS) qspi_disable(); -#endif + #endif // Clear the FPU interrupt because it can prevent us from sleeping. if (NVIC_GetPendingIRQ(FPU_IRQn)) { - __set_FPSCR(__get_FPSCR() & ~(0x9f)); - (void) __get_FPSCR(); + __set_FPSCR(__get_FPSCR() & ~(0x9f)); + (void)__get_FPSCR(); NVIC_ClearPendingIRQ(FPU_IRQn); } uint8_t sd_enabled; @@ -352,6 +352,6 @@ void port_idle_until_interrupt(void) { void HardFault_Handler(void) { reset_into_safe_mode(HARD_CRASH); while (true) { - asm("nop;"); + asm ("nop;"); } } diff --git a/ports/nrf/supervisor/qspi_flash.c b/ports/nrf/supervisor/qspi_flash.c index 7ca27d56c4..1386af7c44 100644 --- a/ports/nrf/supervisor/qspi_flash.c +++ b/ports/nrf/supervisor/qspi_flash.c @@ -39,8 +39,7 @@ #include "supervisor/shared/external_flash/qspi_flash.h" // When USB is disconnected, disable QSPI in sleep mode to save energy -void qspi_disable(void) -{ +void qspi_disable(void) { // If VBUS is detected, no need to disable QSPI if (NRF_QSPI->ENABLE && !(NRF_POWER->USBREGSTATUS & POWER_USBREGSTATUS_VBUSDETECT_Msk)) { // Keep CS high when QSPI is diabled @@ -54,8 +53,7 @@ void qspi_disable(void) } } -void qspi_enable(void) -{ +void qspi_enable(void) { if (NRF_QSPI->ENABLE) { return; } @@ -87,7 +85,7 @@ bool spi_flash_command(uint8_t command) { return nrfx_qspi_cinstr_xfer(&cinstr_cfg, NULL, NULL) == NRFX_SUCCESS; } -bool spi_flash_read_command(uint8_t command, uint8_t* response, uint32_t length) { +bool spi_flash_read_command(uint8_t command, uint8_t *response, uint32_t length) { qspi_enable(); nrf_qspi_cinstr_conf_t cinstr_cfg = { .opcode = command, @@ -101,7 +99,7 @@ bool spi_flash_read_command(uint8_t command, uint8_t* response, uint32_t length) } -bool spi_flash_write_command(uint8_t command, uint8_t* data, uint32_t length) { +bool spi_flash_write_command(uint8_t command, uint8_t *data, uint32_t length) { qspi_enable(); nrf_qspi_cinstr_conf_t cinstr_cfg = { .opcode = command, @@ -122,7 +120,7 @@ bool spi_flash_sector_command(uint8_t command, uint32_t address) { return nrfx_qspi_erase(NRF_QSPI_ERASE_LEN_4KB, address) == NRFX_SUCCESS; } -bool spi_flash_write_data(uint32_t address, uint8_t* data, uint32_t length) { +bool spi_flash_write_data(uint32_t address, uint8_t *data, uint32_t length) { qspi_enable(); // TODO: In theory, this also needs to handle unaligned data and // non-multiple-of-4 length. (in practice, I don't think the fat layer @@ -130,17 +128,17 @@ bool spi_flash_write_data(uint32_t address, uint8_t* data, uint32_t length) { return nrfx_qspi_write(data, length, address) == NRFX_SUCCESS; } -bool spi_flash_read_data(uint32_t address, uint8_t* data, uint32_t length) { +bool spi_flash_read_data(uint32_t address, uint8_t *data, uint32_t length) { qspi_enable(); int misaligned = ((intptr_t)data) & 3; // If the data is misaligned, we need to read 4 bytes // into an aligned buffer, and then copy 1, 2, or 3 bytes from the aligned // buffer to data. - if(misaligned) { + if (misaligned) { int sz = 4 - misaligned; __attribute__((aligned(4))) uint8_t buf[4]; - if(nrfx_qspi_read(buf, 4, address) != NRFX_SUCCESS) { + if (nrfx_qspi_read(buf, 4, address) != NRFX_SUCCESS) { return false; } memcpy(data, buf, sz); @@ -153,7 +151,7 @@ bool spi_flash_read_data(uint32_t address, uint8_t* data, uint32_t length) { // signal an error if sz is not a multiple of 4. Read (directly into data) // all but the last 1, 2, or 3 bytes depending on the (remaining) length. uint32_t sz = length & ~(uint32_t)3; - if(nrfx_qspi_read(data, sz, address) != NRFX_SUCCESS) { + if (nrfx_qspi_read(data, sz, address) != NRFX_SUCCESS) { return false; } data += sz; @@ -162,9 +160,9 @@ bool spi_flash_read_data(uint32_t address, uint8_t* data, uint32_t length) { // Now, if we have any bytes left over, we must do a final read of 4 // bytes and copy 1, 2, or 3 bytes to data. - if(length) { + if (length) { __attribute__((aligned(4))) uint8_t buf[4]; - if(nrfx_qspi_read(buf, 4, address) != NRFX_SUCCESS) { + if (nrfx_qspi_read(buf, 4, address) != NRFX_SUCCESS) { return false; } memcpy(data, buf, length); @@ -201,23 +199,23 @@ void spi_flash_init(void) { .irq_priority = 7, }; -#if defined(EXTERNAL_FLASH_QSPI_DUAL) + #if defined(EXTERNAL_FLASH_QSPI_DUAL) qspi_cfg.pins.io1_pin = MICROPY_QSPI_DATA1; qspi_cfg.prot_if.readoc = NRF_QSPI_READOC_READ2O; qspi_cfg.prot_if.writeoc = NRF_QSPI_WRITEOC_PP2O; -#else + #else qspi_cfg.pins.io1_pin = MICROPY_QSPI_DATA1; qspi_cfg.pins.io2_pin = MICROPY_QSPI_DATA2; qspi_cfg.pins.io3_pin = MICROPY_QSPI_DATA3; qspi_cfg.prot_if.readoc = NRF_QSPI_READOC_READ4IO; qspi_cfg.prot_if.writeoc = NRF_QSPI_WRITEOC_PP4O; -#endif + #endif // No callback for blocking API nrfx_qspi_init(&qspi_cfg, NULL, NULL); } -void spi_flash_init_device(const external_flash_device* device) { +void spi_flash_init_device(const external_flash_device *device) { check_quad_enable(device); // Switch to single output line if the device doesn't support quad programs. @@ -236,5 +234,5 @@ void spi_flash_init_device(const external_flash_device* device) { sckfreq += 1; } NRF_QSPI->IFCONFIG1 &= ~QSPI_IFCONFIG1_SCKFREQ_Msk; - NRF_QSPI->IFCONFIG1 |= sckfreq << QSPI_IFCONFIG1_SCKFREQ_Pos; + NRF_QSPI->IFCONFIG1 |= sckfreq << QSPI_IFCONFIG1_SCKFREQ_Pos; } diff --git a/ports/nrf/supervisor/serial.c b/ports/nrf/supervisor/serial.c index 2c2c0116fb..10bdb2819a 100644 --- a/ports/nrf/supervisor/serial.c +++ b/ports/nrf/supervisor/serial.c @@ -47,7 +47,7 @@ bool serial_connected(void) { } char serial_read(void) { - return (char) ble_uart_rx_chr(); + return (char)ble_uart_rx_chr(); } bool serial_bytes_available(void) { @@ -101,7 +101,7 @@ bool serial_bytes_available(void) { return nrf_uarte_event_check(serial_instance.p_reg, NRF_UARTE_EVENT_RXDRDY); } -void serial_write(const char* text) { +void serial_write(const char *text) { serial_write_substring(text, strlen(text)); } @@ -111,15 +111,15 @@ void serial_write_substring(const char *text, uint32_t len) { } // EasyDMA can only access SRAM - uint8_t * tx_buf = (uint8_t*) text; - if ( !nrfx_is_in_ram(text) ) { - tx_buf = (uint8_t *) m_malloc(len, false); + uint8_t *tx_buf = (uint8_t *)text; + if (!nrfx_is_in_ram(text)) { + tx_buf = (uint8_t *)m_malloc(len, false); memcpy(tx_buf, text, len); } nrfx_uarte_tx(&serial_instance, tx_buf, len); - if ( !nrfx_is_in_ram(text) ) { + if (!nrfx_is_in_ram(text)) { m_free(tx_buf); } } diff --git a/ports/nrf/supervisor/usb.c b/ports/nrf/supervisor/usb.c index 771e86ce03..3ca9b8365d 100644 --- a/ports/nrf/supervisor/usb.c +++ b/ports/nrf/supervisor/usb.c @@ -53,25 +53,25 @@ void init_usb_hardware(void) { static bool first_call = true; uint32_t usb_reg; -#ifdef SOFTDEVICE_PRESENT + #ifdef SOFTDEVICE_PRESENT uint8_t sd_en = false; - (void) sd_softdevice_is_enabled(&sd_en); + (void)sd_softdevice_is_enabled(&sd_en); - if ( sd_en ) { + if (sd_en) { sd_power_usbdetected_enable(true); sd_power_usbpwrrdy_enable(true); sd_power_usbremoved_enable(true); sd_power_usbregstatus_get(&usb_reg); - }else -#endif + } else + #endif { // Power module init const nrfx_power_config_t pwr_cfg = { 0 }; nrfx_power_init(&pwr_cfg); // Register tusb function as USB power handler - const nrfx_power_usbevt_config_t config = { .handler = (nrfx_power_usb_event_handler_t) tusb_hal_nrf_power_event }; + const nrfx_power_usbevt_config_t config = { .handler = (nrfx_power_usb_event_handler_t)tusb_hal_nrf_power_event }; nrfx_power_usbevt_init(&config); nrfx_power_usbevt_enable(); @@ -79,13 +79,13 @@ void init_usb_hardware(void) { usb_reg = NRF_POWER->USBREGSTATUS; } - if ( first_call ) { + if (first_call) { first_call = false; - if ( usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk ) { + if (usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk) { tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_DETECTED); } - if ( usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk ) { + if (usb_reg & POWER_USBREGSTATUS_OUTPUTRDY_Msk) { tusb_hal_nrf_power_event(NRFX_POWER_USB_EVT_READY); } } diff --git a/ports/raspberrypi/audio_dma.c b/ports/raspberrypi/audio_dma.c index ccf08b1b49..28a80a770c 100644 --- a/ports/raspberrypi/audio_dma.c +++ b/ports/raspberrypi/audio_dma.c @@ -49,8 +49,8 @@ void audio_dma_reset(void) { } } -void audio_dma_convert_signed(audio_dma_t* dma, uint8_t* buffer, uint32_t buffer_length, - uint8_t** output_buffer, uint32_t* output_buffer_length) { +void audio_dma_convert_signed(audio_dma_t *dma, uint8_t *buffer, uint32_t buffer_length, + uint8_t **output_buffer, uint32_t *output_buffer_length) { if (dma->first_buffer_free) { *output_buffer = dma->first_buffer; } else { @@ -59,9 +59,9 @@ void audio_dma_convert_signed(audio_dma_t* dma, uint8_t* buffer, uint32_t buffer #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" if (dma->signed_to_unsigned || - dma->unsigned_to_signed || - dma->sample_spacing > 1 || - (dma->sample_resolution != dma->output_resolution)) { + dma->unsigned_to_signed || + dma->sample_spacing > 1 || + (dma->sample_resolution != dma->output_resolution)) { *output_buffer_length = buffer_length / dma->sample_spacing; uint32_t out_i = 0; if (dma->sample_resolution <= 8 && dma->output_resolution > 8) { @@ -69,22 +69,22 @@ void audio_dma_convert_signed(audio_dma_t* dma, uint8_t* buffer, uint32_t buffer for (uint32_t i = 0; i < buffer_length; i += dma->sample_spacing) { if (dma->signed_to_unsigned) { - ((uint16_t*) *output_buffer)[out_i] = ((uint16_t) ((int8_t*) buffer)[i] + 0x80) << shift; + ((uint16_t *)*output_buffer)[out_i] = ((uint16_t)((int8_t *)buffer)[i] + 0x80) << shift; } else if (dma->unsigned_to_signed) { - ((int16_t*) *output_buffer)[out_i] = ((int16_t) ((uint8_t*) buffer)[i] - 0x80) << shift; + ((int16_t *)*output_buffer)[out_i] = ((int16_t)((uint8_t *)buffer)[i] - 0x80) << shift; } else { - ((uint16_t*) *output_buffer)[out_i] = ((uint16_t) ((uint8_t*) buffer)[i]) << shift; + ((uint16_t *)*output_buffer)[out_i] = ((uint16_t)((uint8_t *)buffer)[i]) << shift; } out_i += 1; } } else if (dma->sample_resolution <= 8 && dma->output_resolution <= 8) { for (uint32_t i = 0; i < buffer_length; i += dma->sample_spacing) { if (dma->signed_to_unsigned) { - ((uint8_t*) *output_buffer)[out_i] = ((int8_t*) buffer)[i] + 0x80; + ((uint8_t *)*output_buffer)[out_i] = ((int8_t *)buffer)[i] + 0x80; } else if (dma->unsigned_to_signed) { - ((int8_t*) *output_buffer)[out_i] = ((uint8_t*) buffer)[i] - 0x80; + ((int8_t *)*output_buffer)[out_i] = ((uint8_t *)buffer)[i] - 0x80; } else { - ((uint8_t*) *output_buffer)[out_i] = ((uint8_t*) buffer)[i]; + ((uint8_t *)*output_buffer)[out_i] = ((uint8_t *)buffer)[i]; } out_i += 1; } @@ -92,17 +92,17 @@ void audio_dma_convert_signed(audio_dma_t* dma, uint8_t* buffer, uint32_t buffer size_t shift = 16 - dma->output_resolution; for (uint32_t i = 0; i < buffer_length / 2; i += dma->sample_spacing) { if (dma->signed_to_unsigned) { - ((uint16_t*) *output_buffer)[out_i] = ((int16_t*) buffer)[i] + 0x8000; - } else if (dma->unsigned_to_signed) { - ((int16_t*) *output_buffer)[out_i] = ((uint16_t*) buffer)[i] - 0x8000; + ((uint16_t *)*output_buffer)[out_i] = ((int16_t *)buffer)[i] + 0x8000; + } else if (dma->unsigned_to_signed) { + ((int16_t *)*output_buffer)[out_i] = ((uint16_t *)buffer)[i] - 0x8000; } else { - ((uint16_t*) *output_buffer)[out_i] = ((uint16_t*) buffer)[i]; + ((uint16_t *)*output_buffer)[out_i] = ((uint16_t *)buffer)[i]; } if (dma->output_resolution < 16) { if (dma->output_signed) { - ((int16_t*) *output_buffer)[out_i] = ((int16_t*) *output_buffer)[out_i] >> shift; + ((int16_t *)*output_buffer)[out_i] = ((int16_t *)*output_buffer)[out_i] >> shift; } else { - ((uint16_t*) *output_buffer)[out_i] = ((uint16_t*) *output_buffer)[out_i] >> shift; + ((uint16_t *)*output_buffer)[out_i] = ((uint16_t *)*output_buffer)[out_i] >> shift; } } out_i += 1; @@ -116,17 +116,17 @@ void audio_dma_convert_signed(audio_dma_t* dma, uint8_t* buffer, uint32_t buffer dma->first_buffer_free = !dma->first_buffer_free; } -void audio_dma_load_next_block(audio_dma_t* dma) { +void audio_dma_load_next_block(audio_dma_t *dma) { uint8_t dma_channel = dma->channel[1]; if (dma->first_channel_free) { dma_channel = dma->channel[0]; } dma->first_channel_free = !dma->first_channel_free; - uint8_t* output_buffer; + uint8_t *output_buffer; uint32_t output_buffer_length; audioio_get_buffer_result_t get_buffer_result; - uint8_t* buffer; + uint8_t *buffer; uint32_t buffer_length; get_buffer_result = audiosample_get_buffer(dma->sample, dma->single_channel, dma->audio_channel, &buffer, &buffer_length); @@ -151,22 +151,22 @@ void audio_dma_load_next_block(audio_dma_t* dma) { audiosample_reset_buffer(dma->sample, dma->single_channel, dma->audio_channel); } else { // Set channel trigger to ourselves so we don't keep going. - dma_channel_hw_t* c = &dma_hw->ch[dma_channel]; + dma_channel_hw_t *c = &dma_hw->ch[dma_channel]; c->al1_ctrl = (c->al1_ctrl & ~DMA_CH0_CTRL_TRIG_CHAIN_TO_BITS) | (dma_channel << DMA_CH0_CTRL_TRIG_CHAIN_TO_LSB); } } } // Playback should be shutdown before calling this. -audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, - mp_obj_t sample, - bool loop, - bool single_channel, - uint8_t audio_channel, - bool output_signed, - uint8_t output_resolution, - uint32_t output_register_address, - uint8_t dma_trigger_source) { +audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, + mp_obj_t sample, + bool loop, + bool single_channel, + uint8_t audio_channel, + bool output_signed, + uint8_t output_resolution, + uint32_t output_register_address, + uint8_t dma_trigger_source) { // Use two DMA channels to because the DMA can't wrap to itself without the // buffer being power of two aligned. dma->channel[0] = dma_claim_unused_channel(false); @@ -195,24 +195,24 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, bool samples_signed; uint32_t max_buffer_length; audiosample_get_buffer_structure(sample, single_channel, &single_buffer, &samples_signed, - &max_buffer_length, &dma->sample_spacing); + &max_buffer_length, &dma->sample_spacing); // Check to see if we have to scale the resolution up. if (dma->sample_resolution <= 8 && dma->output_resolution > 8) { max_buffer_length *= 2; } if (output_signed != samples_signed || - dma->sample_spacing > 1 || - (dma->sample_resolution != dma->output_resolution)) { + dma->sample_spacing > 1 || + (dma->sample_resolution != dma->output_resolution)) { max_buffer_length /= dma->sample_spacing; - dma->first_buffer = (uint8_t*) m_realloc(dma->first_buffer, max_buffer_length); + dma->first_buffer = (uint8_t *)m_realloc(dma->first_buffer, max_buffer_length); if (dma->first_buffer == NULL) { return AUDIO_DMA_MEMORY_ERROR; } dma->first_buffer_free = true; if (!single_buffer) { - dma->second_buffer = (uint8_t*) m_realloc(dma->second_buffer, max_buffer_length); + dma->second_buffer = (uint8_t *)m_realloc(dma->second_buffer, max_buffer_length); if (dma->second_buffer == NULL) { return AUDIO_DMA_MEMORY_ERROR; } @@ -247,7 +247,7 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, // Chain to the other channel by default. channel_config_set_chain_to(&c, dma->channel[(i + 1) % 2]); dma_channel_set_config(dma->channel[i], &c, false /* trigger */); - dma_channel_set_write_addr(dma->channel[i], (void*) output_register_address, false /* trigger */); + dma_channel_set_write_addr(dma->channel[i], (void *)output_register_address, false /* trigger */); } // We keep the audio_dma_t for internal use and the sample as a root pointer because it @@ -290,7 +290,7 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, return AUDIO_DMA_OK; } -void audio_dma_stop(audio_dma_t* dma) { +void audio_dma_stop(audio_dma_t *dma) { // Disable our interrupts. dma_hw->inte0 &= ~((1 << dma->channel[0]) | (1 << dma->channel[1])); irq_set_mask_enabled(1 << DMA_IRQ_0, false); @@ -322,12 +322,12 @@ void audio_dma_stop(audio_dma_t* dma) { // To pause we simply stop the DMA. It is the responsibility of the output peripheral // to hold the previous value. -void audio_dma_pause(audio_dma_t* dma) { +void audio_dma_pause(audio_dma_t *dma) { dma_hw->ch[dma->channel[0]].al1_ctrl &= ~DMA_CH0_CTRL_TRIG_EN_BITS; dma_hw->ch[dma->channel[1]].al1_ctrl &= ~DMA_CH0_CTRL_TRIG_EN_BITS; } -void audio_dma_resume(audio_dma_t* dma) { +void audio_dma_resume(audio_dma_t *dma) { // Always re-enable the non-busy channel first so it's ready to continue when the busy channel // finishes and chains to it. (An interrupt could make the time between enables long.) size_t first = 0; @@ -340,7 +340,7 @@ void audio_dma_resume(audio_dma_t* dma) { dma_hw->ch[dma->channel[second]].al1_ctrl |= DMA_CH0_CTRL_TRIG_EN_BITS; } -bool audio_dma_get_paused(audio_dma_t* dma) { +bool audio_dma_get_paused(audio_dma_t *dma) { if (dma->channel[0] >= AUDIO_DMA_CHANNEL_COUNT) { return false; } @@ -349,12 +349,12 @@ bool audio_dma_get_paused(audio_dma_t* dma) { return (control & DMA_CH0_CTRL_TRIG_EN_BITS) == 0; } -void audio_dma_init(audio_dma_t* dma) { +void audio_dma_init(audio_dma_t *dma) { dma->first_buffer = NULL; dma->second_buffer = NULL; } -void audio_dma_deinit(audio_dma_t* dma) { +void audio_dma_deinit(audio_dma_t *dma) { m_free(dma->first_buffer); dma->first_buffer = NULL; @@ -362,7 +362,7 @@ void audio_dma_deinit(audio_dma_t* dma) { dma->second_buffer = NULL; } -bool audio_dma_get_playing(audio_dma_t* dma) { +bool audio_dma_get_playing(audio_dma_t *dma) { if (dma->channel[0] == NUM_DMA_CHANNELS) { return false; } @@ -378,7 +378,7 @@ bool audio_dma_get_playing(audio_dma_t* dma) { // WARN(tannewt): DO NOT print from here, or anything it calls. Printing calls // background tasks such as this and causes a stack overflow. STATIC void dma_callback_fun(void *arg) { - audio_dma_t* dma = arg; + audio_dma_t *dma = arg; if (dma == NULL) { return; } @@ -390,8 +390,8 @@ void isr_dma_0(void) { for (size_t i = 0; i < NUM_DMA_CHANNELS; i++) { uint32_t mask = 1 << i; if ((dma_hw->intr & mask) != 0 && MP_STATE_PORT(playing_audio)[i] != NULL) { - audio_dma_t* dma = MP_STATE_PORT(playing_audio)[i]; - background_callback_add(&dma->callback, dma_callback_fun, (void*)dma); + audio_dma_t *dma = MP_STATE_PORT(playing_audio)[i]; + background_callback_add(&dma->callback, dma_callback_fun, (void *)dma); dma_hw->ints0 = mask; } } diff --git a/ports/raspberrypi/audio_dma.h b/ports/raspberrypi/audio_dma.h index 1f739ff737..faececa8df 100644 --- a/ports/raspberrypi/audio_dma.h +++ b/ports/raspberrypi/audio_dma.h @@ -47,8 +47,8 @@ typedef struct { bool first_buffer_free; uint8_t output_resolution; // in bits uint8_t sample_resolution; // in bits - uint8_t* first_buffer; - uint8_t* second_buffer; + uint8_t *first_buffer; + uint8_t *second_buffer; background_callback_t callback; } audio_dma_t; @@ -59,8 +59,8 @@ typedef enum { } audio_dma_result; -void audio_dma_init(audio_dma_t* dma); -void audio_dma_deinit(audio_dma_t* dma); +void audio_dma_init(audio_dma_t *dma); +void audio_dma_deinit(audio_dma_t *dma); void audio_dma_reset(void); // This sets everything up but doesn't start the timer. @@ -72,20 +72,20 @@ void audio_dma_reset(void); // output_signed is true if the dma'd data should be signed. False and it will be unsigned. // output_register_address is the address to copy data to. // dma_trigger_source is the DMA trigger source which cause another copy -audio_dma_result audio_dma_setup_playback(audio_dma_t* dma, - mp_obj_t sample, - bool loop, - bool single_channel, - uint8_t audio_channel, - bool output_signed, - uint8_t output_resolution, - uint32_t output_register_address, - uint8_t dma_trigger_source); +audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, + mp_obj_t sample, + bool loop, + bool single_channel, + uint8_t audio_channel, + bool output_signed, + uint8_t output_resolution, + uint32_t output_register_address, + uint8_t dma_trigger_source); -void audio_dma_stop(audio_dma_t* dma); -bool audio_dma_get_playing(audio_dma_t* dma); -void audio_dma_pause(audio_dma_t* dma); -void audio_dma_resume(audio_dma_t* dma); -bool audio_dma_get_paused(audio_dma_t* dma); +void audio_dma_stop(audio_dma_t *dma); +bool audio_dma_get_playing(audio_dma_t *dma); +void audio_dma_pause(audio_dma_t *dma); +void audio_dma_resume(audio_dma_t *dma); +bool audio_dma_get_paused(audio_dma_t *dma); #endif // MICROPY_INCLUDED_RASPBERRYPI_AUDIO_DMA_OUT_H diff --git a/ports/raspberrypi/background.c b/ports/raspberrypi/background.c index 52f2e4fb4e..4b5190aa27 100644 --- a/ports/raspberrypi/background.c +++ b/ports/raspberrypi/background.c @@ -28,8 +28,10 @@ #include "py/runtime.h" #include "supervisor/port.h" -void port_start_background_task(void) {} -void port_finish_background_task(void) {} +void port_start_background_task(void) { +} +void port_finish_background_task(void) { +} void port_background_task(void) { } diff --git a/ports/raspberrypi/bindings/rp2pio/StateMachine.c b/ports/raspberrypi/bindings/rp2pio/StateMachine.c index 90fd7f95e7..9464159498 100644 --- a/ports/raspberrypi/bindings/rp2pio/StateMachine.c +++ b/ports/raspberrypi/bindings/rp2pio/StateMachine.c @@ -363,13 +363,13 @@ STATIC mp_obj_t rp2pio_statemachine_write(size_t n_args, const mp_obj_t *pos_arg return mp_const_none; } - uint8_t* original_pointer = bufinfo.buf; + uint8_t *original_pointer = bufinfo.buf; int stride_in_bytes = mp_binary_get_size('@', bufinfo.typecode, NULL); if (stride_in_bytes > 4) { mp_raise_ValueError(translate("Buffer elements must be 4 bytes long or less")); } - bool ok = common_hal_rp2pio_statemachine_write(self, ((uint8_t*)bufinfo.buf) + start, length, stride_in_bytes); + bool ok = common_hal_rp2pio_statemachine_write(self, ((uint8_t *)bufinfo.buf) + start, length, stride_in_bytes); if (mp_hal_is_interrupted()) { return mp_const_none; } @@ -413,13 +413,13 @@ STATIC mp_obj_t rp2pio_statemachine_readinto(size_t n_args, const mp_obj_t *pos_ return mp_const_none; } - uint8_t* original_pointer = bufinfo.buf; + uint8_t *original_pointer = bufinfo.buf; int stride_in_bytes = mp_binary_get_size('@', bufinfo.typecode, NULL); if (stride_in_bytes > 4) { mp_raise_ValueError(translate("Buffer elements must be 4 bytes long or less")); } - bool ok = common_hal_rp2pio_statemachine_readinto(self, ((uint8_t*)bufinfo.buf) + start, length, stride_in_bytes); + bool ok = common_hal_rp2pio_statemachine_readinto(self, ((uint8_t *)bufinfo.buf) + start, length, stride_in_bytes); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -484,12 +484,12 @@ STATIC mp_obj_t rp2pio_statemachine_write_readinto(size_t n_args, const mp_obj_t } bool ok = common_hal_rp2pio_statemachine_write_readinto(self, - ((uint8_t*)buf_out_info.buf) + out_start, - out_length, - out_stride_in_bytes, - ((uint8_t*)buf_in_info.buf) + in_start, - in_length, - in_stride_in_bytes); + ((uint8_t *)buf_out_info.buf) + out_start, + out_length, + out_stride_in_bytes, + ((uint8_t *)buf_in_info.buf) + in_start, + in_length, + in_stride_in_bytes); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -594,10 +594,10 @@ STATIC const mp_rom_map_elem_t rp2pio_statemachine_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(rp2pio_statemachine_locals_dict, rp2pio_statemachine_locals_dict_table); const mp_obj_type_t rp2pio_statemachine_type = { - { &mp_type_type }, - .name = MP_QSTR_StateMachine, - .make_new = rp2pio_statemachine_make_new, - .locals_dict = (mp_obj_dict_t*)&rp2pio_statemachine_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_StateMachine, + .make_new = rp2pio_statemachine_make_new, + .locals_dict = (mp_obj_dict_t *)&rp2pio_statemachine_locals_dict, }; rp2pio_statemachine_obj_t *validate_obj_is_statemachine(mp_obj_t obj) { diff --git a/ports/raspberrypi/bindings/rp2pio/StateMachine.h b/ports/raspberrypi/bindings/rp2pio/StateMachine.h index 3a0d4290d5..661bddd815 100644 --- a/ports/raspberrypi/bindings/rp2pio/StateMachine.h +++ b/ports/raspberrypi/bindings/rp2pio/StateMachine.h @@ -37,13 +37,13 @@ extern const mp_obj_type_t rp2pio_statemachine_type; // Construct an underlying SPI object. void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, - const uint16_t* program, size_t program_len, + const uint16_t *program, size_t program_len, size_t frequency, - const uint16_t* init, size_t init_len, - const mcu_pin_obj_t * first_out_pin, uint8_t out_pin_count, uint32_t initial_out_pin_state, uint32_t initial_out_pin_direction, - const mcu_pin_obj_t * first_in_pin, uint8_t in_pin_count, uint32_t pull_pin_up, uint32_t pull_pin_down, - const mcu_pin_obj_t * first_set_pin, uint8_t set_pin_count, uint32_t initial_set_pin_state, uint32_t initial_set_pin_direction, - const mcu_pin_obj_t * first_sideset_pin, uint8_t sideset_pin_count, uint32_t initial_sideset_pin_state, uint32_t initial_sideset_pin_direction, + const uint16_t *init, size_t init_len, + const mcu_pin_obj_t *first_out_pin, uint8_t out_pin_count, uint32_t initial_out_pin_state, uint32_t initial_out_pin_direction, + const mcu_pin_obj_t *first_in_pin, uint8_t in_pin_count, uint32_t pull_pin_up, uint32_t pull_pin_down, + const mcu_pin_obj_t *first_set_pin, uint8_t set_pin_count, uint32_t initial_set_pin_state, uint32_t initial_set_pin_direction, + const mcu_pin_obj_t *first_sideset_pin, uint8_t sideset_pin_count, uint32_t initial_sideset_pin_state, uint32_t initial_sideset_pin_direction, bool exclusive_pin_use, bool auto_pull, uint8_t pull_threshold, bool out_shift_right, bool wait_for_txstall, @@ -60,17 +60,17 @@ void common_hal_rp2pio_statemachine_run(rp2pio_statemachine_obj_t *self, const u bool common_hal_rp2pio_statemachine_write(rp2pio_statemachine_obj_t *self, const uint8_t *data, size_t len, uint8_t stride_in_bytes); bool common_hal_rp2pio_statemachine_readinto(rp2pio_statemachine_obj_t *self, uint8_t *data, size_t len, uint8_t stride_in_bytes); bool common_hal_rp2pio_statemachine_write_readinto(rp2pio_statemachine_obj_t *self, - const uint8_t *data_out, size_t out_len, uint8_t out_stride_in_bytes, - uint8_t *data_in, size_t in_len, uint8_t in_stride_in_bytes); + const uint8_t *data_out, size_t out_len, uint8_t out_stride_in_bytes, + uint8_t *data_in, size_t in_len, uint8_t in_stride_in_bytes); // Return actual state machine frequency. -uint32_t common_hal_rp2pio_statemachine_get_frequency(rp2pio_statemachine_obj_t* self); -void common_hal_rp2pio_statemachine_set_frequency(rp2pio_statemachine_obj_t* self, uint32_t frequency); +uint32_t common_hal_rp2pio_statemachine_get_frequency(rp2pio_statemachine_obj_t *self); +void common_hal_rp2pio_statemachine_set_frequency(rp2pio_statemachine_obj_t *self, uint32_t frequency); -bool common_hal_rp2pio_statemachine_get_rxstall(rp2pio_statemachine_obj_t* self); +bool common_hal_rp2pio_statemachine_get_rxstall(rp2pio_statemachine_obj_t *self); void common_hal_rp2pio_statemachine_clear_rxfifo(rp2pio_statemachine_obj_t *self); size_t common_hal_rp2pio_statemachine_get_in_waiting(rp2pio_statemachine_obj_t *self); -void common_hal_rp2pio_statemachine_set_interrupt_handler(rp2pio_statemachine_obj_t *self, void(*handler)(void*), void *arg, int mask); +void common_hal_rp2pio_statemachine_set_interrupt_handler(rp2pio_statemachine_obj_t *self, void (*handler)(void *), void *arg, int mask); #endif // MICROPY_INCLUDED_RASPBERRYPI_BINDINGS_RP2PIO_STATEMACHINE_H diff --git a/ports/raspberrypi/bindings/rp2pio/__init__.c b/ports/raspberrypi/bindings/rp2pio/__init__.c index 7eab423e9e..68f7cf3019 100644 --- a/ports/raspberrypi/bindings/rp2pio/__init__.c +++ b/ports/raspberrypi/bindings/rp2pio/__init__.c @@ -56,5 +56,5 @@ STATIC MP_DEFINE_CONST_DICT(rp2pio_module_globals, rp2pio_module_globals_table); const mp_obj_module_t rp2pio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&rp2pio_module_globals, + .globals = (mp_obj_dict_t *)&rp2pio_module_globals, }; diff --git a/ports/raspberrypi/boards/raspberry_pi_pico/board.c b/ports/raspberrypi/boards/raspberry_pi_pico/board.c index 80ec5de32b..67486d4c23 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico/board.c +++ b/ports/raspberrypi/boards/raspberry_pi_pico/board.c @@ -26,8 +26,7 @@ #include "supervisor/board.h" -void board_init(void) -{ +void board_init(void) { } bool board_requests_safe_mode(void) { diff --git a/ports/raspberrypi/common-hal/analogio/AnalogIn.c b/ports/raspberrypi/common-hal/analogio/AnalogIn.c index c51a749295..7db2956b03 100644 --- a/ports/raspberrypi/common-hal/analogio/AnalogIn.c +++ b/ports/raspberrypi/common-hal/analogio/AnalogIn.c @@ -64,7 +64,7 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { uint16_t value = adc_read(); // Map value to from 12 to 16 bits - return (value << 4); + return value << 4; } float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t *self) { diff --git a/ports/raspberrypi/common-hal/analogio/AnalogIn.h b/ports/raspberrypi/common-hal/analogio/AnalogIn.h index ee9976e348..c322a6776f 100644 --- a/ports/raspberrypi/common-hal/analogio/AnalogIn.h +++ b/ports/raspberrypi/common-hal/analogio/AnalogIn.h @@ -33,7 +33,7 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t * pin; + const mcu_pin_obj_t *pin; } analogio_analogin_obj_t; void analogin_init(void); diff --git a/ports/raspberrypi/common-hal/analogio/AnalogOut.c b/ports/raspberrypi/common-hal/analogio/AnalogOut.c index adafa15d5c..7afa773d30 100644 --- a/ports/raspberrypi/common-hal/analogio/AnalogOut.c +++ b/ports/raspberrypi/common-hal/analogio/AnalogOut.c @@ -33,7 +33,7 @@ #include "py/runtime.h" #include "supervisor/shared/translate.h" -void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, const mcu_pin_obj_t *pin) { mp_raise_RuntimeError(translate("AnalogOut functionality not supported")); } diff --git a/ports/raspberrypi/common-hal/audiobusio/I2SOut.c b/ports/raspberrypi/common-hal/audiobusio/I2SOut.c index fa5852fce5..5f77a74a5e 100644 --- a/ports/raspberrypi/common-hal/audiobusio/I2SOut.c +++ b/ports/raspberrypi/common-hal/audiobusio/I2SOut.c @@ -101,18 +101,19 @@ void i2sout_reset(void) { } // Caller validates that pins are free. -void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, - const mcu_pin_obj_t* bit_clock, const mcu_pin_obj_t* word_select, - const mcu_pin_obj_t* data, bool left_justified) { +void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, + const mcu_pin_obj_t *bit_clock, const mcu_pin_obj_t *word_select, + const mcu_pin_obj_t *data, bool left_justified) { if (bit_clock->number != word_select->number - 1) { mp_raise_ValueError(translate("Bit clock and word select must be sequential pins")); } - const uint16_t* program = i2s_program; + const uint16_t *program = i2s_program; size_t program_len = sizeof(i2s_program) / sizeof(i2s_program[0]); if (left_justified) { program = i2s_program_left_justified; - program_len = sizeof(i2s_program_left_justified) / sizeof(i2s_program_left_justified[0]);; + program_len = sizeof(i2s_program_left_justified) / sizeof(i2s_program_left_justified[0]); + ; } // Use the state machine to manage pins. @@ -134,11 +135,11 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, audio_dma_init(&self->dma); } -bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t *self) { return common_hal_rp2pio_statemachine_deinited(&self->state_machine); } -void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self) { if (common_hal_audiobusio_i2sout_deinited(self)) { return; } @@ -146,8 +147,8 @@ void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self) { common_hal_rp2pio_statemachine_deinit(&self->state_machine); } -void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, - mp_obj_t sample, bool loop) { +void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, + mp_obj_t sample, bool loop) { if (common_hal_audiobusio_i2sout_get_playing(self)) { common_hal_audiobusio_i2sout_stop(self); } @@ -178,7 +179,7 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, 0, // audio channel true, // output signed bits_per_sample, - (uint32_t) &self->state_machine.pio->txf[self->state_machine.state_machine], // output register + (uint32_t)&self->state_machine.pio->txf[self->state_machine.state_machine], // output register self->state_machine.tx_dreq); // data request line if (result == AUDIO_DMA_DMA_BUSY) { @@ -194,21 +195,21 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, self->playing = true; } -void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t *self) { audio_dma_pause(&self->dma); } -void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t *self) { // Maybe: Clear any overrun/underrun errors audio_dma_resume(&self->dma); } -bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t *self) { return audio_dma_get_paused(&self->dma); } -void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t* self) { +void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t *self) { audio_dma_stop(&self->dma); common_hal_rp2pio_statemachine_stop(&self->state_machine); @@ -216,7 +217,7 @@ void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t* self) { self->playing = false; } -bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t* self) { +bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t *self) { bool playing = audio_dma_get_playing(&self->dma); if (!playing && self->playing) { common_hal_audiobusio_i2sout_stop(self); diff --git a/ports/raspberrypi/common-hal/audiobusio/PDMIn.c b/ports/raspberrypi/common-hal/audiobusio/PDMIn.c index 8836602712..bbcfbb805a 100644 --- a/ports/raspberrypi/common-hal/audiobusio/PDMIn.c +++ b/ports/raspberrypi/common-hal/audiobusio/PDMIn.c @@ -50,13 +50,13 @@ const uint16_t pdmin[] = { }; // Caller validates that pins are free. -void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t* self, - const mcu_pin_obj_t* clock_pin, - const mcu_pin_obj_t* data_pin, - uint32_t sample_rate, - uint8_t bit_depth, - bool mono, - uint8_t oversample) { +void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, + const mcu_pin_obj_t *clock_pin, + const mcu_pin_obj_t *data_pin, + uint32_t sample_rate, + uint8_t bit_depth, + bool mono, + uint8_t oversample) { if (!(bit_depth == 16 || bit_depth == 8) || !mono || oversample != OVERSAMPLING) { mp_raise_NotImplementedError(translate("Only 8 or 16 bit mono with " MP_STRINGIFY(OVERSAMPLING) "x oversampling is supported.")); } @@ -77,30 +77,30 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t* self, false, 32, true); // in settings uint32_t actual_frequency = common_hal_rp2pio_statemachine_get_frequency(&self->state_machine); - if (actual_frequency < MIN_MIC_CLOCK) { + if (actual_frequency < MIN_MIC_CLOCK) { mp_raise_ValueError(translate("sampling rate out of range")); } - self->sample_rate = actual_frequency / oversample; + self->sample_rate = actual_frequency / oversample; self->bit_depth = bit_depth; } -bool common_hal_audiobusio_pdmin_deinited(audiobusio_pdmin_obj_t* self) { +bool common_hal_audiobusio_pdmin_deinited(audiobusio_pdmin_obj_t *self) { return common_hal_rp2pio_statemachine_deinited(&self->state_machine); } -void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t* self) { +void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t *self) { if (common_hal_audiobusio_pdmin_deinited(self)) { return; } return common_hal_rp2pio_statemachine_deinit(&self->state_machine); } -uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t* self) { +uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t *self) { return self->bit_depth; } -uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t* self) { +uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t *self) { return self->sample_rate; } @@ -114,7 +114,7 @@ uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t* sel // higher sample rate than specified. Then after the audio is // recorded, a more expensive filter non-real-time filter could be // used to down-sample and low-pass. -const uint16_t sinc_filter [OVERSAMPLING] = { +const uint16_t sinc_filter[OVERSAMPLING] = { 0, 2, 9, 21, 39, 63, 94, 132, 179, 236, 302, 379, 467, 565, 674, 792, 920, 1055, 1196, 1341, 1487, 1633, 1776, 1913, @@ -125,20 +125,20 @@ const uint16_t sinc_filter [OVERSAMPLING] = { 94, 63, 39, 21, 9, 2, 0, 0 }; -#define REPEAT_32_TIMES(X) do { X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X } while(0) +#define REPEAT_32_TIMES(X) do { X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X X } while (0) static uint16_t filter_sample(uint32_t pdm_samples[2]) { uint16_t running_sum = 0; const uint16_t *filter_ptr = sinc_filter; for (uint8_t i = 0; i < 2; i++) { uint32_t pdm_sample = pdm_samples[i]; - REPEAT_32_TIMES( { - if (pdm_sample & 0x1) { - running_sum += *filter_ptr; - } - filter_ptr++; - pdm_sample >>= 1; + REPEAT_32_TIMES({ + if (pdm_sample & 0x1) { + running_sum += *filter_ptr; } + filter_ptr++; + pdm_sample >>= 1; + } ); } return running_sum; @@ -146,20 +146,20 @@ static uint16_t filter_sample(uint32_t pdm_samples[2]) { // output_buffer may be a byte buffer or a halfword buffer. // output_buffer_length is the number of slots, not the number of bytes. -uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* self, - uint16_t* output_buffer, uint32_t output_buffer_length) { +uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t *self, + uint16_t *output_buffer, uint32_t output_buffer_length) { uint32_t samples[2]; size_t output_count = 0; common_hal_rp2pio_statemachine_clear_rxfifo(&self->state_machine); // Do one read to get the mic going and throw it away. - common_hal_rp2pio_statemachine_readinto(&self->state_machine, (uint8_t*) samples, 2 * sizeof(uint32_t), sizeof(uint32_t)); + common_hal_rp2pio_statemachine_readinto(&self->state_machine, (uint8_t *)samples, 2 * sizeof(uint32_t), sizeof(uint32_t)); while (output_count < output_buffer_length && !common_hal_rp2pio_statemachine_get_rxstall(&self->state_machine)) { - common_hal_rp2pio_statemachine_readinto(&self->state_machine, (uint8_t*) samples, 2 * sizeof(uint32_t), sizeof(uint32_t)); + common_hal_rp2pio_statemachine_readinto(&self->state_machine, (uint8_t *)samples, 2 * sizeof(uint32_t), sizeof(uint32_t)); // Call filter_sample just one place so it can be inlined. uint16_t value = filter_sample(samples); if (self->bit_depth == 8) { // Truncate to 8 bits. - ((uint8_t*) output_buffer)[output_count] = value >> 8; + ((uint8_t *)output_buffer)[output_count] = value >> 8; } else { output_buffer[output_count] = value; } @@ -169,6 +169,6 @@ uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* se return output_count; } -void common_hal_audiobusio_pdmin_record_to_file(audiobusio_pdmin_obj_t* self, uint8_t* buffer, uint32_t length) { +void common_hal_audiobusio_pdmin_record_to_file(audiobusio_pdmin_obj_t *self, uint8_t *buffer, uint32_t length) { } diff --git a/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c index 57605a1fb4..4fef53ff0a 100644 --- a/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +++ b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c @@ -53,8 +53,8 @@ void audiopwmout_reset() { } // Caller validates that pins are free. -void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t* self, - const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t quiescent_value) { +void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t *self, + const mcu_pin_obj_t *left_channel, const mcu_pin_obj_t *right_channel, uint16_t quiescent_value) { if (left_channel != NULL && right_channel != NULL) { if (pwm_gpio_to_slice_num(left_channel->number) != pwm_gpio_to_slice_num(right_channel->number)) { mp_raise_ValueError(translate("Pins must share PWM slice")); @@ -106,11 +106,11 @@ void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t* s self->quiescent_value = quiescent_value; } -bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t* self) { +bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t *self) { return common_hal_pwmio_pwmout_deinited(&self->left_pwm); } -void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t* self) { +void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t *self) { if (common_hal_audiopwmio_pwmaudioout_deinited(self)) { return; } @@ -125,7 +125,7 @@ void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t* self audio_dma_deinit(&self->dma); } -void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, mp_obj_t sample, bool loop) { +void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, mp_obj_t sample, bool loop) { if (common_hal_audiopwmio_pwmaudioout_get_playing(self)) { common_hal_audiopwmio_pwmaudioout_stop(self); } @@ -141,7 +141,7 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, if (pacing_timer == NUM_DMA_TIMERS) { mp_raise_RuntimeError(translate("No DMA pacing timer found")); } - uint32_t tx_register = (uint32_t) &pwm_hw->slice[self->left_pwm.slice].cc; + uint32_t tx_register = (uint32_t)&pwm_hw->slice[self->left_pwm.slice].cc; if (common_hal_pwmio_pwmout_deinited(&self->right_pwm)) { // Shift the destination if we are outputting to the second PWM channel. tx_register += self->left_pwm.channel * sizeof(uint16_t); @@ -157,7 +157,7 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, 0, // audio channel false, // output signed 10, - (uint32_t) tx_register, // output register + (uint32_t)tx_register, // output register 0x3b + pacing_timer); // data request line if (result == AUDIO_DMA_DMA_BUSY) { @@ -206,14 +206,14 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, dma_hw->timer[pacing_timer] = best_numerator << 16 | best_denominator; } -void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t* self) { +void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t *self) { dma_hw->timer[self->pacing_timer] = 0; self->pacing_timer = NUM_DMA_TIMERS; audio_dma_stop(&self->dma); } -bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t* self) { +bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t *self) { bool playing = audio_dma_get_playing(&self->dma); if (!playing && self->pacing_timer < NUM_DMA_TIMERS) { dma_hw->timer[self->pacing_timer] = 0; @@ -222,14 +222,14 @@ bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t* return playing; } -void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t* self) { +void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t *self) { audio_dma_pause(&self->dma); } -void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t* self) { +void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t *self) { audio_dma_resume(&self->dma); } -bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t* self) { +bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t *self) { return audio_dma_get_paused(&self->dma); } diff --git a/ports/raspberrypi/common-hal/busio/I2C.c b/ports/raspberrypi/common-hal/busio/I2C.c index cb0d73e75b..c9f89fadd8 100644 --- a/ports/raspberrypi/common-hal/busio/I2C.c +++ b/ports/raspberrypi/common-hal/busio/I2C.c @@ -42,7 +42,7 @@ #define BUS_TIMEOUT_US 1000000 STATIC bool never_reset_i2c[2]; -STATIC i2c_inst_t* i2c[2] = {i2c0, i2c1}; +STATIC i2c_inst_t *i2c[2] = {i2c0, i2c1}; void reset_i2c(void) { for (size_t i = 0; i < 2; i++) { @@ -55,7 +55,7 @@ void reset_i2c(void) { } void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, - const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, uint32_t frequency, uint32_t timeout) { + const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint32_t frequency, uint32_t timeout) { self->peripheral = NULL; // I2C pins have a regular pattern. SCL is always odd and SDA is even. They match up in pairs // so we can divide by two to get the instance. This pattern repeats. @@ -73,7 +73,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, mp_raise_ValueError(translate("Unsupported baudrate")); } -#if CIRCUITPY_REQUIRE_I2C_PULLUPS + #if CIRCUITPY_REQUIRE_I2C_PULLUPS // Test that the pins are in a high state. (Hopefully indicating they are pulled up.) gpio_set_function(sda->number, GPIO_FUNC_SIO); gpio_set_function(scl->number, GPIO_FUNC_SIO); @@ -96,7 +96,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, reset_pin_number(scl->number); mp_raise_RuntimeError(translate("No pull up found on SDA or SCL; check your wiring")); } -#endif + #endif // Create a bitbangio.I2C object to do short writes. // Must be done before setting up the I2C pins, since they will be @@ -104,7 +104,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, // // Sets pins to open drain, high, and input. shared_module_bitbangio_i2c_construct(&self->bitbangio_i2c, scl, sda, - frequency, timeout); + frequency, timeout); self->baudrate = i2c_init(self->peripheral, frequency); @@ -157,7 +157,7 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { } uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, - const uint8_t *data, size_t len, bool transmit_stop_bit) { + const uint8_t *data, size_t len, bool transmit_stop_bit) { if (len <= 2) { // The RP2040 I2C peripheral will not do writes 2 bytes or less long. // So use bitbangio.I2C to do the write. @@ -170,7 +170,7 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, gpio_put(self->sda_pin, false); uint8_t status = shared_module_bitbangio_i2c_write(&self->bitbangio_i2c, - addr, data, len, transmit_stop_bit); + addr, data, len, transmit_stop_bit); // The pins must be set back to GPIO_FUNC_I2C in the order given here, // SCL first, otherwise reads will hang. @@ -195,7 +195,7 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *data, size_t len) { + uint8_t *data, size_t len) { int result = i2c_read_timeout_us(self->peripheral, addr, data, len, false, BUS_TIMEOUT_US); if (result == len) { return 0; diff --git a/ports/raspberrypi/common-hal/busio/I2C.h b/ports/raspberrypi/common-hal/busio/I2C.h index 651054a048..dbaede1f56 100644 --- a/ports/raspberrypi/common-hal/busio/I2C.h +++ b/ports/raspberrypi/common-hal/busio/I2C.h @@ -36,7 +36,7 @@ typedef struct { mp_obj_base_t base; - i2c_inst_t * peripheral; + i2c_inst_t *peripheral; bitbangio_i2c_obj_t bitbangio_i2c; bool has_lock; uint baudrate; diff --git a/ports/raspberrypi/common-hal/busio/SPI.c b/ports/raspberrypi/common-hal/busio/SPI.c index b157ae3eb0..0fc71136e6 100644 --- a/ports/raspberrypi/common-hal/busio/SPI.c +++ b/ports/raspberrypi/common-hal/busio/SPI.c @@ -41,7 +41,7 @@ #define NO_INSTANCE 0xff STATIC bool never_reset_spi[2]; -STATIC spi_inst_t* spi[2] = {spi0, spi1}; +STATIC spi_inst_t *spi[2] = {spi0, spi1}; void reset_spi(void) { for (size_t i = 0; i < 2; i++) { @@ -54,8 +54,8 @@ void reset_spi(void) { } void common_hal_busio_spi_construct(busio_spi_obj_t *self, - const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, - const mcu_pin_obj_t * miso) { + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso) { size_t instance_index = NO_INSTANCE; if (clock->number % 4 == 2) { instance_index = (clock->number / 8) % 2; @@ -136,7 +136,7 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, - uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { + uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { if (baudrate == self->target_frequency && polarity == self->polarity && phase == self->phase && @@ -244,7 +244,7 @@ static bool _transfer(busio_spi_obj_t *self, while (!mp_hal_is_interrupted() && (rx_remaining || tx_remaining)) { if (tx_remaining && spi_is_writable(self->peripheral) && rx_remaining - tx_remaining < fifo_depth) { - spi_get_hw(self->peripheral)->dr = (uint32_t) *data_out; + spi_get_hw(self->peripheral)->dr = (uint32_t)*data_out; // Increment only if the buffer is the transfer length. It's 1 otherwise. if (out_len == len) { data_out++; @@ -252,7 +252,7 @@ static bool _transfer(busio_spi_obj_t *self, --tx_remaining; } if (rx_remaining && spi_is_readable(self->peripheral)) { - *data_in = (uint8_t) spi_get_hw(self->peripheral)->dr; + *data_in = (uint8_t)spi_get_hw(self->peripheral)->dr; // Increment only if the buffer is the transfer length. It's 1 otherwise. if (in_len == len) { data_in++; @@ -266,29 +266,29 @@ static bool _transfer(busio_spi_obj_t *self, } bool common_hal_busio_spi_write(busio_spi_obj_t *self, - const uint8_t *data, size_t len) { + const uint8_t *data, size_t len) { uint32_t data_in; - return _transfer(self, data, len, (uint8_t*) &data_in, MIN(len, 4)); + return _transfer(self, data, len, (uint8_t *)&data_in, MIN(len, 4)); } bool common_hal_busio_spi_read(busio_spi_obj_t *self, - uint8_t *data, size_t len, uint8_t write_value) { + uint8_t *data, size_t len, uint8_t write_value) { uint32_t data_out = write_value << 24 | write_value << 16 | write_value << 8 | write_value; - return _transfer(self, (const uint8_t*) &data_out, MIN(4, len), data, len); + return _transfer(self, (const uint8_t *)&data_out, MIN(4, len), data, len); } bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { return _transfer(self, data_out, len, data_in, len); } -uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self) { +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { return self->real_frequency; } -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { return self->phase; } -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { return self->polarity; } diff --git a/ports/raspberrypi/common-hal/busio/SPI.h b/ports/raspberrypi/common-hal/busio/SPI.h index 981db46d41..b76dbbf9db 100644 --- a/ports/raspberrypi/common-hal/busio/SPI.h +++ b/ports/raspberrypi/common-hal/busio/SPI.h @@ -35,11 +35,11 @@ typedef struct { mp_obj_base_t base; - spi_inst_t * peripheral; + spi_inst_t *peripheral; bool has_lock; - const mcu_pin_obj_t* clock; - const mcu_pin_obj_t* MOSI; - const mcu_pin_obj_t* MISO; + const mcu_pin_obj_t *clock; + const mcu_pin_obj_t *MOSI; + const mcu_pin_obj_t *MISO; uint32_t target_frequency; int32_t real_frequency; uint8_t polarity; diff --git a/ports/raspberrypi/common-hal/busio/UART.c b/ports/raspberrypi/common-hal/busio/UART.c index 1bc1211777..2d8ff099eb 100644 --- a/ports/raspberrypi/common-hal/busio/UART.c +++ b/ports/raspberrypi/common-hal/busio/UART.c @@ -61,7 +61,7 @@ void never_reset_uart(uint8_t num) { uart_status[num] = STATUS_NEVER_RESET; } -static uint8_t pin_init(const uint8_t uart, const mcu_pin_obj_t * pin, const uint8_t pin_type) { +static uint8_t pin_init(const uint8_t uart, const mcu_pin_obj_t *pin, const uint8_t pin_type) { if (pin == NULL) { return NO_PIN; } @@ -73,11 +73,11 @@ static uint8_t pin_init(const uint8_t uart, const mcu_pin_obj_t * pin, const uin return pin->number; } -static busio_uart_obj_t* active_uarts[NUM_UARTS]; +static busio_uart_obj_t *active_uarts[NUM_UARTS]; -static void _copy_into_ringbuf(ringbuf_t* r, uart_inst_t* uart) { +static void _copy_into_ringbuf(ringbuf_t *r, uart_inst_t *uart) { while (uart_is_readable(uart) && ringbuf_num_empty(r) > 0) { - ringbuf_put(r, (uint8_t) uart_get_hw(uart)->dr); + ringbuf_put(r, (uint8_t)uart_get_hw(uart)->dr); } } @@ -97,12 +97,12 @@ static void uart1_callback(void) { } void common_hal_busio_uart_construct(busio_uart_obj_t *self, - const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, - const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, - const mcu_pin_obj_t * rs485_dir, bool rs485_invert, - uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, - mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, - bool sigint_enabled) { + const mcu_pin_obj_t *tx, const mcu_pin_obj_t *rx, + const mcu_pin_obj_t *rts, const mcu_pin_obj_t *cts, + const mcu_pin_obj_t *rs485_dir, bool rs485_invert, + uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, + mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, + bool sigint_enabled) { if (bits > 8) { mp_raise_ValueError(translate("Invalid word/bit length")); @@ -223,7 +223,7 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t // Check if we still need to read more data. if (len > total_read) { - len-=total_read; + len -= total_read; uint64_t start_ticks = supervisor_ticks_ms64(); // Busy-wait until timeout or until we've read enough chars. while (len > 0 && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms)) { @@ -272,7 +272,7 @@ void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrat } mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { - return (mp_float_t) (self->timeout_ms / 1000.0f); + return (mp_float_t)(self->timeout_ms / 1000.0f); } void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { @@ -296,7 +296,7 @@ void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self) { // Throw away the FIFO contents too. while (uart_is_readable(self->uart)) { - (void) uart_get_hw(self->uart)->dr; + (void)uart_get_hw(self->uart)->dr; } irq_set_enabled(self->uart_irq_id, true); } diff --git a/ports/raspberrypi/common-hal/busio/UART.h b/ports/raspberrypi/common-hal/busio/UART.h index 4c07de240b..f6978fd1d2 100644 --- a/ports/raspberrypi/common-hal/busio/UART.h +++ b/ports/raspberrypi/common-hal/busio/UART.h @@ -42,7 +42,7 @@ typedef struct { uint8_t uart_irq_id; uint32_t baudrate; uint32_t timeout_ms; - uart_inst_t * uart; + uart_inst_t *uart; ringbuf_t ringbuf; } busio_uart_obj_t; diff --git a/ports/raspberrypi/common-hal/countio/Counter.c b/ports/raspberrypi/common-hal/countio/Counter.c index 69629a0848..2dcd1de123 100644 --- a/ports/raspberrypi/common-hal/countio/Counter.c +++ b/ports/raspberrypi/common-hal/countio/Counter.c @@ -11,8 +11,8 @@ #include "src/rp2_common/hardware_irq/include/hardware/irq.h" -void common_hal_countio_counter_construct(countio_counter_obj_t* self, - const mcu_pin_obj_t* pin_a) { +void common_hal_countio_counter_construct(countio_counter_obj_t *self, + const mcu_pin_obj_t *pin_a) { if (pwm_gpio_to_channel(pin_a->number) != PWM_CHAN_B) { mp_raise_RuntimeError(translate("Pin must be on PWM Channel B")); @@ -48,11 +48,11 @@ void common_hal_countio_counter_construct(countio_counter_obj_t* self, pwm_set_enabled(self->slice_num, true); } -bool common_hal_countio_counter_deinited(countio_counter_obj_t* self) { +bool common_hal_countio_counter_deinited(countio_counter_obj_t *self) { return self->pin_a == 0; } -void common_hal_countio_counter_deinit(countio_counter_obj_t* self) { +void common_hal_countio_counter_deinit(countio_counter_obj_t *self) { if (common_hal_countio_counter_deinited(self)) { return; } @@ -69,19 +69,19 @@ void common_hal_countio_counter_deinit(countio_counter_obj_t* self) { self->slice_num = 0; } -mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t* self) { +mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t *self) { self->count += pwm_get_counter(self->slice_num); pwm_set_counter(self->slice_num, 0); return self->count; } -void common_hal_countio_counter_set_count(countio_counter_obj_t* self, - mp_int_t new_count) { +void common_hal_countio_counter_set_count(countio_counter_obj_t *self, + mp_int_t new_count) { pwm_set_counter(self->slice_num, 0); self->count = new_count; } -void common_hal_countio_counter_reset(countio_counter_obj_t* self){ +void common_hal_countio_counter_reset(countio_counter_obj_t *self) { pwm_set_counter(self->slice_num, 0); self->count = 0; } @@ -95,7 +95,7 @@ void counter_interrupt_handler() { ++pos; } - countio_counter_obj_t *self = MP_STATE_PORT(counting)[pos-1]; + countio_counter_obj_t *self = MP_STATE_PORT(counting)[pos - 1]; if (self != NULL) { pwm_clear_irq(self->slice_num); self->count += 65536; diff --git a/ports/raspberrypi/common-hal/countio/__init__.c b/ports/raspberrypi/common-hal/countio/__init__.c index b95b20d153..d47de33e53 100644 --- a/ports/raspberrypi/common-hal/countio/__init__.c +++ b/ports/raspberrypi/common-hal/countio/__init__.c @@ -1 +1 @@ -//No countio module functions +// No countio module functions diff --git a/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c b/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c index a1a23b9ab9..22a61afa3f 100644 --- a/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +++ b/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c @@ -37,7 +37,7 @@ #include "src/rp2_common/hardware_gpio/include/hardware/gpio.h" digitalinout_result_t common_hal_digitalio_digitalinout_construct( - digitalio_digitalinout_obj_t* self, const mcu_pin_obj_t* pin) { + digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { claim_pin(pin); self->pin = pin; self->output = false; @@ -49,15 +49,15 @@ digitalinout_result_t common_hal_digitalio_digitalinout_construct( } void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { never_reset_pin_number(self->pin->number); } -bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t* self) { +bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { return self->pin == NULL; } -void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t* self) { +void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self) { if (common_hal_digitalio_digitalinout_deinited(self)) { return; } @@ -66,22 +66,22 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t* self } void common_hal_digitalio_digitalinout_switch_to_input( - digitalio_digitalinout_obj_t* self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { self->output = false; // This also sets direction to input. common_hal_digitalio_digitalinout_set_pull(self, pull); } digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( - digitalio_digitalinout_obj_t* self, bool value, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, bool value, + digitalio_drive_mode_t drive_mode) { const uint8_t pin = self->pin->number; gpio_disable_pulls(pin); // Turn on "strong" pin driving (more current available). hw_write_masked(&padsbank0_hw->io[pin], - PADS_BANK0_GPIO0_DRIVE_VALUE_12MA << PADS_BANK0_GPIO0_DRIVE_LSB, - PADS_BANK0_GPIO0_DRIVE_BITS); + PADS_BANK0_GPIO0_DRIVE_VALUE_12MA << PADS_BANK0_GPIO0_DRIVE_LSB, + PADS_BANK0_GPIO0_DRIVE_BITS); self->output = true; self->open_drain = drive_mode == DRIVE_MODE_OPEN_DRAIN; @@ -92,12 +92,12 @@ digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( } digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( - digitalio_digitalinout_obj_t* self) { + digitalio_digitalinout_obj_t *self) { return self->output ? DIRECTION_OUTPUT : DIRECTION_INPUT; } void common_hal_digitalio_digitalinout_set_value( - digitalio_digitalinout_obj_t* self, bool value) { + digitalio_digitalinout_obj_t *self, bool value) { const uint8_t pin = self->pin->number; if (self->open_drain && value) { // If true and open-drain, set the direction -before- setting @@ -115,13 +115,13 @@ void common_hal_digitalio_digitalinout_set_value( } bool common_hal_digitalio_digitalinout_get_value( - digitalio_digitalinout_obj_t* self) { + digitalio_digitalinout_obj_t *self) { return gpio_get(self->pin->number); } digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( - digitalio_digitalinout_obj_t* self, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, + digitalio_drive_mode_t drive_mode) { const uint8_t pin = self->pin->number; bool value = common_hal_digitalio_digitalinout_get_value(self); self->open_drain = drive_mode == DRIVE_MODE_OPEN_DRAIN; @@ -134,7 +134,7 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( } digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( - digitalio_digitalinout_obj_t* self) { + digitalio_digitalinout_obj_t *self) { if (self->open_drain) { return DRIVE_MODE_OPEN_DRAIN; } else { @@ -143,14 +143,14 @@ digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( } void common_hal_digitalio_digitalinout_set_pull( - digitalio_digitalinout_obj_t* self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { const uint8_t pin = self->pin->number; gpio_set_pulls(pin, pull == PULL_UP, pull == PULL_DOWN); gpio_set_dir(pin, GPIO_IN); } digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( - digitalio_digitalinout_obj_t* self) { + digitalio_digitalinout_obj_t *self) { uint32_t pin = self->pin->number; if (self->output) { mp_raise_AttributeError(translate("Cannot get pull while in output mode")); diff --git a/ports/raspberrypi/common-hal/digitalio/DigitalInOut.h b/ports/raspberrypi/common-hal/digitalio/DigitalInOut.h index 8b14bbad8f..d656f607f6 100644 --- a/ports/raspberrypi/common-hal/digitalio/DigitalInOut.h +++ b/ports/raspberrypi/common-hal/digitalio/DigitalInOut.h @@ -32,7 +32,7 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t * pin; + const mcu_pin_obj_t *pin; bool output; bool open_drain; } digitalio_digitalinout_obj_t; diff --git a/ports/raspberrypi/common-hal/displayio/ParallelBus.c b/ports/raspberrypi/common-hal/displayio/ParallelBus.c index 57b2ffc36b..6060c4668d 100644 --- a/ports/raspberrypi/common-hal/displayio/ParallelBus.c +++ b/ports/raspberrypi/common-hal/displayio/ParallelBus.c @@ -33,20 +33,20 @@ #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/microcontroller/__init__.h" -void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* self, - const mcu_pin_obj_t* data0, const mcu_pin_obj_t* command, const mcu_pin_obj_t* chip_select, - const mcu_pin_obj_t* write, const mcu_pin_obj_t* read, const mcu_pin_obj_t* reset) { +void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t *self, + const mcu_pin_obj_t *data0, const mcu_pin_obj_t *command, const mcu_pin_obj_t *chip_select, + const mcu_pin_obj_t *write, const mcu_pin_obj_t *read, const mcu_pin_obj_t *reset) { mp_raise_NotImplementedError(translate("ParallelBus not yet supported")); // TODO: Implement with PIO and DMA. } -void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) { +void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t *self) { } bool common_hal_displayio_parallelbus_reset(mp_obj_t obj) { - return false; + return false; } bool common_hal_displayio_parallelbus_bus_free(mp_obj_t obj) { @@ -59,7 +59,7 @@ bool common_hal_displayio_parallelbus_begin_transaction(mp_obj_t obj) { } void common_hal_displayio_parallelbus_send(mp_obj_t obj, display_byte_type_t byte_type, - display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { + display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { } diff --git a/ports/raspberrypi/common-hal/microcontroller/Pin.c b/ports/raspberrypi/common-hal/microcontroller/Pin.c index ca5cf5a045..271966c2fe 100644 --- a/ports/raspberrypi/common-hal/microcontroller/Pin.c +++ b/ports/raspberrypi/common-hal/microcontroller/Pin.c @@ -74,8 +74,8 @@ void reset_pin_number(uint8_t pin_number) { // disabled and both buffers are as well. gpio_init(pin_number); hw_clear_bits(&padsbank0_hw->io[pin_number], PADS_BANK0_GPIO0_IE_BITS | - PADS_BANK0_GPIO0_PUE_BITS | - PADS_BANK0_GPIO0_PDE_BITS); + PADS_BANK0_GPIO0_PUE_BITS | + PADS_BANK0_GPIO0_PDE_BITS); hw_set_bits(&padsbank0_hw->io[pin_number], PADS_BANK0_GPIO0_OD_BITS); #ifdef MICROPY_HW_NEOPIXEL @@ -104,15 +104,15 @@ void reset_pin_number(uint8_t pin_number) { #endif } -void common_hal_never_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { never_reset_pin_number(pin->number); } -void common_hal_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_reset_pin(const mcu_pin_obj_t *pin) { reset_pin_number(pin->number); } -void claim_pin(const mcu_pin_obj_t* pin) { +void claim_pin(const mcu_pin_obj_t *pin) { #ifdef MICROPY_HW_NEOPIXEL if (pin == MICROPY_HW_NEOPIXEL) { neopixel_in_use = true; @@ -144,7 +144,7 @@ bool pin_number_is_free(uint8_t pin_number) { (pad_state & PADS_BANK0_GPIO0_OD_BITS) != 0; } -bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t* pin) { +bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { #ifdef MICROPY_HW_NEOPIXEL if (pin == MICROPY_HW_NEOPIXEL) { return !neopixel_in_use; @@ -168,11 +168,11 @@ bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t* pin) { return pin_number_is_free(pin->number); } -uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t* pin) { +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin) { return pin->number; } -void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) { +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { return claim_pin(pin); } diff --git a/ports/raspberrypi/common-hal/microcontroller/Pin.h b/ports/raspberrypi/common-hal/microcontroller/Pin.h index 07c3211850..7da3a2b88b 100644 --- a/ports/raspberrypi/common-hal/microcontroller/Pin.h +++ b/ports/raspberrypi/common-hal/microcontroller/Pin.h @@ -47,7 +47,7 @@ void reset_all_pins(void); // need to store a full pointer. void reset_pin_number(uint8_t pin_number); void never_reset_pin_number(uint8_t pin_number); -void claim_pin(const mcu_pin_obj_t* pin); +void claim_pin(const mcu_pin_obj_t *pin); bool pin_number_is_free(uint8_t pin_number); #endif // MICROPY_INCLUDED_RASPBERRYPI_COMMON_HAL_MICROCONTROLLER_PIN_H diff --git a/ports/raspberrypi/common-hal/microcontroller/__init__.c b/ports/raspberrypi/common-hal/microcontroller/__init__.c index bfea8b2d9a..6b5cb9b0d8 100644 --- a/ports/raspberrypi/common-hal/microcontroller/__init__.c +++ b/ports/raspberrypi/common-hal/microcontroller/__init__.c @@ -129,7 +129,7 @@ const nvm_bytearray_obj_t common_hal_mcu_nvm_obj = { .type = &nvm_bytearray_type, }, .len = CIRCUITPY_INTERNAL_NVM_SIZE, - .start_address = (uint8_t*) (CIRCUITPY_INTERNAL_NVM_START_ADDR) + .start_address = (uint8_t *)(CIRCUITPY_INTERNAL_NVM_START_ADDR) }; #endif diff --git a/ports/raspberrypi/common-hal/neopixel_write/__init__.c b/ports/raspberrypi/common-hal/neopixel_write/__init__.c index b57cb2bdea..d1d8728434 100644 --- a/ports/raspberrypi/common-hal/neopixel_write/__init__.c +++ b/ports/raspberrypi/common-hal/neopixel_write/__init__.c @@ -54,7 +54,7 @@ const uint16_t neopixel_program[] = { 0xa142 }; -void common_hal_neopixel_write(const digitalio_digitalinout_obj_t* digitalinout, uint8_t *pixels, uint32_t num_bytes) { +void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, uint8_t *pixels, uint32_t num_bytes) { // Set everything up. rp2pio_statemachine_obj_t state_machine; @@ -83,7 +83,8 @@ void common_hal_neopixel_write(const digitalio_digitalinout_obj_t* digitalinout, // Wait to make sure we don't append onto the last transmission. This should only be a tick or // two. - while (port_get_raw_ticks(NULL) < next_start_raw_ticks) {} + while (port_get_raw_ticks(NULL) < next_start_raw_ticks) { + } common_hal_rp2pio_statemachine_write(&state_machine, pixels, num_bytes, 1 /* stride in bytes */); @@ -92,7 +93,7 @@ void common_hal_neopixel_write(const digitalio_digitalinout_obj_t* digitalinout, // Reset the pin and release it from the PIO gpio_init(digitalinout->pin->number); - common_hal_digitalio_digitalinout_switch_to_output((digitalio_digitalinout_obj_t*)digitalinout, false, DRIVE_MODE_PUSH_PULL); + common_hal_digitalio_digitalinout_switch_to_output((digitalio_digitalinout_obj_t *)digitalinout, false, DRIVE_MODE_PUSH_PULL); // Update the next start. next_start_raw_ticks = port_get_raw_ticks(NULL) + 1; diff --git a/ports/raspberrypi/common-hal/nvm/ByteArray.c b/ports/raspberrypi/common-hal/nvm/ByteArray.c index fdc2c60805..94d98d686f 100644 --- a/ports/raspberrypi/common-hal/nvm/ByteArray.c +++ b/ports/raspberrypi/common-hal/nvm/ByteArray.c @@ -32,44 +32,44 @@ #include "src/rp2_common/hardware_flash/include/hardware/flash.h" extern uint32_t __flash_binary_start; -static const uint32_t flash_binary_start = (uint32_t) &__flash_binary_start; +static const uint32_t flash_binary_start = (uint32_t)&__flash_binary_start; #define RMV_OFFSET(addr) addr - flash_binary_start -uint32_t common_hal_nvm_bytearray_get_length(nvm_bytearray_obj_t* self) { +uint32_t common_hal_nvm_bytearray_get_length(nvm_bytearray_obj_t *self) { return self->len; } -static void write_page(uint32_t page_addr, uint32_t offset, uint32_t len, uint8_t* bytes) { +static void write_page(uint32_t page_addr, uint32_t offset, uint32_t len, uint8_t *bytes) { // Write a whole page to flash, buffering it first and then erasing and rewriting it // since we can only write a whole page at a time. if (offset == 0 && len == FLASH_PAGE_SIZE) { flash_range_program(RMV_OFFSET(page_addr), bytes, FLASH_PAGE_SIZE); } else { uint8_t buffer[FLASH_PAGE_SIZE]; - memcpy(buffer, (uint8_t*) page_addr, FLASH_PAGE_SIZE); + memcpy(buffer, (uint8_t *)page_addr, FLASH_PAGE_SIZE); memcpy(buffer + offset, bytes, len); flash_range_program(RMV_OFFSET(page_addr), buffer, FLASH_PAGE_SIZE); } } -static void erase_and_write_sector(uint32_t address, uint32_t len, uint8_t* bytes) { +static void erase_and_write_sector(uint32_t address, uint32_t len, uint8_t *bytes) { // Write a whole sector to flash, buffering it first and then erasing and rewriting it // since we can only erase a whole sector at a time. uint8_t buffer[FLASH_SECTOR_SIZE]; - memcpy(buffer, (uint8_t*) CIRCUITPY_INTERNAL_NVM_START_ADDR, FLASH_SECTOR_SIZE); + memcpy(buffer, (uint8_t *)CIRCUITPY_INTERNAL_NVM_START_ADDR, FLASH_SECTOR_SIZE); memcpy(buffer + address, bytes, len); flash_range_erase(RMV_OFFSET(CIRCUITPY_INTERNAL_NVM_START_ADDR), FLASH_SECTOR_SIZE); flash_range_program(RMV_OFFSET(CIRCUITPY_INTERNAL_NVM_START_ADDR), buffer, FLASH_SECTOR_SIZE); } -void common_hal_nvm_bytearray_get_bytes(nvm_bytearray_obj_t* self, - uint32_t start_index, uint32_t len, uint8_t* values) { +void common_hal_nvm_bytearray_get_bytes(nvm_bytearray_obj_t *self, + uint32_t start_index, uint32_t len, uint8_t *values) { memcpy(values, self->start_address + start_index, len); } -bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t* self, - uint32_t start_index, uint8_t* values, uint32_t len) { +bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, + uint32_t start_index, uint8_t *values, uint32_t len) { uint8_t values_in[len]; common_hal_nvm_bytearray_get_bytes(self, start_index, len, values_in); @@ -82,7 +82,7 @@ bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t* self, } if (all_ones) { - uint32_t address = (uint32_t) self->start_address + start_index; + uint32_t address = (uint32_t)self->start_address + start_index; uint32_t offset = address % FLASH_PAGE_SIZE; uint32_t page_addr = address - offset; diff --git a/ports/raspberrypi/common-hal/nvm/ByteArray.h b/ports/raspberrypi/common-hal/nvm/ByteArray.h index a2a904fea8..4667e6b231 100644 --- a/ports/raspberrypi/common-hal/nvm/ByteArray.h +++ b/ports/raspberrypi/common-hal/nvm/ByteArray.h @@ -31,7 +31,7 @@ typedef struct { mp_obj_base_t base; - uint8_t * start_address; + uint8_t *start_address; uint32_t len; } nvm_bytearray_obj_t; diff --git a/ports/raspberrypi/common-hal/os/__init__.c b/ports/raspberrypi/common-hal/os/__init__.c index 0df7653d39..3352cef122 100644 --- a/ports/raspberrypi/common-hal/os/__init__.c +++ b/ports/raspberrypi/common-hal/os/__init__.c @@ -56,7 +56,7 @@ STATIC MP_DEFINE_ATTRTUPLE( (mp_obj_t)&os_uname_info_release_obj, (mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj -); + ); mp_obj_t common_hal_os_uname(void) { return (mp_obj_t)&os_uname_info_obj; @@ -82,10 +82,10 @@ static BYTE random_state[SHA256_BLOCK_SIZE]; static void seed_random_bits(BYTE out[SHA256_BLOCK_SIZE]) { CRYAL_SHA256_CTX context; sha256_init(&context); - for (int i=0; i<2*RANDOM_SAFETY_MARGIN; i++) { - for(int j=0; jrandombit & 1; - for(int k=0; k<8; k++) { + for (int k = 0; k < 8; k++) { out[j] = (out[j] << 1) ^ (rosc_hw->randombit & 1); } } @@ -104,12 +104,12 @@ static void get_random_bits(BYTE out[SHA256_BLOCK_SIZE]) { sha256_final(&context, out); } -bool common_hal_os_urandom(uint8_t* buffer, uint32_t length) { +bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { #define ROSC_POWER_SAVE (1) // assume ROSC is not necessarily active all the time -#if ROSC_POWER_SAVE + #if ROSC_POWER_SAVE uint32_t old_rosc_ctrl = rosc_hw->ctrl; rosc_hw->ctrl = (old_rosc_ctrl & ~ROSC_CTRL_ENABLE_BITS) | (ROSC_CTRL_ENABLE_VALUE_ENABLE << 12); -#endif + #endif while (length) { size_t n = MIN(length, SHA256_BLOCK_SIZE); BYTE sha_buf[SHA256_BLOCK_SIZE]; @@ -118,8 +118,8 @@ bool common_hal_os_urandom(uint8_t* buffer, uint32_t length) { buffer += n; length -= n; } -#if ROSC_POWER_SAVE + #if ROSC_POWER_SAVE rosc_hw->ctrl = old_rosc_ctrl; -#endif + #endif return true; } diff --git a/ports/raspberrypi/common-hal/pulseio/PulseIn.c b/ports/raspberrypi/common-hal/pulseio/PulseIn.c index e05b35536c..278c0cd662 100644 --- a/ports/raspberrypi/common-hal/pulseio/PulseIn.c +++ b/ports/raspberrypi/common-hal/pulseio/PulseIn.c @@ -36,7 +36,7 @@ #include "bindings/rp2pio/StateMachine.h" #include "common-hal/pulseio/PulseIn.h" -pulseio_pulsein_obj_t* save_self; +pulseio_pulsein_obj_t *save_self; #define NO_PIN 0xff volatile bool last_level; @@ -48,10 +48,10 @@ uint16_t pulsein_program[] = { 0x4001, // 1: in pins, 1 }; -void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, - const mcu_pin_obj_t* pin, uint16_t maxlen, bool idle_state) { +void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, + const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state) { - self->buffer = (uint16_t *) m_malloc(maxlen * sizeof(uint16_t), false); + self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t), false); if (self->buffer == NULL) { mp_raise_msg_varg(&mp_type_MemoryError, translate("Failed to allocate RX buffer of %d bytes"), maxlen * sizeof(uint16_t)); } @@ -76,10 +76,10 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, NULL, 0, 1, 0, 1 << self->pin, false, true, - false, 8, false, // TX, unused - false, - true, 32, true, // RX auto-push every 32 bits - false); // claim pins + false, 8, false, // TX, unused + false, + true, 32, true, // RX auto-push every 32 bits + false); // claim pins pio_sm_set_enabled(state_machine.pio,state_machine.state_machine, false); self->state_machine.pio = state_machine.pio; self->state_machine.state_machine = state_machine.state_machine; @@ -96,79 +96,79 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, // exec a set pindirs to 0 for input pio_sm_exec(state_machine.pio,state_machine.state_machine,0xe080); - //exec the appropriate wait for pin - if (self->idle_state == true ) { - pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x2020); + // exec the appropriate wait for pin + if (self->idle_state == true) { + pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x2020); } else { - pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x20a0); + pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x20a0); } pio_sm_set_enabled(state_machine.pio, state_machine.state_machine, true); } -bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t* self) { +bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self) { return self->pin == NO_PIN; } -void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { if (common_hal_pulseio_pulsein_deinited(self)) { return; } pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, false); - pio_sm_unclaim (self->state_machine.pio, self->state_machine.state_machine); + pio_sm_unclaim(self->state_machine.pio, self->state_machine.state_machine); m_free(self->buffer); self->pin = NO_PIN; } -void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self) { pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, false); } void common_hal_pulseio_pulsein_interrupt() { - pulseio_pulsein_obj_t* self = save_self; + pulseio_pulsein_obj_t *self = save_self; uint32_t rxfifo = 0; rxfifo = pio_sm_get_blocking(self->state_machine.pio, self->state_machine.state_machine); // translate from fifo to buffer for (uint i = 0; i < 32; i++) { bool level = (rxfifo & (1 << i)) >> i; - if (level == last_level ) { - level_count ++; + if (level == last_level) { + level_count++; } else { - result = level_count; - last_level = level; - level_count = 1; - // ignore pulses that are too long and too short - if (result < 4000 && result > 10) { - self->buffer[buf_index] = result; - buf_index++; - self->len++; - } - } - } + result = level_count; + last_level = level; + level_count = 1; + // ignore pulses that are too long and too short + if (result < 4000 && result > 10) { + self->buffer[buf_index] = result; + buf_index++; + self->len++; + } + } + } // check for a pulse thats too long (4000 us) or maxlen reached, and reset - if (( level_count > 4000 ) || (buf_index >= self->maxlen)) { - pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, false); - pio_sm_init(self->state_machine.pio, self->state_machine.state_machine, self->state_machine.offset, &self->state_machine.sm_config); - pio_sm_restart(self->state_machine.pio,self->state_machine.state_machine); - pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, true); + if ((level_count > 4000) || (buf_index >= self->maxlen)) { + pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, false); + pio_sm_init(self->state_machine.pio, self->state_machine.state_machine, self->state_machine.offset, &self->state_machine.sm_config); + pio_sm_restart(self->state_machine.pio,self->state_machine.state_machine); + pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, true); } } -void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, - uint16_t trigger_duration) { +void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t *self, + uint16_t trigger_duration) { // exec a wait for the selected pin to change state - if (self->idle_state == true ) { - pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x2020); + if (self->idle_state == true) { + pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x2020); } else { - pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x20a0); + pio_sm_exec(self->state_machine.pio,self->state_machine.state_machine,0x20a0); } // Send the trigger pulse. if (trigger_duration > 0) { - gpio_set_function(self->pin ,GPIO_FUNC_SIO); + gpio_set_function(self->pin,GPIO_FUNC_SIO); gpio_set_dir(self->pin,true); gpio_put(self->pin, !self->idle_state); common_hal_mcu_delay_us((uint32_t)trigger_duration); - gpio_set_function(self->pin ,GPIO_FUNC_PIO0); + gpio_set_function(self->pin,GPIO_FUNC_PIO0); common_hal_mcu_delay_us(225); } @@ -177,12 +177,12 @@ void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, pio_sm_set_enabled(self->state_machine.pio, self->state_machine.state_machine, true); } -void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t *self) { self->start = 0; self->len = 0; } -uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t *self) { if (self->len == 0) { mp_raise_IndexError_varg(translate("pop from empty %q"), MP_QSTR_PulseIn); } @@ -190,28 +190,28 @@ uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { self->start = (self->start + 1) % self->maxlen; self->len--; // if we are empty reset buffer pointer and counters - if (self->len == 0 ) { - self->start = 0; - buf_index = 0; - level_count = 0; + if (self->len == 0) { + self->start = 0; + buf_index = 0; + level_count = 0; } return value; } -uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t *self) { return self->maxlen; } -uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t *self) { return self->len; } -bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t* self) { +bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t *self) { return true; } -uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, - int16_t index) { +uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t *self, + int16_t index) { if (index < 0) { index += self->len; } diff --git a/ports/raspberrypi/common-hal/pulseio/PulseIn.h b/ports/raspberrypi/common-hal/pulseio/PulseIn.h index c83a86fca0..b68a2238d5 100644 --- a/ports/raspberrypi/common-hal/pulseio/PulseIn.h +++ b/ports/raspberrypi/common-hal/pulseio/PulseIn.h @@ -36,7 +36,7 @@ typedef struct { mp_obj_base_t base; uint8_t pin; - uint16_t* buffer; + uint16_t *buffer; uint16_t maxlen; bool idle_state; volatile uint16_t start; diff --git a/ports/raspberrypi/common-hal/pulseio/PulseOut.c b/ports/raspberrypi/common-hal/pulseio/PulseOut.c index e284cd46a2..c3536af04b 100644 --- a/ports/raspberrypi/common-hal/pulseio/PulseOut.c +++ b/ports/raspberrypi/common-hal/pulseio/PulseOut.c @@ -58,12 +58,12 @@ void pulseout_reset() { refcount = 0; } -void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, - const pwmio_pwmout_obj_t* carrier, - const mcu_pin_obj_t* pin, - uint32_t frequency, - uint16_t duty_cycle) { - mp_raise_NotImplementedError(translate("Unsupported operation")); +void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, + const pwmio_pwmout_obj_t *carrier, + const mcu_pin_obj_t *pin, + uint32_t frequency, + uint16_t duty_cycle) { + mp_raise_NotImplementedError(translate("Unsupported operation")); refcount++; @@ -71,11 +71,11 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, } -bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t* self) { +bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t *self) { return self->pin == NO_PIN; } -void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { +void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { if (common_hal_pulseio_pulseout_deinited(self)) { return; } @@ -85,7 +85,7 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { self->pin = NO_PIN; } -void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pulses, uint16_t length) { +void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pulses, uint16_t length) { pulse_buffer = pulses; pulse_index = 0; pulse_length = length; diff --git a/ports/raspberrypi/common-hal/pwmio/PWMOut.c b/ports/raspberrypi/common-hal/pwmio/PWMOut.c index fd85fbf55b..9695a8fdf7 100644 --- a/ports/raspberrypi/common-hal/pwmio/PWMOut.c +++ b/ports/raspberrypi/common-hal/pwmio/PWMOut.c @@ -154,11 +154,11 @@ pwmout_result_t pwmout_allocate(uint8_t slice, uint8_t channel, bool variable_fr return PWMOUT_OK; } -pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, - const mcu_pin_obj_t* pin, - uint16_t duty, - uint32_t frequency, - bool variable_frequency) { +pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, + const mcu_pin_obj_t *pin, + uint16_t duty, + uint32_t frequency, + bool variable_frequency) { self->pin = pin; self->variable_frequency = variable_frequency; self->duty_cycle = duty; @@ -195,7 +195,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, return PWMOUT_OK; } -bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { return self->pin == NULL; } @@ -211,7 +211,7 @@ void pwmout_free(uint8_t slice, uint8_t channel) { } } -void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { +void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { if (common_hal_pwmio_pwmout_deinited(self)) { return; } @@ -220,33 +220,33 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { self->pin = NULL; } -extern void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t* self, uint16_t duty) { +extern void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty) { self->duty_cycle = duty; // Do arithmetic in 32 bits to prevent overflow. uint16_t compare_count; if (duty == 65535) { // Ensure that 100% duty cycle is 100% full on and not rounded down, // but do MIN() to keep value in range, just in case. - compare_count = MIN(UINT16_MAX, (uint32_t) self->top + 1); + compare_count = MIN(UINT16_MAX, (uint32_t)self->top + 1); } else { - compare_count= ((uint32_t) duty * self->top + MAX_TOP / 2) / MAX_TOP; + compare_count = ((uint32_t)duty * self->top + MAX_TOP / 2) / MAX_TOP; } // compare_count is the CC register value, which should be TOP+1 for 100% duty cycle. pwm_set_chan_level(self->slice, self->channel, compare_count); } -uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t* self) { +uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t *self) { return self->duty_cycle; } -void pwmio_pwmout_set_top(pwmio_pwmout_obj_t* self, uint16_t top) { +void pwmio_pwmout_set_top(pwmio_pwmout_obj_t *self, uint16_t top) { self->actual_frequency = common_hal_mcu_processor_get_frequency() / top; self->top = top; pwm_set_clkdiv_int_frac(self->slice, 1, 0); pwm_set_wrap(self->slice, self->top); } -void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t frequency) { +void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, uint32_t frequency) { if (frequency == 0 || frequency > (common_hal_mcu_processor_get_frequency() / 2)) { mp_raise_ValueError(translate("Invalid PWM frequency")); } @@ -258,7 +258,7 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t fr // Compute the divisor. It's an 8 bit integer and 4 bit fraction. Therefore, // we compute everything * 16 for the fractional part. // This is 1 << 12 because 4 bits are the * 16. - uint64_t frequency16 = ((uint64_t) clock_get_hz(clk_sys)) / (1 << 12); + uint64_t frequency16 = ((uint64_t)clock_get_hz(clk_sys)) / (1 << 12); uint64_t div16 = frequency16 / frequency; // Round the divisor to try and get closest to the target frequency. We could // also always round up and use TOP to get us closer. We may not need that though. @@ -283,10 +283,10 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t fr common_hal_pwmio_pwmout_set_duty_cycle(self, self->duty_cycle); } -uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t* self) { +uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t *self) { return self->actual_frequency; } -bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *self) { return self->variable_frequency; } diff --git a/ports/raspberrypi/common-hal/pwmio/PWMOut.h b/ports/raspberrypi/common-hal/pwmio/PWMOut.h index 41da810106..c7707762e4 100644 --- a/ports/raspberrypi/common-hal/pwmio/PWMOut.h +++ b/ports/raspberrypi/common-hal/pwmio/PWMOut.h @@ -44,7 +44,7 @@ typedef struct { void pwmout_reset(void); // Private API for AudioPWMOut. -void pwmio_pwmout_set_top(pwmio_pwmout_obj_t* self, uint16_t top); +void pwmio_pwmout_set_top(pwmio_pwmout_obj_t *self, uint16_t top); // Private APIs for RGBMatrix enum pwmout_result_t pwmout_allocate(uint8_t slice, uint8_t channel, bool variable_frequency, uint32_t frequency); void pwmout_free(uint8_t slice, uint8_t channel); diff --git a/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c index 657c7f0a6c..f150422e3c 100644 --- a/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c @@ -38,29 +38,29 @@ void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self) { // Choose a PWM channel based on the first RGB pin uint8_t slice = pwm_gpio_to_slice_num(self->rgb_pins[0]); uint8_t channel = pwm_gpio_to_channel(self->rgb_pins[0]); - int result = pwmout_allocate(slice, channel, true, 125000000/3); + int result = pwmout_allocate(slice, channel, true, 125000000 / 3); if (result == PWMOUT_OK) { // return value must be nonzero (but slice and channel can both be // zero), so set bit 16... pwmout_never_reset(slice, channel); - return (void*)(intptr_t)(slice | (channel << 8) | 0x10000); + return (void *)(intptr_t)(slice | (channel << 8) | 0x10000); } return NULL; } -void common_hal_rgbmatrix_timer_enable(void* ptr) { +void common_hal_rgbmatrix_timer_enable(void *ptr) { int8_t slice = ((intptr_t)ptr) & 0xff; pwm_set_enabled(slice, false); pwm_clear_irq(slice); pwm_set_enabled(slice, true); } -void common_hal_rgbmatrix_timer_disable(void* ptr) { +void common_hal_rgbmatrix_timer_disable(void *ptr) { int8_t slice = ((intptr_t)ptr) & 0xff; pwm_set_enabled(slice, false); } -void common_hal_rgbmatrix_timer_free(void* ptr) { +void common_hal_rgbmatrix_timer_free(void *ptr) { intptr_t value = (intptr_t)ptr; uint8_t slice = value & 0xff; uint8_t channel = value >> 8; diff --git a/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.h b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.h index 2378cf1735..d14cd9b083 100644 --- a/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.h +++ b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.h @@ -30,8 +30,8 @@ #include "shared-module/rgbmatrix/RGBMatrix.h" void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self); -void common_hal_rgbmatrix_timer_enable(void*); -void common_hal_rgbmatrix_timer_disable(void*); -void common_hal_rgbmatrix_timer_free(void*); +void common_hal_rgbmatrix_timer_enable(void *); +void common_hal_rgbmatrix_timer_disable(void *); +void common_hal_rgbmatrix_timer_free(void *); #endif diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c index b2225991d6..30b3ac619e 100644 --- a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c @@ -57,8 +57,8 @@ STATIC const uint16_t encoder_init[] = { STATIC void incrementalencoder_interrupt_handler(void *self_in); -void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t* self, - const mcu_pin_obj_t* pin_a, const mcu_pin_obj_t* pin_b) { +void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self, + const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b) { mp_obj_t pins[] = {MP_OBJ_FROM_PTR(pin_a), MP_OBJ_FROM_PTR(pin_b)}; if (!common_hal_rp2pio_pins_are_sequential(2, pins)) { mp_raise_RuntimeError(translate("Pins must be sequential")); @@ -93,28 +93,28 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode common_hal_rp2pio_statemachine_set_interrupt_handler(&self->state_machine, incrementalencoder_interrupt_handler, self, PIO_IRQ0_INTF_SM0_RXNEMPTY_BITS); } -bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t* self) { +bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t *self) { return common_hal_rp2pio_statemachine_deinited(&self->state_machine); } -void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t* self) { +void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t *self) { if (common_hal_rotaryio_incrementalencoder_deinited(self)) { return; } common_hal_rp2pio_statemachine_deinit(&self->state_machine); } -mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t* self) { +mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self) { return self->position; } -void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t* self, - mp_int_t new_position) { +void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, + mp_int_t new_position) { self->position = new_position; } STATIC void incrementalencoder_interrupt_handler(void *self_in) { - rotaryio_incrementalencoder_obj_t* self = self_in; + rotaryio_incrementalencoder_obj_t *self = self_in; // This table also works for detent both at 11 and 00 // For 11 at detent: // Turning cw: 11->01->00->10->11 diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h index ff5c874c83..83fe97d316 100644 --- a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.h @@ -34,7 +34,7 @@ typedef struct { mp_obj_base_t base; rp2pio_statemachine_obj_t state_machine; - uint8_t last_state:4; // - int8_t quarter_count:4; // count intermediate transitions between detents + uint8_t last_state : 4; // + int8_t quarter_count : 4; // count intermediate transitions between detents mp_int_t position; } rotaryio_incrementalencoder_obj_t; diff --git a/ports/raspberrypi/common-hal/rp2pio/StateMachine.c b/ports/raspberrypi/common-hal/rp2pio/StateMachine.c index 56a7ab668d..4e2886eedf 100644 --- a/ports/raspberrypi/common-hal/rp2pio/StateMachine.c +++ b/ports/raspberrypi/common-hal/rp2pio/StateMachine.c @@ -53,16 +53,16 @@ STATIC uint32_t _current_pins[NUM_PIOS]; STATIC uint32_t _current_sm_pins[NUM_PIOS][NUM_PIO_STATE_MACHINES]; STATIC PIO pio_instances[2] = {pio0, pio1}; -typedef void (*interrupt_handler_type)(void*); +typedef void (*interrupt_handler_type)(void *); STATIC interrupt_handler_type _interrupt_handler[NUM_PIOS][NUM_PIO_STATE_MACHINES]; STATIC void *_interrupt_arg[NUM_PIOS][NUM_PIO_STATE_MACHINES]; STATIC void rp2pio_statemachine_interrupt_handler(void); static void rp2pio_statemachine_set_pull(uint32_t pull_pin_up, uint32_t pull_pin_down, uint32_t pins_we_use) { - for (int i=0; i 0) { - irq_set_enabled (irq, false); - irq_remove_handler(irq,int_handler); - } - } + for (uint8_t irq = PIO0_IRQ_0; irq <= PIO1_IRQ_1; irq++) { + irq_handler_t int_handler = irq_get_exclusive_handler(irq); + if (int_handler > 0) { + irq_set_enabled(irq, false); + irq_remove_handler(irq,int_handler); + } + } } -STATIC uint32_t _check_pins_free(const mcu_pin_obj_t * first_pin, uint8_t pin_count, bool exclusive_pin_use) { +STATIC uint32_t _check_pins_free(const mcu_pin_obj_t *first_pin, uint8_t pin_count, bool exclusive_pin_use) { uint32_t pins_we_use = 0; if (first_pin != NULL) { for (size_t i = 0; i < pin_count; i++) { @@ -137,7 +137,7 @@ STATIC uint32_t _check_pins_free(const mcu_pin_obj_t * first_pin, uint8_t pin_co if (pin_number >= TOTAL_GPIO_COUNT) { mp_raise_ValueError(translate("Pin count too large")); } - const mcu_pin_obj_t * pin = mcu_pin_global_dict_table[pin_number].value; + const mcu_pin_obj_t *pin = mcu_pin_global_dict_table[pin_number].value; if (exclusive_pin_use || _pin_reference_count[pin_number] == 0) { assert_pin_free(pin); } @@ -149,14 +149,14 @@ STATIC uint32_t _check_pins_free(const mcu_pin_obj_t * first_pin, uint8_t pin_co bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, - const uint16_t* program, size_t program_len, + const uint16_t *program, size_t program_len, size_t frequency, - const uint16_t* init, size_t init_len, - const mcu_pin_obj_t * first_out_pin, uint8_t out_pin_count, - const mcu_pin_obj_t * first_in_pin, uint8_t in_pin_count, + const uint16_t *init, size_t init_len, + const mcu_pin_obj_t *first_out_pin, uint8_t out_pin_count, + const mcu_pin_obj_t *first_in_pin, uint8_t in_pin_count, uint32_t pull_pin_up, uint32_t pull_pin_down, - const mcu_pin_obj_t * first_set_pin, uint8_t set_pin_count, - const mcu_pin_obj_t * first_sideset_pin, uint8_t sideset_pin_count, + const mcu_pin_obj_t *first_set_pin, uint8_t set_pin_count, + const mcu_pin_obj_t *first_sideset_pin, uint8_t sideset_pin_count, uint32_t initial_pin_state, uint32_t initial_pin_direction, uint32_t pins_we_use, bool tx_fifo, bool rx_fifo, bool auto_pull, uint8_t pull_threshold, bool out_shift_right, @@ -164,13 +164,13 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, bool auto_push, uint8_t push_threshold, bool in_shift_right, bool claim_pins) { // Create a program id that isn't the pointer so we can store it without storing the original object. - uint32_t program_id = ~((uint32_t) program); + uint32_t program_id = ~((uint32_t)program); // Next, find a PIO and state machine to use. size_t pio_index = NUM_PIOS; uint8_t program_offset = 32; pio_program_t program_struct = { - .instructions = (uint16_t*) program, + .instructions = (uint16_t *)program, .length = program_len, .origin = 0 }; @@ -242,7 +242,7 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, continue; } _pin_reference_count[pin_number]++; - const mcu_pin_obj_t * pin = mcu_pin_global_dict_table[pin_number].value; + const mcu_pin_obj_t *pin = mcu_pin_global_dict_table[pin_number].value; // Also claim the pin at the top level when we're the first to grab it. if (_pin_reference_count[pin_number] == 1) { if (claim_pins) { @@ -257,7 +257,7 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, if (frequency == 0) { frequency = clock_get_hz(clk_sys); } - uint64_t frequency256 = ((uint64_t) clock_get_hz(clk_sys)) * 256; + uint64_t frequency256 = ((uint64_t)clock_get_hz(clk_sys)) * 256; uint64_t div256 = frequency256 / frequency; if (frequency256 % div256 > 0) { div256 += 1; @@ -314,21 +314,21 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, return true; } -static uint32_t mask_and_rotate(const mcu_pin_obj_t* first_pin, uint32_t bit_count, uint32_t value) { +static uint32_t mask_and_rotate(const mcu_pin_obj_t *first_pin, uint32_t bit_count, uint32_t value) { value = value & ((1 << bit_count) - 1); uint32_t shift = first_pin->number; return value << shift | value >> (32 - shift); } void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, - const uint16_t* program, size_t program_len, + const uint16_t *program, size_t program_len, size_t frequency, - const uint16_t* init, size_t init_len, - const mcu_pin_obj_t * first_out_pin, uint8_t out_pin_count, uint32_t initial_out_pin_state, uint32_t initial_out_pin_direction, - const mcu_pin_obj_t * first_in_pin, uint8_t in_pin_count, + const uint16_t *init, size_t init_len, + const mcu_pin_obj_t *first_out_pin, uint8_t out_pin_count, uint32_t initial_out_pin_state, uint32_t initial_out_pin_direction, + const mcu_pin_obj_t *first_in_pin, uint8_t in_pin_count, uint32_t pull_pin_up, uint32_t pull_pin_down, - const mcu_pin_obj_t * first_set_pin, uint8_t set_pin_count, uint32_t initial_set_pin_state, uint32_t initial_set_pin_direction, - const mcu_pin_obj_t * first_sideset_pin, uint8_t sideset_pin_count, uint32_t initial_sideset_pin_state, uint32_t initial_sideset_pin_direction, + const mcu_pin_obj_t *first_set_pin, uint8_t set_pin_count, uint32_t initial_set_pin_state, uint32_t initial_set_pin_direction, + const mcu_pin_obj_t *first_sideset_pin, uint8_t sideset_pin_count, uint32_t initial_sideset_pin_state, uint32_t initial_sideset_pin_direction, bool exclusive_pin_use, bool auto_pull, uint8_t pull_threshold, bool out_shift_right, bool wait_for_txstall, @@ -453,7 +453,7 @@ void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, initial_set_pin_state = mask_and_rotate(first_set_pin, set_pin_count, initial_set_pin_state); initial_set_pin_direction = mask_and_rotate(first_set_pin, set_pin_count, initial_set_pin_direction); uint32_t set_out_overlap = mask_and_rotate(first_out_pin, out_pin_count, 0xffffffff) & - mask_and_rotate(first_set_pin, set_pin_count, 0xffffffff); + mask_and_rotate(first_set_pin, set_pin_count, 0xffffffff); // Check that OUT and SET settings agree because we don't have a way of picking one over the other. if ((initial_pin_state & set_out_overlap) != (initial_set_pin_state & set_out_overlap)) { mp_raise_ValueError(translate("Initial set pin state conflicts with initial out pin state")); @@ -517,15 +517,15 @@ void common_hal_rp2pio_statemachine_run(rp2pio_statemachine_obj_t *self, const u } } -uint32_t common_hal_rp2pio_statemachine_get_frequency(rp2pio_statemachine_obj_t* self) { +uint32_t common_hal_rp2pio_statemachine_get_frequency(rp2pio_statemachine_obj_t *self) { return self->actual_frequency; } -void common_hal_rp2pio_statemachine_set_frequency(rp2pio_statemachine_obj_t* self, uint32_t frequency) { +void common_hal_rp2pio_statemachine_set_frequency(rp2pio_statemachine_obj_t *self, uint32_t frequency) { if (frequency == 0) { frequency = clock_get_hz(clk_sys); } - uint64_t frequency256 = ((uint64_t) clock_get_hz(clk_sys)) * 256; + uint64_t frequency256 = ((uint64_t)clock_get_hz(clk_sys)) * 256; uint64_t div256 = frequency256 / frequency; if (frequency256 % div256 > 0) { div256 += 1; @@ -602,16 +602,16 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, chan_rx = dma_claim_unused_channel(false); } } - volatile uint8_t* tx_destination = NULL; - const volatile uint8_t* rx_source = NULL; + volatile uint8_t *tx_destination = NULL; + const volatile uint8_t *rx_source = NULL; if (tx) { - tx_destination = (volatile uint8_t*) &self->pio->txf[self->state_machine]; + tx_destination = (volatile uint8_t *)&self->pio->txf[self->state_machine]; if (!self->out_shift_right) { tx_destination += 4 - out_stride_in_bytes; } } if (rx) { - rx_source = (const volatile uint8_t*) &self->pio->rxf[self->state_machine]; + rx_source = (const volatile uint8_t *)&self->pio->rxf[self->state_machine]; if (self->in_shift_right) { rx_source += 4 - in_stride_in_bytes; } @@ -686,20 +686,20 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, if (out_stride_in_bytes == 1) { *tx_destination = *data_out; } else if (out_stride_in_bytes == 2) { - *((uint16_t*) tx_destination) = *((uint16_t*) data_out); + *((uint16_t *)tx_destination) = *((uint16_t *)data_out); } else if (out_stride_in_bytes == 4) { - *((uint32_t*) tx_destination) = *((uint32_t*) data_out); + *((uint32_t *)tx_destination) = *((uint32_t *)data_out); } data_out += out_stride_in_bytes; --tx_remaining; } while (rx_remaining && !pio_sm_is_rx_fifo_empty(self->pio, self->state_machine)) { if (in_stride_in_bytes == 1) { - *data_in = (uint8_t) *rx_source; + *data_in = (uint8_t)*rx_source; } else if (in_stride_in_bytes == 2) { - *((uint16_t*) data_in) = *((uint16_t*) rx_source); + *((uint16_t *)data_in) = *((uint16_t *)rx_source); } else if (in_stride_in_bytes == 4) { - *((uint32_t*) data_in) = *((uint32_t*) rx_source); + *((uint32_t *)data_in) = *((uint32_t *)rx_source); } data_in += in_stride_in_bytes; --rx_remaining; @@ -744,15 +744,15 @@ bool common_hal_rp2pio_statemachine_readinto(rp2pio_statemachine_obj_t *self, ui } bool common_hal_rp2pio_statemachine_write_readinto(rp2pio_statemachine_obj_t *self, - const uint8_t *data_out, size_t out_len, uint8_t out_stride_in_bytes, - uint8_t *data_in, size_t in_len, uint8_t in_stride_in_bytes) { + const uint8_t *data_out, size_t out_len, uint8_t out_stride_in_bytes, + uint8_t *data_in, size_t in_len, uint8_t in_stride_in_bytes) { if (!self->in || !self->out) { mp_raise_RuntimeError(translate("No in or out in program")); } return _transfer(self, data_out, out_len, out_stride_in_bytes, data_in, in_len, in_stride_in_bytes); } -bool common_hal_rp2pio_statemachine_get_rxstall(rp2pio_statemachine_obj_t* self) { +bool common_hal_rp2pio_statemachine_get_rxstall(rp2pio_statemachine_obj_t *self) { uint32_t stall_mask = 1 << (PIO_FDEBUG_RXSTALL_LSB + self->state_machine); return (self->pio->fdebug & stall_mask) != 0; } @@ -761,7 +761,7 @@ void common_hal_rp2pio_statemachine_clear_rxfifo(rp2pio_statemachine_obj_t *self uint8_t level = pio_sm_get_rx_fifo_level(self->pio, self->state_machine); uint32_t stall_mask = 1 << (PIO_FDEBUG_RXSTALL_LSB + self->state_machine); for (size_t i = 0; i < level; i++) { - (void) self->pio->rxf[self->state_machine]; + (void)self->pio->rxf[self->state_machine]; } self->pio->fdebug = stall_mask; } @@ -771,7 +771,7 @@ size_t common_hal_rp2pio_statemachine_get_in_waiting(rp2pio_statemachine_obj_t * return level; } -void common_hal_rp2pio_statemachine_set_interrupt_handler(rp2pio_statemachine_obj_t *self, void(*handler)(void*), void *arg, int mask) { +void common_hal_rp2pio_statemachine_set_interrupt_handler(rp2pio_statemachine_obj_t *self, void (*handler)(void *), void *arg, int mask) { uint8_t pio_index = pio_get_index(self->pio); uint8_t sm = self->state_machine; diff --git a/ports/raspberrypi/common-hal/rp2pio/StateMachine.h b/ports/raspberrypi/common-hal/rp2pio/StateMachine.h index 15bc2a346c..38410a3629 100644 --- a/ports/raspberrypi/common-hal/rp2pio/StateMachine.h +++ b/ports/raspberrypi/common-hal/rp2pio/StateMachine.h @@ -37,7 +37,7 @@ typedef struct { uint32_t pins; // Bitmask of what pins this state machine uses. int state_machine; PIO pio; - const uint16_t* init; + const uint16_t *init; size_t init_len; uint32_t initial_pin_state; uint32_t initial_pin_direction; @@ -59,14 +59,14 @@ void reset_rp2pio_statemachine(void); // Minimal internal version that only fails on pin error (not in use) or full PIO. bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, - const uint16_t* program, size_t program_len, + const uint16_t *program, size_t program_len, size_t frequency, - const uint16_t* init, size_t init_len, - const mcu_pin_obj_t * first_out_pin, uint8_t out_pin_count, - const mcu_pin_obj_t * first_in_pin, uint8_t in_pin_count, + const uint16_t *init, size_t init_len, + const mcu_pin_obj_t *first_out_pin, uint8_t out_pin_count, + const mcu_pin_obj_t *first_in_pin, uint8_t in_pin_count, uint32_t pull_pin_up, uint32_t pull_pin_down, - const mcu_pin_obj_t * first_set_pin, uint8_t set_pin_count, - const mcu_pin_obj_t * first_sideset_pin, uint8_t sideset_pin_count, + const mcu_pin_obj_t *first_set_pin, uint8_t set_pin_count, + const mcu_pin_obj_t *first_sideset_pin, uint8_t sideset_pin_count, uint32_t initial_pin_state, uint32_t initial_pin_direction, uint32_t pins_we_use, bool tx_fifo, bool rx_fifo, bool auto_pull, uint8_t pull_threshold, bool out_shift_right, diff --git a/ports/raspberrypi/common-hal/rp2pio/__init__.c b/ports/raspberrypi/common-hal/rp2pio/__init__.c index 5ad52c751c..ae4cb93d18 100644 --- a/ports/raspberrypi/common-hal/rp2pio/__init__.c +++ b/ports/raspberrypi/common-hal/rp2pio/__init__.c @@ -29,11 +29,11 @@ #include "bindings/rp2pio/__init__.h" bool common_hal_rp2pio_pins_are_sequential(size_t len, mp_obj_t *items) { - if(len == 0) { + if (len == 0) { return true; } mcu_pin_obj_t *last_pin = validate_obj_is_pin(items[0]); - for(int i=1; inumber != last_pin->number + 1) { return false; diff --git a/ports/raspberrypi/common-hal/rtc/RTC.c b/ports/raspberrypi/common-hal/rtc/RTC.c index e6c5d88712..8647fc246c 100644 --- a/ports/raspberrypi/common-hal/rtc/RTC.c +++ b/ports/raspberrypi/common-hal/rtc/RTC.c @@ -33,13 +33,13 @@ void common_hal_rtc_init(void) { datetime_t t = { - .year = 2020, - .month = 1, - .day = 1, - .dotw = 3, // 0 is Sunday, so 3 is Wednesday - .hour = 0, - .min = 0, - .sec = 0 + .year = 2020, + .month = 1, + .day = 1, + .dotw = 3, // 0 is Sunday, so 3 is Wednesday + .hour = 0, + .min = 0, + .sec = 0 }; // Start the RTC @@ -53,17 +53,17 @@ void common_hal_rtc_get_time(timeutils_struct_time_t *tm) { rtc_get_datetime(&t); tm->tm_year = t.year; - tm->tm_mon = t.month; + tm->tm_mon = t.month; tm->tm_mday = t.day; tm->tm_wday = t.dotw; tm->tm_hour = t.hour; - tm->tm_min = t.min; - tm->tm_sec = t.sec; + tm->tm_min = t.min; + tm->tm_sec = t.sec; if (tm->tm_wday == 0) { tm->tm_wday = 6; } else { - tm->tm_wday-=1; + tm->tm_wday -= 1; } } @@ -71,17 +71,17 @@ void common_hal_rtc_set_time(timeutils_struct_time_t *tm) { if (tm->tm_wday == 6) { tm->tm_wday = 0; } else { - tm->tm_wday+=1; + tm->tm_wday += 1; } datetime_t t = { - .year = tm->tm_year, - .month = tm->tm_mon, - .day = tm->tm_mday, - .dotw = tm->tm_wday, - .hour = tm->tm_hour, - .min = tm->tm_min, - .sec = tm->tm_sec + .year = tm->tm_year, + .month = tm->tm_mon, + .day = tm->tm_mday, + .dotw = tm->tm_wday, + .hour = tm->tm_hour, + .min = tm->tm_min, + .sec = tm->tm_sec }; rtc_set_datetime(&t); } diff --git a/ports/raspberrypi/common-hal/supervisor/Runtime.c b/ports/raspberrypi/common-hal/supervisor/Runtime.c old mode 100755 new mode 100644 index 974f26cec1..f827651781 --- a/ports/raspberrypi/common-hal/supervisor/Runtime.c +++ b/ports/raspberrypi/common-hal/supervisor/Runtime.c @@ -29,9 +29,9 @@ #include "supervisor/serial.h" bool common_hal_supervisor_runtime_get_serial_connected(void) { - return (bool) serial_connected(); + return (bool)serial_connected(); } bool common_hal_supervisor_runtime_get_serial_bytes_available(void) { - return (bool) serial_bytes_available(); + return (bool)serial_bytes_available(); } diff --git a/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.h b/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.h index ec1e2f6592..ce34f0b8ab 100644 --- a/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.h +++ b/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.h @@ -32,9 +32,9 @@ #include "shared-bindings/watchdog/WatchDogTimer.h" struct _watchdog_watchdogtimer_obj_t { - mp_obj_base_t base; - mp_float_t timeout; - watchdog_watchdogmode_t mode; + mp_obj_base_t base; + mp_float_t timeout; + watchdog_watchdogmode_t mode; }; // This needs to be called in order to disable the watchdog diff --git a/ports/raspberrypi/fatfs_port.c b/ports/raspberrypi/fatfs_port.c index c65a73a428..e6eee20495 100644 --- a/ports/raspberrypi/fatfs_port.c +++ b/ports/raspberrypi/fatfs_port.c @@ -35,14 +35,14 @@ #endif DWORD get_fattime(void) { -#if CIRCUITPY_RTC + #if CIRCUITPY_RTC timeutils_struct_time_t tm; common_hal_rtc_get_time(&tm); return ((tm.tm_year - 1980) << 25) | (tm.tm_mon << 21) | (tm.tm_mday << 16) | - (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1); -#else + (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec >> 1); + #else return ((2016 - 1980) << 25) | ((9) << 21) | ((1) << 16) | ((16) << 11) | ((43) << 5) | (35 / 2); -#endif + #endif } diff --git a/ports/raspberrypi/mpconfigport.h b/ports/raspberrypi/mpconfigport.h index dba008a94d..0259ffd023 100644 --- a/ports/raspberrypi/mpconfigport.h +++ b/ports/raspberrypi/mpconfigport.h @@ -31,10 +31,10 @@ #define MICROPY_PY_SYS_PLATFORM "RP2040" -#define CIRCUITPY_INTERNAL_NVM_SIZE (4*1024) +#define CIRCUITPY_INTERNAL_NVM_SIZE (4 * 1024) #define CIRCUITPY_INTERNAL_NVM_START_ADDR (0x100FF000) -#define CIRCUITPY_DEFAULT_STACK_SIZE (24*1024) +#define CIRCUITPY_DEFAULT_STACK_SIZE (24 * 1024) #define MICROPY_USE_INTERNAL_PRINTF (1) diff --git a/ports/raspberrypi/mphalport.h b/ports/raspberrypi/mphalport.h index 8d2d7d51a2..6d47534388 100644 --- a/ports/raspberrypi/mphalport.h +++ b/ports/raspberrypi/mphalport.h @@ -34,7 +34,7 @@ #include "supervisor/shared/tick.h" // Global millisecond tick count (driven by SysTick interrupt). -#define mp_hal_ticks_ms() ((mp_uint_t) supervisor_ticks_ms32()) +#define mp_hal_ticks_ms() ((mp_uint_t)supervisor_ticks_ms32()) // Number of bytes in receive buffer extern volatile uint8_t usb_rx_count; diff --git a/ports/raspberrypi/peripherals/pins.c b/ports/raspberrypi/peripherals/pins.c index a2a7b85bd3..1b5fe91cac 100644 --- a/ports/raspberrypi/peripherals/pins.c +++ b/ports/raspberrypi/peripherals/pins.c @@ -30,10 +30,10 @@ // This macro is used to simplify pin definition in boards//pins.c #define PIN(p_number) \ -const mcu_pin_obj_t pin_GPIO## p_number = { \ - { &mcu_pin_type }, \ - .number = p_number \ -} + const mcu_pin_obj_t pin_GPIO##p_number = { \ + { &mcu_pin_type }, \ + .number = p_number \ + } PIN(0); PIN(1); diff --git a/ports/raspberrypi/supervisor/internal_flash.c b/ports/raspberrypi/supervisor/internal_flash.c index e8ee5cf1a6..81f26967e3 100644 --- a/ports/raspberrypi/supervisor/internal_flash.c +++ b/ports/raspberrypi/supervisor/internal_flash.c @@ -85,8 +85,8 @@ void port_internal_flash_flush(void) { mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t num_blocks) { memcpy(dest, - (void*)(XIP_BASE + RESERVED_FLASH + block * FILESYSTEM_BLOCK_SIZE), - num_blocks * FILESYSTEM_BLOCK_SIZE); + (void *)(XIP_BASE + RESERVED_FLASH + block * FILESYSTEM_BLOCK_SIZE), + num_blocks * FILESYSTEM_BLOCK_SIZE); return 0; } @@ -100,18 +100,18 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 if (_cache_lba != block_address) { memcpy(_cache, - (void*)(XIP_BASE + RESERVED_FLASH + sector_offset), - SECTOR_SIZE); + (void *)(XIP_BASE + RESERVED_FLASH + sector_offset), + SECTOR_SIZE); _cache_lba = sector_offset; } for (uint8_t b = block_offset; b < blocks_per_sector; b++) { // Stop copying after the last block. if (block >= num_blocks) { - break; + break; } memcpy(_cache + b * FILESYSTEM_BLOCK_SIZE, - src + block * FILESYSTEM_BLOCK_SIZE, - FILESYSTEM_BLOCK_SIZE); + src + block * FILESYSTEM_BLOCK_SIZE, + FILESYSTEM_BLOCK_SIZE); block++; } // Make sure we don't have an interrupt while we do flash operations. diff --git a/ports/raspberrypi/supervisor/port.c b/ports/raspberrypi/supervisor/port.c index 501a0c5ce2..cf4c05f81f 100644 --- a/ports/raspberrypi/supervisor/port.c +++ b/ports/raspberrypi/supervisor/port.c @@ -128,7 +128,8 @@ void reset_port(void) { void reset_to_bootloader(void) { reset_usb_boot(0, 0); - while (true) {} + while (true) { + } } void reset_cpu(void) { @@ -172,7 +173,7 @@ uint32_t port_get_saved_word(void) { return watchdog_hw->scratch[0]; } -uint64_t port_get_raw_ticks(uint8_t* subticks) { +uint64_t port_get_raw_ticks(uint8_t *subticks) { uint64_t microseconds = time_us_64(); return 1024 * (microseconds / 1000000) + (microseconds % 1000000) / 977; } @@ -210,16 +211,15 @@ void port_idle_until_interrupt(void) { /** * \brief Default interrupt handler for unused IRQs. */ -__attribute__((used)) void HardFault_Handler(void) -{ -#ifdef ENABLE_MICRO_TRACE_BUFFER +__attribute__((used)) void HardFault_Handler(void) { + #ifdef ENABLE_MICRO_TRACE_BUFFER // Turn off the micro trace buffer so we don't fill it up in the infinite // loop below. REG_MTB_MASTER = 0x00000000 + 6; -#endif + #endif reset_into_safe_mode(HARD_CRASH); while (true) { - asm("nop;"); + asm ("nop;"); } } diff --git a/ports/stm/background.c b/ports/stm/background.c index d83a0ccec7..dbf5ccee2b 100644 --- a/ports/stm/background.c +++ b/ports/stm/background.c @@ -33,6 +33,9 @@ #include "shared-module/displayio/__init__.h" #endif -void port_background_task(void) {} -void port_start_background_task(void) {} -void port_finish_background_task(void) {} +void port_background_task(void) { +} +void port_start_background_task(void) { +} +void port_finish_background_task(void) { +} diff --git a/ports/stm/boards/espruino_pico/mpconfigboard.h b/ports/stm/boards/espruino_pico/mpconfigboard.h index fe4ed6ca25..9a3f93864e 100644 --- a/ports/stm/boards/espruino_pico/mpconfigboard.h +++ b/ports/stm/boards/espruino_pico/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Espruino Pico" #define MICROPY_HW_MCU_NAME "STM32F401xD" diff --git a/ports/stm/boards/espruino_wifi/board.c b/ports/stm/boards/espruino_wifi/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/espruino_wifi/board.c +++ b/ports/stm/boards/espruino_wifi/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/espruino_wifi/mpconfigboard.h b/ports/stm/boards/espruino_wifi/mpconfigboard.h index b7f38f69be..b857650d6b 100644 --- a/ports/stm/boards/espruino_wifi/mpconfigboard.h +++ b/ports/stm/boards/espruino_wifi/mpconfigboard.h @@ -24,13 +24,13 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Espruino Wifi" #define MICROPY_HW_MCU_NAME "STM32F411xE" -#define FLASH_SIZE (0x80000) //512K -#define FLASH_PAGE_SIZE (0x4000) //16K +#define FLASH_SIZE (0x80000) // 512K +#define FLASH_PAGE_SIZE (0x4000) // 16K #define HSE_VALUE ((uint32_t)8000000) #define LSE_VALUE ((uint32_t)32768) diff --git a/ports/stm/boards/espruino_wifi/pins.c b/ports/stm/boards/espruino_wifi/pins.c index 8800317d50..2d36ae8b95 100644 --- a/ports/stm/boards/espruino_wifi/pins.c +++ b/ports/stm/boards/espruino_wifi/pins.c @@ -1,39 +1,39 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - //P1 - { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA00) }, - { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA04) }, - { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PA07) }, - { MP_ROM_QSTR(MP_QSTR_B1), MP_ROM_PTR(&pin_PB01) }, - { MP_ROM_QSTR(MP_QSTR_B10), MP_ROM_PTR(&pin_PB10) }, - { MP_ROM_QSTR(MP_QSTR_B13), MP_ROM_PTR(&pin_PB13) }, - { MP_ROM_QSTR(MP_QSTR_B14), MP_ROM_PTR(&pin_PB14) }, - { MP_ROM_QSTR(MP_QSTR_B15), MP_ROM_PTR(&pin_PB15) }, + // P1 + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_B1), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_B10), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_B13), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_B14), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_B15), MP_ROM_PTR(&pin_PB15) }, - { MP_ROM_QSTR(MP_QSTR_B0), MP_ROM_PTR(&pin_PB00) }, - { MP_ROM_QSTR(MP_QSTR_B9), MP_ROM_PTR(&pin_PB09) }, - { MP_ROM_QSTR(MP_QSTR_B8), MP_ROM_PTR(&pin_PB08) }, - { MP_ROM_QSTR(MP_QSTR_B7), MP_ROM_PTR(&pin_PB07) }, - { MP_ROM_QSTR(MP_QSTR_B6), MP_ROM_PTR(&pin_PB06) }, - { MP_ROM_QSTR(MP_QSTR_B5), MP_ROM_PTR(&pin_PB05) }, - { MP_ROM_QSTR(MP_QSTR_B4), MP_ROM_PTR(&pin_PB04) }, - { MP_ROM_QSTR(MP_QSTR_B3), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_B0), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_B9), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_B8), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_B7), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_B6), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_B5), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_B4), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_B3), MP_ROM_PTR(&pin_PB03) }, - { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PA10) }, - { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PB02) }, - { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PB12) }, - { MP_ROM_QSTR(MP_QSTR_BTN), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_BTN), MP_ROM_PTR(&pin_PC13) }, - { MP_ROM_QSTR(MP_QSTR_ESP_RX), MP_ROM_PTR(&pin_PA02) }, - { MP_ROM_QSTR(MP_QSTR_ESP_TX), MP_ROM_PTR(&pin_PA03) }, - { MP_ROM_QSTR(MP_QSTR_ESP_GPIO0), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_ESP_CHPD), MP_ROM_PTR(&pin_PA14) }, - { MP_ROM_QSTR(MP_QSTR_ESP_GPIO13), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_ESP_RX), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_ESP_TX), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_ESP_GPIO0), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_ESP_CHPD), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_ESP_GPIO13), MP_ROM_PTR(&pin_PA15) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/stm/boards/feather_stm32f405_express/mpconfigboard.h b/ports/stm/boards/feather_stm32f405_express/mpconfigboard.h index e69be6cf95..8558edd8cd 100644 --- a/ports/stm/boards/feather_stm32f405_express/mpconfigboard.h +++ b/ports/stm/boards/feather_stm32f405_express/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "Adafruit Feather STM32F405 Express" #define MICROPY_HW_MCU_NAME "STM32F405RG" @@ -46,7 +46,7 @@ // Bootloader only #ifdef UF2_BOOTLOADER_ENABLED - #define BOARD_VTOR_DEFER (1) //Leave VTOR relocation to bootloader + #define BOARD_VTOR_DEFER (1) // Leave VTOR relocation to bootloader #endif #define DEFAULT_I2C_BUS_SCL (&pin_PB06) diff --git a/ports/stm/boards/meowbit_v121/board.c b/ports/stm/boards/meowbit_v121/board.c index 4a8014a3a1..44d1254629 100644 --- a/ports/stm/boards/meowbit_v121/board.c +++ b/ports/stm/boards/meowbit_v121/board.c @@ -41,36 +41,36 @@ displayio_fourwire_obj_t board_display_obj; uint8_t display_init_sequence[] = { 0x01, 0 | DELAY, 150, // SWRESET - 0x11, 0 | DELAY, 255, // SLPOUT - 0xb1, 3, 0x01, 0x2C, 0x2D, // _FRMCTR1 - 0xb2, 3, 0x01, 0x2C, 0x2D, // - 0xb3, 6, 0x01, 0x2C, 0x2D, 0x01, 0x2C, 0x2D, - 0xb4, 1, 0x07, // _INVCTR line inversion - 0xc0, 3, 0xa2, 0x02, 0x84, // _PWCTR1 GVDD = 4.7V, 1.0uA - 0xc1, 1, 0xc5, // _PWCTR2 VGH=14.7V, VGL=-7.35V - 0xc2, 2, 0x0a, 0x00, // _PWCTR3 Opamp current small, Boost frequency - 0xc3, 2, 0x8a, 0x2a, - 0xc4, 2, 0x8a, 0xee, - 0xc5, 1, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V - 0x20, 0, // _INVOFF //MISMATCh 0x2a vs 0x20 - 0x36, 1, 0x18, // _MADCTL bottom to top refresh - // 1 clk cycle nonoverlap, 2 cycle gate rise, 3 sycle osc equalie, - // fix on VTL - 0x3a, 1, 0x05, // COLMOD - 16bit color - 0xe0, 0x10, 0x02, 0x1c, 0x07, 0x12, - 0x37, 0x32, 0x29, 0x2d, - 0x29, 0x25, 0x2B, 0x39, - 0x00, 0x01, 0x03, 0x10, // _GMCTRP1 Gamma - 0xe1, 0x10, 0x03, 0x1d, 0x07, 0x06, - 0x2E, 0x2C, 0x29, 0x2D, - 0x2E, 0x2E, 0x37, 0x3F, - 0x00, 0x00, 0x02, 0x10, // _GMCTRN1 - 0x13, 0 | DELAY, 10, // _NORON - 0x29, 0 | DELAY, 100, // _DISPON + 0x11, 0 | DELAY, 255, // SLPOUT + 0xb1, 3, 0x01, 0x2C, 0x2D, // _FRMCTR1 + 0xb2, 3, 0x01, 0x2C, 0x2D, // + 0xb3, 6, 0x01, 0x2C, 0x2D, 0x01, 0x2C, 0x2D, + 0xb4, 1, 0x07, // _INVCTR line inversion + 0xc0, 3, 0xa2, 0x02, 0x84, // _PWCTR1 GVDD = 4.7V, 1.0uA + 0xc1, 1, 0xc5, // _PWCTR2 VGH=14.7V, VGL=-7.35V + 0xc2, 2, 0x0a, 0x00, // _PWCTR3 Opamp current small, Boost frequency + 0xc3, 2, 0x8a, 0x2a, + 0xc4, 2, 0x8a, 0xee, + 0xc5, 1, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V + 0x20, 0, // _INVOFF //MISMATCh 0x2a vs 0x20 + 0x36, 1, 0x18, // _MADCTL bottom to top refresh + // 1 clk cycle nonoverlap, 2 cycle gate rise, 3 sycle osc equalie, + // fix on VTL + 0x3a, 1, 0x05, // COLMOD - 16bit color + 0xe0, 0x10, 0x02, 0x1c, 0x07, 0x12, + 0x37, 0x32, 0x29, 0x2d, + 0x29, 0x25, 0x2B, 0x39, + 0x00, 0x01, 0x03, 0x10, // _GMCTRP1 Gamma + 0xe1, 0x10, 0x03, 0x1d, 0x07, 0x06, + 0x2E, 0x2C, 0x29, 0x2D, + 0x2E, 0x2E, 0x37, 0x3F, + 0x00, 0x00, 0x02, 0x10, // _GMCTRN1 + 0x13, 0 | DELAY, 10, // _NORON + 0x29, 0 | DELAY, 100, // _DISPON }; void board_init(void) { - displayio_fourwire_obj_t* bus = &displays[0].fourwire_bus; + displayio_fourwire_obj_t *bus = &displays[0].fourwire_bus; bus->base.type = &displayio_fourwire_type; busio_spi_obj_t *internal_spi = &supervisor_flash_spi_bus; common_hal_displayio_fourwire_construct(bus, @@ -82,7 +82,7 @@ void board_init(void) { 0, // Polarity 0); // Phase - displayio_display_obj_t* display = &displays[0].display; + displayio_display_obj_t *display = &displays[0].display; display->base.type = &displayio_display_type; common_hal_displayio_display_construct(display, bus, diff --git a/ports/stm/boards/meowbit_v121/mpconfigboard.h b/ports/stm/boards/meowbit_v121/mpconfigboard.h index be9f2a75fb..7807437941 100644 --- a/ports/stm/boards/meowbit_v121/mpconfigboard.h +++ b/ports/stm/boards/meowbit_v121/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "MEOWBIT" #define MICROPY_HW_MCU_NAME "STM32F401xE" @@ -39,7 +39,7 @@ #define BOARD_HAS_LOW_SPEED_CRYSTAL (0) #define BOARD_NO_VBUS_SENSE (1) -#define BOARD_VTOR_DEFER (1) //Leave VTOR relocation to bootloader +#define BOARD_VTOR_DEFER (1) // Leave VTOR relocation to bootloader #define BOARD_USE_INTERNAL_SPI // On-board flash diff --git a/ports/stm/boards/meowbit_v121/pins.c b/ports/stm/boards/meowbit_v121/pins.c index af896fad87..d11341145f 100644 --- a/ports/stm/boards/meowbit_v121/pins.c +++ b/ports/stm/boards/meowbit_v121/pins.c @@ -55,7 +55,7 @@ STATIC const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_P9), MP_ROM_PTR(&pin_PC06) }, { MP_ROM_QSTR(MP_QSTR_P8), MP_ROM_PTR(&pin_PA04) }, { MP_ROM_QSTR(MP_QSTR_P1), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_PA10) }, //in use by USB + { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_PA10) }, // in use by USB { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_PC07) }, { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_PB05) }, { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_PC01) }, diff --git a/ports/stm/boards/nucleo_f746zg/board.c b/ports/stm/boards/nucleo_f746zg/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/nucleo_f746zg/board.c +++ b/ports/stm/boards/nucleo_f746zg/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/nucleo_f746zg/mpconfigboard.h b/ports/stm/boards/nucleo_f746zg/mpconfigboard.h index e2b54335a5..ef8f84ceba 100644 --- a/ports/stm/boards/nucleo_f746zg/mpconfigboard.h +++ b/ports/stm/boards/nucleo_f746zg/mpconfigboard.h @@ -25,7 +25,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "NUCLEO STM32F746" #define MICROPY_HW_MCU_NAME "STM32F746" diff --git a/ports/stm/boards/nucleo_f746zg/pins.c b/ports/stm/boards/nucleo_f746zg/pins.c index 7c6a075e23..251ce4bcba 100644 --- a/ports/stm/boards/nucleo_f746zg/pins.c +++ b/ports/stm/boards/nucleo_f746zg/pins.c @@ -1,74 +1,74 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { -{ MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA03) }, -{ MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PC00) }, -{ MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PC03) }, -{ MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PF03) }, -{ MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PF05) }, -{ MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PF10) }, -{ MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PG09) }, -{ MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PG14) }, -{ MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PF15) }, -{ MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PE13) }, -{ MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PF14) }, -{ MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PE11) }, -{ MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PE09) }, -{ MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PF13) }, -{ MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PF12) }, -{ MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PD15) }, -{ MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PD14) }, -{ MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA07) }, -{ MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA06) }, -{ MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA05) }, -{ MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB09) }, -{ MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PB08) }, -{ MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_PC06) }, -{ MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_PB15) }, -{ MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_PB13) }, -{ MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_PB12) }, -{ MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_PA15) }, -{ MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_PC07) }, -{ MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_PB05) }, -{ MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_PB03) }, -{ MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_PA04) }, -{ MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_PB04) }, -{ MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PB00) }, -{ MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PB07) }, -{ MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PB14) }, -{ MP_ROM_QSTR(MP_QSTR_SW), MP_ROM_PTR(&pin_PC13) }, -{ MP_ROM_QSTR(MP_QSTR_TP1), MP_ROM_PTR(&pin_PH02) }, -{ MP_ROM_QSTR(MP_QSTR_TP2), MP_ROM_PTR(&pin_PI08) }, -{ MP_ROM_QSTR(MP_QSTR_TP3), MP_ROM_PTR(&pin_PH15) }, -{ MP_ROM_QSTR(MP_QSTR_AUDIO_INT), MP_ROM_PTR(&pin_PD06) }, -{ MP_ROM_QSTR(MP_QSTR_AUDIO_SDA), MP_ROM_PTR(&pin_PH08) }, -{ MP_ROM_QSTR(MP_QSTR_AUDIO_SCL), MP_ROM_PTR(&pin_PH07) }, -{ MP_ROM_QSTR(MP_QSTR_EXT_SDA), MP_ROM_PTR(&pin_PB09) }, -{ MP_ROM_QSTR(MP_QSTR_EXT_SCL), MP_ROM_PTR(&pin_PB08) }, -{ MP_ROM_QSTR(MP_QSTR_EXT_RST), MP_ROM_PTR(&pin_PG03) }, -{ MP_ROM_QSTR(MP_QSTR_SD_SW), MP_ROM_PTR(&pin_PC13) }, -{ MP_ROM_QSTR(MP_QSTR_LCD_BL_CTRL), MP_ROM_PTR(&pin_PK03) }, -{ MP_ROM_QSTR(MP_QSTR_LCD_INT), MP_ROM_PTR(&pin_PI13) }, -{ MP_ROM_QSTR(MP_QSTR_LCD_SDA), MP_ROM_PTR(&pin_PH08) }, -{ MP_ROM_QSTR(MP_QSTR_LCD_SCL), MP_ROM_PTR(&pin_PH07) }, -{ MP_ROM_QSTR(MP_QSTR_OTG_FS_POWER), MP_ROM_PTR(&pin_PD05) }, -{ MP_ROM_QSTR(MP_QSTR_OTG_FS_OVER_CURRENT), MP_ROM_PTR(&pin_PD04) }, -{ MP_ROM_QSTR(MP_QSTR_OTG_HS_OVER_CURRENT), MP_ROM_PTR(&pin_PE03) }, -{ MP_ROM_QSTR(MP_QSTR_USB_VBUS), MP_ROM_PTR(&pin_PA09) }, -{ MP_ROM_QSTR(MP_QSTR_USB_ID), MP_ROM_PTR(&pin_PA10) }, -{ MP_ROM_QSTR(MP_QSTR_USB_DM), MP_ROM_PTR(&pin_PA11) }, -{ MP_ROM_QSTR(MP_QSTR_USB_DP), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PC00) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PF03) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PF05) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PF10) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PG09) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PG14) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PF15) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PE13) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PF14) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PE11) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PE09) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PF13) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PF12) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PD15) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_PC06) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_PC07) }, + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_SW), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_TP1), MP_ROM_PTR(&pin_PH02) }, + { MP_ROM_QSTR(MP_QSTR_TP2), MP_ROM_PTR(&pin_PI08) }, + { MP_ROM_QSTR(MP_QSTR_TP3), MP_ROM_PTR(&pin_PH15) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_INT), MP_ROM_PTR(&pin_PD06) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_SDA), MP_ROM_PTR(&pin_PH08) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_SCL), MP_ROM_PTR(&pin_PH07) }, + { MP_ROM_QSTR(MP_QSTR_EXT_SDA), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_EXT_SCL), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_EXT_RST), MP_ROM_PTR(&pin_PG03) }, + { MP_ROM_QSTR(MP_QSTR_SD_SW), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BL_CTRL), MP_ROM_PTR(&pin_PK03) }, + { MP_ROM_QSTR(MP_QSTR_LCD_INT), MP_ROM_PTR(&pin_PI13) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SDA), MP_ROM_PTR(&pin_PH08) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SCL), MP_ROM_PTR(&pin_PH07) }, + { MP_ROM_QSTR(MP_QSTR_OTG_FS_POWER), MP_ROM_PTR(&pin_PD05) }, + { MP_ROM_QSTR(MP_QSTR_OTG_FS_OVER_CURRENT), MP_ROM_PTR(&pin_PD04) }, + { MP_ROM_QSTR(MP_QSTR_OTG_HS_OVER_CURRENT), MP_ROM_PTR(&pin_PE03) }, + { MP_ROM_QSTR(MP_QSTR_USB_VBUS), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_USB_ID), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_USB_DM), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_USB_DP), MP_ROM_PTR(&pin_PA12) }, // As we use these for the debug_console, we won't enable them here. // { MP_ROM_QSTR(MP_QSTR_VCP_TX), MP_ROM_PTR(&pin_PD08) }, // { MP_ROM_QSTR(MP_QSTR_VCP_RX), MP_ROM_PTR(&pin_PD09) }, -{ MP_ROM_QSTR(MP_QSTR_UART2_TX), MP_ROM_PTR(&pin_PD05) }, -{ MP_ROM_QSTR(MP_QSTR_UART2_RX), MP_ROM_PTR(&pin_PD06) }, -{ MP_ROM_QSTR(MP_QSTR_UART2_RTS), MP_ROM_PTR(&pin_PD04) }, -{ MP_ROM_QSTR(MP_QSTR_UART2_CTS), MP_ROM_PTR(&pin_PD03) }, -{ MP_ROM_QSTR(MP_QSTR_UART6_TX), MP_ROM_PTR(&pin_PG14) }, -{ MP_ROM_QSTR(MP_QSTR_UART6_RX), MP_ROM_PTR(&pin_PG09) }, -{ MP_ROM_QSTR(MP_QSTR_SPI_B_NSS), MP_ROM_PTR(&pin_PA04) }, -{ MP_ROM_QSTR(MP_QSTR_SPI_B_SCK), MP_ROM_PTR(&pin_PB03) }, -{ MP_ROM_QSTR(MP_QSTR_SPI_B_MOSI), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_UART2_TX), MP_ROM_PTR(&pin_PD05) }, + { MP_ROM_QSTR(MP_QSTR_UART2_RX), MP_ROM_PTR(&pin_PD06) }, + { MP_ROM_QSTR(MP_QSTR_UART2_RTS), MP_ROM_PTR(&pin_PD04) }, + { MP_ROM_QSTR(MP_QSTR_UART2_CTS), MP_ROM_PTR(&pin_PD03) }, + { MP_ROM_QSTR(MP_QSTR_UART6_TX), MP_ROM_PTR(&pin_PG14) }, + { MP_ROM_QSTR(MP_QSTR_UART6_RX), MP_ROM_PTR(&pin_PG09) }, + { MP_ROM_QSTR(MP_QSTR_SPI_B_NSS), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_SPI_B_SCK), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_SPI_B_MOSI), MP_ROM_PTR(&pin_PB05) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/stm/boards/nucleo_f767zi/board.c b/ports/stm/boards/nucleo_f767zi/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/nucleo_f767zi/board.c +++ b/ports/stm/boards/nucleo_f767zi/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/nucleo_f767zi/mpconfigboard.h b/ports/stm/boards/nucleo_f767zi/mpconfigboard.h index 327651923a..8db104e871 100644 --- a/ports/stm/boards/nucleo_f767zi/mpconfigboard.h +++ b/ports/stm/boards/nucleo_f767zi/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "NUCLEO STM32F767" #define MICROPY_HW_MCU_NAME "STM32F767" diff --git a/ports/stm/boards/nucleo_f767zi/pins.c b/ports/stm/boards/nucleo_f767zi/pins.c index 9ecc38f01f..0373fc4fb6 100644 --- a/ports/stm/boards/nucleo_f767zi/pins.c +++ b/ports/stm/boards/nucleo_f767zi/pins.c @@ -1,142 +1,142 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { -{ MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA03) }, -{ MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PC00) }, -{ MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PC03) }, -{ MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PF03) }, -{ MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PF05) }, -{ MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PF10) }, -{ MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PB01) }, -{ MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PC02) }, -{ MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PF04) }, -{ MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PG09) }, -{ MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PG14) }, -{ MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PF15) }, -{ MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PE13) }, -{ MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PF14) }, -{ MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PE11) }, -{ MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PE09) }, -{ MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PF13) }, -{ MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PF12) }, -{ MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PD15) }, -{ MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PD14) }, -{ MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA07) }, -{ MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA06) }, -{ MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA05) }, -{ MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB09) }, -{ MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PB08) }, -{ MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_PC06) }, -{ MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_PB15) }, -{ MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_PB13) }, -{ MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_PB12) }, -{ MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_PA15) }, -{ MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_PC07) }, -{ MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_PB05) }, -{ MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_PB03) }, -{ MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_PA04) }, -{ MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_PB04) }, -{ MP_ROM_QSTR(MP_QSTR_D26), MP_ROM_PTR(&pin_PB06) }, -{ MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_PB02) }, -{ MP_ROM_QSTR(MP_QSTR_D28), MP_ROM_PTR(&pin_PD13) }, -{ MP_ROM_QSTR(MP_QSTR_D29), MP_ROM_PTR(&pin_PD12) }, -{ MP_ROM_QSTR(MP_QSTR_D30), MP_ROM_PTR(&pin_PD11) }, -{ MP_ROM_QSTR(MP_QSTR_D31), MP_ROM_PTR(&pin_PE02) }, -{ MP_ROM_QSTR(MP_QSTR_D32), MP_ROM_PTR(&pin_PA00) }, -{ MP_ROM_QSTR(MP_QSTR_D33), MP_ROM_PTR(&pin_PB00) }, -{ MP_ROM_QSTR(MP_QSTR_D34), MP_ROM_PTR(&pin_PE00) }, -{ MP_ROM_QSTR(MP_QSTR_D35), MP_ROM_PTR(&pin_PB11) }, -{ MP_ROM_QSTR(MP_QSTR_D36), MP_ROM_PTR(&pin_PB10) }, -{ MP_ROM_QSTR(MP_QSTR_D37), MP_ROM_PTR(&pin_PE15) }, -{ MP_ROM_QSTR(MP_QSTR_D38), MP_ROM_PTR(&pin_PE14) }, -{ MP_ROM_QSTR(MP_QSTR_D39), MP_ROM_PTR(&pin_PE12) }, -{ MP_ROM_QSTR(MP_QSTR_D40), MP_ROM_PTR(&pin_PE10) }, -{ MP_ROM_QSTR(MP_QSTR_D41), MP_ROM_PTR(&pin_PE07) }, -{ MP_ROM_QSTR(MP_QSTR_D42), MP_ROM_PTR(&pin_PE08) }, -{ MP_ROM_QSTR(MP_QSTR_D43), MP_ROM_PTR(&pin_PC08) }, -{ MP_ROM_QSTR(MP_QSTR_D44), MP_ROM_PTR(&pin_PC09) }, -{ MP_ROM_QSTR(MP_QSTR_D45), MP_ROM_PTR(&pin_PC10) }, -{ MP_ROM_QSTR(MP_QSTR_D46), MP_ROM_PTR(&pin_PC11) }, -{ MP_ROM_QSTR(MP_QSTR_D47), MP_ROM_PTR(&pin_PC12) }, -{ MP_ROM_QSTR(MP_QSTR_D48), MP_ROM_PTR(&pin_PD02) }, -{ MP_ROM_QSTR(MP_QSTR_D49), MP_ROM_PTR(&pin_PG02) }, -{ MP_ROM_QSTR(MP_QSTR_D50), MP_ROM_PTR(&pin_PG03) }, -{ MP_ROM_QSTR(MP_QSTR_D51), MP_ROM_PTR(&pin_PD07) }, -{ MP_ROM_QSTR(MP_QSTR_D52), MP_ROM_PTR(&pin_PD06) }, -{ MP_ROM_QSTR(MP_QSTR_D53), MP_ROM_PTR(&pin_PD05) }, -{ MP_ROM_QSTR(MP_QSTR_D54), MP_ROM_PTR(&pin_PD04) }, -{ MP_ROM_QSTR(MP_QSTR_D55), MP_ROM_PTR(&pin_PD03) }, -{ MP_ROM_QSTR(MP_QSTR_D56), MP_ROM_PTR(&pin_PE02) }, -{ MP_ROM_QSTR(MP_QSTR_D57), MP_ROM_PTR(&pin_PE04) }, -{ MP_ROM_QSTR(MP_QSTR_D58), MP_ROM_PTR(&pin_PE05) }, -{ MP_ROM_QSTR(MP_QSTR_D59), MP_ROM_PTR(&pin_PE06) }, -{ MP_ROM_QSTR(MP_QSTR_D60), MP_ROM_PTR(&pin_PE03) }, -{ MP_ROM_QSTR(MP_QSTR_D61), MP_ROM_PTR(&pin_PF08) }, -{ MP_ROM_QSTR(MP_QSTR_D62), MP_ROM_PTR(&pin_PF07) }, -{ MP_ROM_QSTR(MP_QSTR_D63), MP_ROM_PTR(&pin_PF09) }, -{ MP_ROM_QSTR(MP_QSTR_D64), MP_ROM_PTR(&pin_PG01) }, -{ MP_ROM_QSTR(MP_QSTR_D65), MP_ROM_PTR(&pin_PG00) }, -{ MP_ROM_QSTR(MP_QSTR_D66), MP_ROM_PTR(&pin_PD01) }, -{ MP_ROM_QSTR(MP_QSTR_D67), MP_ROM_PTR(&pin_PD00) }, -{ MP_ROM_QSTR(MP_QSTR_D68), MP_ROM_PTR(&pin_PF00) }, -{ MP_ROM_QSTR(MP_QSTR_D69), MP_ROM_PTR(&pin_PF01) }, -{ MP_ROM_QSTR(MP_QSTR_D70), MP_ROM_PTR(&pin_PF02) }, -{ MP_ROM_QSTR(MP_QSTR_D71), MP_ROM_PTR(&pin_PA07) }, -{ MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_PA04) }, -{ MP_ROM_QSTR(MP_QSTR_DAC2), MP_ROM_PTR(&pin_PA05) }, -{ MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PB00) }, -{ MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PB07) }, -{ MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PB14) }, -{ MP_ROM_QSTR(MP_QSTR_SW), MP_ROM_PTR(&pin_PC13) }, -{ MP_ROM_QSTR(MP_QSTR_SD_D0), MP_ROM_PTR(&pin_PC08) }, -{ MP_ROM_QSTR(MP_QSTR_SD_D1), MP_ROM_PTR(&pin_PC09) }, -{ MP_ROM_QSTR(MP_QSTR_SD_D2), MP_ROM_PTR(&pin_PC10) }, -{ MP_ROM_QSTR(MP_QSTR_SD_D3), MP_ROM_PTR(&pin_PC11) }, -{ MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_PD02) }, -{ MP_ROM_QSTR(MP_QSTR_SD_CK), MP_ROM_PTR(&pin_PC12) }, -{ MP_ROM_QSTR(MP_QSTR_SD_SW), MP_ROM_PTR(&pin_PG02) }, -{ MP_ROM_QSTR(MP_QSTR_OTG_FS_POWER), MP_ROM_PTR(&pin_PG06) }, -{ MP_ROM_QSTR(MP_QSTR_OTG_FS_OVER_CURRENT), MP_ROM_PTR(&pin_PG07) }, -{ MP_ROM_QSTR(MP_QSTR_USB_VBUS), MP_ROM_PTR(&pin_PA09) }, -{ MP_ROM_QSTR(MP_QSTR_USB_ID), MP_ROM_PTR(&pin_PA10) }, -{ MP_ROM_QSTR(MP_QSTR_USB_DM), MP_ROM_PTR(&pin_PA11) }, -{ MP_ROM_QSTR(MP_QSTR_USB_DP), MP_ROM_PTR(&pin_PA12) }, -{ MP_ROM_QSTR(MP_QSTR_UART2_TX), MP_ROM_PTR(&pin_PD05) }, -{ MP_ROM_QSTR(MP_QSTR_UART2_RX), MP_ROM_PTR(&pin_PD06) }, -{ MP_ROM_QSTR(MP_QSTR_UART2_RTS), MP_ROM_PTR(&pin_PD04) }, -{ MP_ROM_QSTR(MP_QSTR_UART2_CTS), MP_ROM_PTR(&pin_PD03) }, -{ MP_ROM_QSTR(MP_QSTR_VCP_TX), MP_ROM_PTR(&pin_PD08) }, -{ MP_ROM_QSTR(MP_QSTR_VCP_RX), MP_ROM_PTR(&pin_PD09) }, -{ MP_ROM_QSTR(MP_QSTR_UART3_TX), MP_ROM_PTR(&pin_PD08) }, -{ MP_ROM_QSTR(MP_QSTR_UART3_RX), MP_ROM_PTR(&pin_PD09) }, -{ MP_ROM_QSTR(MP_QSTR_UART5_TX), MP_ROM_PTR(&pin_PB06) }, -{ MP_ROM_QSTR(MP_QSTR_UART5_RX), MP_ROM_PTR(&pin_PB12) }, -{ MP_ROM_QSTR(MP_QSTR_UART6_TX), MP_ROM_PTR(&pin_PC06) }, -{ MP_ROM_QSTR(MP_QSTR_UART6_RX), MP_ROM_PTR(&pin_PC07) }, -{ MP_ROM_QSTR(MP_QSTR_UART7_TX), MP_ROM_PTR(&pin_PF07) }, -{ MP_ROM_QSTR(MP_QSTR_UART7_RX), MP_ROM_PTR(&pin_PF06) }, -{ MP_ROM_QSTR(MP_QSTR_UART8_TX), MP_ROM_PTR(&pin_PE01) }, -{ MP_ROM_QSTR(MP_QSTR_UART8_RX), MP_ROM_PTR(&pin_PE00) }, -{ MP_ROM_QSTR(MP_QSTR_SPI3_NSS), MP_ROM_PTR(&pin_PA04) }, -{ MP_ROM_QSTR(MP_QSTR_SPI3_SCK), MP_ROM_PTR(&pin_PB03) }, -{ MP_ROM_QSTR(MP_QSTR_SPI3_MISO), MP_ROM_PTR(&pin_PB04) }, -{ MP_ROM_QSTR(MP_QSTR_SPI3_MOSI), MP_ROM_PTR(&pin_PB05) }, -{ MP_ROM_QSTR(MP_QSTR_I2C1_SDA), MP_ROM_PTR(&pin_PB09) }, -{ MP_ROM_QSTR(MP_QSTR_I2C1_SCL), MP_ROM_PTR(&pin_PB08) }, -{ MP_ROM_QSTR(MP_QSTR_I2C2_SDA), MP_ROM_PTR(&pin_PF00) }, -{ MP_ROM_QSTR(MP_QSTR_I2C2_SCL), MP_ROM_PTR(&pin_PF01) }, -{ MP_ROM_QSTR(MP_QSTR_I2C4_SCL), MP_ROM_PTR(&pin_PF14) }, -{ MP_ROM_QSTR(MP_QSTR_I2C4_SDA), MP_ROM_PTR(&pin_PF15) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_MDC), MP_ROM_PTR(&pin_PC01) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_MDIO), MP_ROM_PTR(&pin_PA02) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_REF_CLK), MP_ROM_PTR(&pin_PA01) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_CRS_DV), MP_ROM_PTR(&pin_PA07) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXD0), MP_ROM_PTR(&pin_PC04) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXD1), MP_ROM_PTR(&pin_PC05) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_TX_EN), MP_ROM_PTR(&pin_PG11) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_TXD0), MP_ROM_PTR(&pin_PG13) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_TXD1), MP_ROM_PTR(&pin_PB13) }, -{ MP_ROM_QSTR(MP_QSTR_SWDIO), MP_ROM_PTR(&pin_PA13) }, -{ MP_ROM_QSTR(MP_QSTR_SWDCLK), MP_ROM_PTR(&pin_PA14) } + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PC00) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PF03) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PF05) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PF10) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PC02) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PF04) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PG09) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PG14) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PF15) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PE13) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PF14) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PE11) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PE09) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PF13) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PF12) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PD15) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_PC06) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_PC07) }, + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_D26), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_D28), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_D29), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_D30), MP_ROM_PTR(&pin_PD11) }, + { MP_ROM_QSTR(MP_QSTR_D31), MP_ROM_PTR(&pin_PE02) }, + { MP_ROM_QSTR(MP_QSTR_D32), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_D33), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_D34), MP_ROM_PTR(&pin_PE00) }, + { MP_ROM_QSTR(MP_QSTR_D35), MP_ROM_PTR(&pin_PB11) }, + { MP_ROM_QSTR(MP_QSTR_D36), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_D37), MP_ROM_PTR(&pin_PE15) }, + { MP_ROM_QSTR(MP_QSTR_D38), MP_ROM_PTR(&pin_PE14) }, + { MP_ROM_QSTR(MP_QSTR_D39), MP_ROM_PTR(&pin_PE12) }, + { MP_ROM_QSTR(MP_QSTR_D40), MP_ROM_PTR(&pin_PE10) }, + { MP_ROM_QSTR(MP_QSTR_D41), MP_ROM_PTR(&pin_PE07) }, + { MP_ROM_QSTR(MP_QSTR_D42), MP_ROM_PTR(&pin_PE08) }, + { MP_ROM_QSTR(MP_QSTR_D43), MP_ROM_PTR(&pin_PC08) }, + { MP_ROM_QSTR(MP_QSTR_D44), MP_ROM_PTR(&pin_PC09) }, + { MP_ROM_QSTR(MP_QSTR_D45), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_D46), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_D47), MP_ROM_PTR(&pin_PC12) }, + { MP_ROM_QSTR(MP_QSTR_D48), MP_ROM_PTR(&pin_PD02) }, + { MP_ROM_QSTR(MP_QSTR_D49), MP_ROM_PTR(&pin_PG02) }, + { MP_ROM_QSTR(MP_QSTR_D50), MP_ROM_PTR(&pin_PG03) }, + { MP_ROM_QSTR(MP_QSTR_D51), MP_ROM_PTR(&pin_PD07) }, + { MP_ROM_QSTR(MP_QSTR_D52), MP_ROM_PTR(&pin_PD06) }, + { MP_ROM_QSTR(MP_QSTR_D53), MP_ROM_PTR(&pin_PD05) }, + { MP_ROM_QSTR(MP_QSTR_D54), MP_ROM_PTR(&pin_PD04) }, + { MP_ROM_QSTR(MP_QSTR_D55), MP_ROM_PTR(&pin_PD03) }, + { MP_ROM_QSTR(MP_QSTR_D56), MP_ROM_PTR(&pin_PE02) }, + { MP_ROM_QSTR(MP_QSTR_D57), MP_ROM_PTR(&pin_PE04) }, + { MP_ROM_QSTR(MP_QSTR_D58), MP_ROM_PTR(&pin_PE05) }, + { MP_ROM_QSTR(MP_QSTR_D59), MP_ROM_PTR(&pin_PE06) }, + { MP_ROM_QSTR(MP_QSTR_D60), MP_ROM_PTR(&pin_PE03) }, + { MP_ROM_QSTR(MP_QSTR_D61), MP_ROM_PTR(&pin_PF08) }, + { MP_ROM_QSTR(MP_QSTR_D62), MP_ROM_PTR(&pin_PF07) }, + { MP_ROM_QSTR(MP_QSTR_D63), MP_ROM_PTR(&pin_PF09) }, + { MP_ROM_QSTR(MP_QSTR_D64), MP_ROM_PTR(&pin_PG01) }, + { MP_ROM_QSTR(MP_QSTR_D65), MP_ROM_PTR(&pin_PG00) }, + { MP_ROM_QSTR(MP_QSTR_D66), MP_ROM_PTR(&pin_PD01) }, + { MP_ROM_QSTR(MP_QSTR_D67), MP_ROM_PTR(&pin_PD00) }, + { MP_ROM_QSTR(MP_QSTR_D68), MP_ROM_PTR(&pin_PF00) }, + { MP_ROM_QSTR(MP_QSTR_D69), MP_ROM_PTR(&pin_PF01) }, + { MP_ROM_QSTR(MP_QSTR_D70), MP_ROM_PTR(&pin_PF02) }, + { MP_ROM_QSTR(MP_QSTR_D71), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_DAC2), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_SW), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_SD_D0), MP_ROM_PTR(&pin_PC08) }, + { MP_ROM_QSTR(MP_QSTR_SD_D1), MP_ROM_PTR(&pin_PC09) }, + { MP_ROM_QSTR(MP_QSTR_SD_D2), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_SD_D3), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_PD02) }, + { MP_ROM_QSTR(MP_QSTR_SD_CK), MP_ROM_PTR(&pin_PC12) }, + { MP_ROM_QSTR(MP_QSTR_SD_SW), MP_ROM_PTR(&pin_PG02) }, + { MP_ROM_QSTR(MP_QSTR_OTG_FS_POWER), MP_ROM_PTR(&pin_PG06) }, + { MP_ROM_QSTR(MP_QSTR_OTG_FS_OVER_CURRENT), MP_ROM_PTR(&pin_PG07) }, + { MP_ROM_QSTR(MP_QSTR_USB_VBUS), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_USB_ID), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_USB_DM), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_USB_DP), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_UART2_TX), MP_ROM_PTR(&pin_PD05) }, + { MP_ROM_QSTR(MP_QSTR_UART2_RX), MP_ROM_PTR(&pin_PD06) }, + { MP_ROM_QSTR(MP_QSTR_UART2_RTS), MP_ROM_PTR(&pin_PD04) }, + { MP_ROM_QSTR(MP_QSTR_UART2_CTS), MP_ROM_PTR(&pin_PD03) }, + { MP_ROM_QSTR(MP_QSTR_VCP_TX), MP_ROM_PTR(&pin_PD08) }, + { MP_ROM_QSTR(MP_QSTR_VCP_RX), MP_ROM_PTR(&pin_PD09) }, + { MP_ROM_QSTR(MP_QSTR_UART3_TX), MP_ROM_PTR(&pin_PD08) }, + { MP_ROM_QSTR(MP_QSTR_UART3_RX), MP_ROM_PTR(&pin_PD09) }, + { MP_ROM_QSTR(MP_QSTR_UART5_TX), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_UART5_RX), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_UART6_TX), MP_ROM_PTR(&pin_PC06) }, + { MP_ROM_QSTR(MP_QSTR_UART6_RX), MP_ROM_PTR(&pin_PC07) }, + { MP_ROM_QSTR(MP_QSTR_UART7_TX), MP_ROM_PTR(&pin_PF07) }, + { MP_ROM_QSTR(MP_QSTR_UART7_RX), MP_ROM_PTR(&pin_PF06) }, + { MP_ROM_QSTR(MP_QSTR_UART8_TX), MP_ROM_PTR(&pin_PE01) }, + { MP_ROM_QSTR(MP_QSTR_UART8_RX), MP_ROM_PTR(&pin_PE00) }, + { MP_ROM_QSTR(MP_QSTR_SPI3_NSS), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_SPI3_SCK), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_SPI3_MISO), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_SPI3_MOSI), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SDA), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_I2C1_SCL), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_I2C2_SDA), MP_ROM_PTR(&pin_PF00) }, + { MP_ROM_QSTR(MP_QSTR_I2C2_SCL), MP_ROM_PTR(&pin_PF01) }, + { MP_ROM_QSTR(MP_QSTR_I2C4_SCL), MP_ROM_PTR(&pin_PF14) }, + { MP_ROM_QSTR(MP_QSTR_I2C4_SDA), MP_ROM_PTR(&pin_PF15) }, + { MP_ROM_QSTR(MP_QSTR_ETH_MDC), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_ETH_MDIO), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_REF_CLK), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_CRS_DV), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXD0), MP_ROM_PTR(&pin_PC04) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXD1), MP_ROM_PTR(&pin_PC05) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_TX_EN), MP_ROM_PTR(&pin_PG11) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_TXD0), MP_ROM_PTR(&pin_PG13) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_TXD1), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_SWDIO), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_SWDCLK), MP_ROM_PTR(&pin_PA14) } }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/stm/boards/nucleo_h743zi_2/board.c b/ports/stm/boards/nucleo_h743zi_2/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/nucleo_h743zi_2/board.c +++ b/ports/stm/boards/nucleo_h743zi_2/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/nucleo_h743zi_2/mpconfigboard.h b/ports/stm/boards/nucleo_h743zi_2/mpconfigboard.h index 2ac986701e..36c55a26aa 100644 --- a/ports/stm/boards/nucleo_h743zi_2/mpconfigboard.h +++ b/ports/stm/boards/nucleo_h743zi_2/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "NUCLEO STM32H743" #define MICROPY_HW_MCU_NAME "STM32H743" diff --git a/ports/stm/boards/openmv_h7/board.c b/ports/stm/boards/openmv_h7/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/openmv_h7/board.c +++ b/ports/stm/boards/openmv_h7/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/openmv_h7/mpconfigboard.h b/ports/stm/boards/openmv_h7/mpconfigboard.h index 77ae235ecf..ffeba28f62 100644 --- a/ports/stm/boards/openmv_h7/mpconfigboard.h +++ b/ports/stm/boards/openmv_h7/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "OPENMV-H7 R1" #define MICROPY_HW_MCU_NAME "STM32H743" diff --git a/ports/stm/boards/pyb_nano_v2/mpconfigboard.h b/ports/stm/boards/pyb_nano_v2/mpconfigboard.h index 7c1ab31e34..0960687d1e 100644 --- a/ports/stm/boards/pyb_nano_v2/mpconfigboard.h +++ b/ports/stm/boards/pyb_nano_v2/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "PYB LR Nano V2" #define MICROPY_HW_MCU_NAME "STM32F411CE" diff --git a/ports/stm/boards/pyboard_v11/board.c b/ports/stm/boards/pyboard_v11/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/pyboard_v11/board.c +++ b/ports/stm/boards/pyboard_v11/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/pyboard_v11/mpconfigboard.h b/ports/stm/boards/pyboard_v11/mpconfigboard.h index 50a90c52b0..1ce89a59fc 100644 --- a/ports/stm/boards/pyboard_v11/mpconfigboard.h +++ b/ports/stm/boards/pyboard_v11/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "PyboardV1_1" #define MICROPY_HW_MCU_NAME "STM32F405RG" diff --git a/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.h b/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.h index 4351339540..400e7bb2c1 100644 --- a/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.h +++ b/ports/stm/boards/stm32f411ce_blackpill/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "stm32f411ce-blackpill" #define MICROPY_HW_MCU_NAME "STM32F411CE" diff --git a/ports/stm/boards/stm32f411ce_blackpill/pins.c b/ports/stm/boards/stm32f411ce_blackpill/pins.c index 16946b8bee..7e25ad042b 100644 --- a/ports/stm/boards/stm32f411ce_blackpill/pins.c +++ b/ports/stm/boards/stm32f411ce_blackpill/pins.c @@ -6,10 +6,10 @@ STATIC const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_B14), MP_ROM_PTR(&pin_PB14) }, { MP_ROM_QSTR(MP_QSTR_B15), MP_ROM_PTR(&pin_PB15) }, { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PA09) }, //USB (shouldn't be used) - { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PA10) }, //USB (shouldn't be used) - { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_PA11) }, //USB (shouldn't be used) - { MP_ROM_QSTR(MP_QSTR_A12), MP_ROM_PTR(&pin_PA12) }, //USB (shouldn't be used) + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PA09) }, // USB (shouldn't be used) + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PA10) }, // USB (shouldn't be used) + { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_PA11) }, // USB (shouldn't be used) + { MP_ROM_QSTR(MP_QSTR_A12), MP_ROM_PTR(&pin_PA12) }, // USB (shouldn't be used) { MP_ROM_QSTR(MP_QSTR_A15), MP_ROM_PTR(&pin_PA15) }, { MP_ROM_QSTR(MP_QSTR_B3), MP_ROM_PTR(&pin_PB03) }, { MP_ROM_QSTR(MP_QSTR_B4), MP_ROM_PTR(&pin_PB04) }, diff --git a/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.h b/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.h index 65e224e47a..a7d56209c4 100644 --- a/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.h +++ b/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "stm32f411ce-blackpill-with-flash" #define MICROPY_HW_MCU_NAME "STM32F411CE" diff --git a/ports/stm/boards/stm32f411ce_blackpill_with_flash/pins.c b/ports/stm/boards/stm32f411ce_blackpill_with_flash/pins.c index 16946b8bee..7e25ad042b 100644 --- a/ports/stm/boards/stm32f411ce_blackpill_with_flash/pins.c +++ b/ports/stm/boards/stm32f411ce_blackpill_with_flash/pins.c @@ -6,10 +6,10 @@ STATIC const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_B14), MP_ROM_PTR(&pin_PB14) }, { MP_ROM_QSTR(MP_QSTR_B15), MP_ROM_PTR(&pin_PB15) }, { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PA09) }, //USB (shouldn't be used) - { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PA10) }, //USB (shouldn't be used) - { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_PA11) }, //USB (shouldn't be used) - { MP_ROM_QSTR(MP_QSTR_A12), MP_ROM_PTR(&pin_PA12) }, //USB (shouldn't be used) + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PA09) }, // USB (shouldn't be used) + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PA10) }, // USB (shouldn't be used) + { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_PA11) }, // USB (shouldn't be used) + { MP_ROM_QSTR(MP_QSTR_A12), MP_ROM_PTR(&pin_PA12) }, // USB (shouldn't be used) { MP_ROM_QSTR(MP_QSTR_A15), MP_ROM_PTR(&pin_PA15) }, { MP_ROM_QSTR(MP_QSTR_B3), MP_ROM_PTR(&pin_PB03) }, { MP_ROM_QSTR(MP_QSTR_B4), MP_ROM_PTR(&pin_PB04) }, diff --git a/ports/stm/boards/stm32f411ve_discovery/board.c b/ports/stm/boards/stm32f411ve_discovery/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/stm32f411ve_discovery/board.c +++ b/ports/stm/boards/stm32f411ve_discovery/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.h b/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.h index 0be43f4fb7..ec6e548339 100644 --- a/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.h +++ b/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.h @@ -24,13 +24,13 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "STM32F411E_DISCO" #define MICROPY_HW_MCU_NAME "STM32F411xE" -#define FLASH_SIZE (0x80000) //512K -#define FLASH_PAGE_SIZE (0x4000) //16K +#define FLASH_SIZE (0x80000) // 512K +#define FLASH_PAGE_SIZE (0x4000) // 16K #define HSE_VALUE ((uint32_t)8000000) #define BOARD_HSE_SOURCE (RCC_HSE_BYPASS) // ST boards use the STLink clock signal diff --git a/ports/stm/boards/stm32f411ve_discovery/pins.c b/ports/stm/boards/stm32f411ve_discovery/pins.c index 673c412d51..6261513342 100644 --- a/ports/stm/boards/stm32f411ve_discovery/pins.c +++ b/ports/stm/boards/stm32f411ve_discovery/pins.c @@ -1,106 +1,106 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - //P1 - { MP_ROM_QSTR(MP_QSTR_PC00), MP_ROM_PTR(&pin_PC00) }, - { MP_ROM_QSTR(MP_QSTR_PC01), MP_ROM_PTR(&pin_PC01) }, - { MP_ROM_QSTR(MP_QSTR_PC02), MP_ROM_PTR(&pin_PC02) }, - { MP_ROM_QSTR(MP_QSTR_PC03), MP_ROM_PTR(&pin_PC03) }, - { MP_ROM_QSTR(MP_QSTR_PA00), MP_ROM_PTR(&pin_PA00) }, - { MP_ROM_QSTR(MP_QSTR_PA01), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_PA02), MP_ROM_PTR(&pin_PA02) }, - { MP_ROM_QSTR(MP_QSTR_PA03), MP_ROM_PTR(&pin_PA03) }, - { MP_ROM_QSTR(MP_QSTR_PA04), MP_ROM_PTR(&pin_PA04) }, - { MP_ROM_QSTR(MP_QSTR_PA05), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_PA06), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_PA07), MP_ROM_PTR(&pin_PA07) }, - { MP_ROM_QSTR(MP_QSTR_PC04), MP_ROM_PTR(&pin_PC04) }, - { MP_ROM_QSTR(MP_QSTR_PC05), MP_ROM_PTR(&pin_PC05) }, - { MP_ROM_QSTR(MP_QSTR_PB00), MP_ROM_PTR(&pin_PB00) }, - { MP_ROM_QSTR(MP_QSTR_PB01), MP_ROM_PTR(&pin_PB01) }, - { MP_ROM_QSTR(MP_QSTR_PB02), MP_ROM_PTR(&pin_PB02) }, - { MP_ROM_QSTR(MP_QSTR_PE07), MP_ROM_PTR(&pin_PE07) }, - { MP_ROM_QSTR(MP_QSTR_PE08), MP_ROM_PTR(&pin_PE08) }, - { MP_ROM_QSTR(MP_QSTR_PE09), MP_ROM_PTR(&pin_PE09) }, - { MP_ROM_QSTR(MP_QSTR_PE10), MP_ROM_PTR(&pin_PE10) }, - { MP_ROM_QSTR(MP_QSTR_PE11), MP_ROM_PTR(&pin_PE11) }, - { MP_ROM_QSTR(MP_QSTR_PE12), MP_ROM_PTR(&pin_PE12) }, - { MP_ROM_QSTR(MP_QSTR_PE13), MP_ROM_PTR(&pin_PE13) }, - { MP_ROM_QSTR(MP_QSTR_PE14), MP_ROM_PTR(&pin_PE14) }, - { MP_ROM_QSTR(MP_QSTR_PE15), MP_ROM_PTR(&pin_PE15) }, - { MP_ROM_QSTR(MP_QSTR_PB10), MP_ROM_PTR(&pin_PB10) }, - { MP_ROM_QSTR(MP_QSTR_PB12), MP_ROM_PTR(&pin_PB12) }, - { MP_ROM_QSTR(MP_QSTR_PB13), MP_ROM_PTR(&pin_PB13) }, - { MP_ROM_QSTR(MP_QSTR_PB14), MP_ROM_PTR(&pin_PB14) }, - { MP_ROM_QSTR(MP_QSTR_PB15), MP_ROM_PTR(&pin_PB15) }, - { MP_ROM_QSTR(MP_QSTR_PD08), MP_ROM_PTR(&pin_PD08) }, - { MP_ROM_QSTR(MP_QSTR_PD09), MP_ROM_PTR(&pin_PD09) }, - { MP_ROM_QSTR(MP_QSTR_PD10), MP_ROM_PTR(&pin_PD10) }, - { MP_ROM_QSTR(MP_QSTR_PD11), MP_ROM_PTR(&pin_PD11) }, - { MP_ROM_QSTR(MP_QSTR_PD12), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_PD13), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_PD14), MP_ROM_PTR(&pin_PD14) }, - { MP_ROM_QSTR(MP_QSTR_PD15), MP_ROM_PTR(&pin_PD15) }, - //P2 - { MP_ROM_QSTR(MP_QSTR_PC14), MP_ROM_PTR(&pin_PC14) }, - { MP_ROM_QSTR(MP_QSTR_PC15), MP_ROM_PTR(&pin_PC15) }, - { MP_ROM_QSTR(MP_QSTR_PC13), MP_ROM_PTR(&pin_PC13) }, - { MP_ROM_QSTR(MP_QSTR_PE06), MP_ROM_PTR(&pin_PE06) }, - { MP_ROM_QSTR(MP_QSTR_PE05), MP_ROM_PTR(&pin_PE05) }, - { MP_ROM_QSTR(MP_QSTR_PE04), MP_ROM_PTR(&pin_PE04) }, - { MP_ROM_QSTR(MP_QSTR_PE03), MP_ROM_PTR(&pin_PE03) }, - { MP_ROM_QSTR(MP_QSTR_PE02), MP_ROM_PTR(&pin_PE02) }, - { MP_ROM_QSTR(MP_QSTR_PE01), MP_ROM_PTR(&pin_PE01) }, - { MP_ROM_QSTR(MP_QSTR_PE00), MP_ROM_PTR(&pin_PE00) }, - { MP_ROM_QSTR(MP_QSTR_PB09), MP_ROM_PTR(&pin_PB09) }, - { MP_ROM_QSTR(MP_QSTR_PB08), MP_ROM_PTR(&pin_PB08) }, - { MP_ROM_QSTR(MP_QSTR_PB07), MP_ROM_PTR(&pin_PB07) }, - { MP_ROM_QSTR(MP_QSTR_PB06), MP_ROM_PTR(&pin_PB06) }, - { MP_ROM_QSTR(MP_QSTR_PB05), MP_ROM_PTR(&pin_PB05) }, - { MP_ROM_QSTR(MP_QSTR_PB04), MP_ROM_PTR(&pin_PB04) }, - { MP_ROM_QSTR(MP_QSTR_PB03), MP_ROM_PTR(&pin_PB03) }, - { MP_ROM_QSTR(MP_QSTR_PD07), MP_ROM_PTR(&pin_PD07) }, - { MP_ROM_QSTR(MP_QSTR_PD06), MP_ROM_PTR(&pin_PD06) }, - { MP_ROM_QSTR(MP_QSTR_PD05), MP_ROM_PTR(&pin_PD05) }, - { MP_ROM_QSTR(MP_QSTR_PD04), MP_ROM_PTR(&pin_PD04) }, - { MP_ROM_QSTR(MP_QSTR_PD03), MP_ROM_PTR(&pin_PD03) }, - { MP_ROM_QSTR(MP_QSTR_PD02), MP_ROM_PTR(&pin_PD02) }, - { MP_ROM_QSTR(MP_QSTR_PD01), MP_ROM_PTR(&pin_PD01) }, - { MP_ROM_QSTR(MP_QSTR_PD00), MP_ROM_PTR(&pin_PD00) }, - { MP_ROM_QSTR(MP_QSTR_PC12), MP_ROM_PTR(&pin_PC12) }, - { MP_ROM_QSTR(MP_QSTR_PC11), MP_ROM_PTR(&pin_PC11) }, - { MP_ROM_QSTR(MP_QSTR_PC10), MP_ROM_PTR(&pin_PC10) }, - { MP_ROM_QSTR(MP_QSTR_PA15), MP_ROM_PTR(&pin_PA15) }, - { MP_ROM_QSTR(MP_QSTR_PA14), MP_ROM_PTR(&pin_PA14) }, - { MP_ROM_QSTR(MP_QSTR_PA13), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, - { MP_ROM_QSTR(MP_QSTR_PA09), MP_ROM_PTR(&pin_PA09) }, - { MP_ROM_QSTR(MP_QSTR_PA08), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_PC09), MP_ROM_PTR(&pin_PC09) }, - { MP_ROM_QSTR(MP_QSTR_PC08), MP_ROM_PTR(&pin_PC08) }, - { MP_ROM_QSTR(MP_QSTR_PC07), MP_ROM_PTR(&pin_PC07) }, - { MP_ROM_QSTR(MP_QSTR_PC06), MP_ROM_PTR(&pin_PC06) }, - //ST LED names - { MP_ROM_QSTR(MP_QSTR_LD3), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_LD4), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_LD5), MP_ROM_PTR(&pin_PD14) }, - { MP_ROM_QSTR(MP_QSTR_LD6), MP_ROM_PTR(&pin_PD15) }, - //more useful LED names - { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PD14) }, - { MP_ROM_QSTR(MP_QSTR_LED4), MP_ROM_PTR(&pin_PD15) }, - //AnalogIO names - { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA00) }, - { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA02) }, - { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PA03) }, - { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA04) }, - { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA05) }, - //actual LED names - { MP_ROM_QSTR(MP_QSTR_LED_ORANGE), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_PD14) }, - { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_PD15) }, + // P1 + { MP_ROM_QSTR(MP_QSTR_PC00), MP_ROM_PTR(&pin_PC00) }, + { MP_ROM_QSTR(MP_QSTR_PC01), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_PC02), MP_ROM_PTR(&pin_PC02) }, + { MP_ROM_QSTR(MP_QSTR_PC03), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_PA00), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_PA01), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_PA02), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_PA03), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_PA04), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_PA05), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_PA06), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_PA07), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_PC04), MP_ROM_PTR(&pin_PC04) }, + { MP_ROM_QSTR(MP_QSTR_PC05), MP_ROM_PTR(&pin_PC05) }, + { MP_ROM_QSTR(MP_QSTR_PB00), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_PB01), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_PB02), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_PE07), MP_ROM_PTR(&pin_PE07) }, + { MP_ROM_QSTR(MP_QSTR_PE08), MP_ROM_PTR(&pin_PE08) }, + { MP_ROM_QSTR(MP_QSTR_PE09), MP_ROM_PTR(&pin_PE09) }, + { MP_ROM_QSTR(MP_QSTR_PE10), MP_ROM_PTR(&pin_PE10) }, + { MP_ROM_QSTR(MP_QSTR_PE11), MP_ROM_PTR(&pin_PE11) }, + { MP_ROM_QSTR(MP_QSTR_PE12), MP_ROM_PTR(&pin_PE12) }, + { MP_ROM_QSTR(MP_QSTR_PE13), MP_ROM_PTR(&pin_PE13) }, + { MP_ROM_QSTR(MP_QSTR_PE14), MP_ROM_PTR(&pin_PE14) }, + { MP_ROM_QSTR(MP_QSTR_PE15), MP_ROM_PTR(&pin_PE15) }, + { MP_ROM_QSTR(MP_QSTR_PB10), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_PB12), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_PB13), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_PB14), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_PB15), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_PD08), MP_ROM_PTR(&pin_PD08) }, + { MP_ROM_QSTR(MP_QSTR_PD09), MP_ROM_PTR(&pin_PD09) }, + { MP_ROM_QSTR(MP_QSTR_PD10), MP_ROM_PTR(&pin_PD10) }, + { MP_ROM_QSTR(MP_QSTR_PD11), MP_ROM_PTR(&pin_PD11) }, + { MP_ROM_QSTR(MP_QSTR_PD12), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_PD13), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_PD14), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_PD15), MP_ROM_PTR(&pin_PD15) }, + // P2 + { MP_ROM_QSTR(MP_QSTR_PC14), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_PC15), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_PC13), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_PE06), MP_ROM_PTR(&pin_PE06) }, + { MP_ROM_QSTR(MP_QSTR_PE05), MP_ROM_PTR(&pin_PE05) }, + { MP_ROM_QSTR(MP_QSTR_PE04), MP_ROM_PTR(&pin_PE04) }, + { MP_ROM_QSTR(MP_QSTR_PE03), MP_ROM_PTR(&pin_PE03) }, + { MP_ROM_QSTR(MP_QSTR_PE02), MP_ROM_PTR(&pin_PE02) }, + { MP_ROM_QSTR(MP_QSTR_PE01), MP_ROM_PTR(&pin_PE01) }, + { MP_ROM_QSTR(MP_QSTR_PE00), MP_ROM_PTR(&pin_PE00) }, + { MP_ROM_QSTR(MP_QSTR_PB09), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_PB08), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_PB07), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_PB06), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_PB05), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_PB04), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_PB03), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_PD07), MP_ROM_PTR(&pin_PD07) }, + { MP_ROM_QSTR(MP_QSTR_PD06), MP_ROM_PTR(&pin_PD06) }, + { MP_ROM_QSTR(MP_QSTR_PD05), MP_ROM_PTR(&pin_PD05) }, + { MP_ROM_QSTR(MP_QSTR_PD04), MP_ROM_PTR(&pin_PD04) }, + { MP_ROM_QSTR(MP_QSTR_PD03), MP_ROM_PTR(&pin_PD03) }, + { MP_ROM_QSTR(MP_QSTR_PD02), MP_ROM_PTR(&pin_PD02) }, + { MP_ROM_QSTR(MP_QSTR_PD01), MP_ROM_PTR(&pin_PD01) }, + { MP_ROM_QSTR(MP_QSTR_PD00), MP_ROM_PTR(&pin_PD00) }, + { MP_ROM_QSTR(MP_QSTR_PC12), MP_ROM_PTR(&pin_PC12) }, + { MP_ROM_QSTR(MP_QSTR_PC11), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_PC10), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_PA15), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_PA14), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_PA13), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_PA09), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_PA08), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_PC09), MP_ROM_PTR(&pin_PC09) }, + { MP_ROM_QSTR(MP_QSTR_PC08), MP_ROM_PTR(&pin_PC08) }, + { MP_ROM_QSTR(MP_QSTR_PC07), MP_ROM_PTR(&pin_PC07) }, + { MP_ROM_QSTR(MP_QSTR_PC06), MP_ROM_PTR(&pin_PC06) }, + // ST LED names + { MP_ROM_QSTR(MP_QSTR_LD3), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_LD4), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_LD5), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_LD6), MP_ROM_PTR(&pin_PD15) }, + // more useful LED names + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_LED4), MP_ROM_PTR(&pin_PD15) }, + // AnalogIO names + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA05) }, + // actual LED names + { MP_ROM_QSTR(MP_QSTR_LED_ORANGE), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_PD15) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/stm/boards/stm32f412zg_discovery/board.c b/ports/stm/boards/stm32f412zg_discovery/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/stm32f412zg_discovery/board.c +++ b/ports/stm/boards/stm32f412zg_discovery/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/stm32f412zg_discovery/mpconfigboard.h b/ports/stm/boards/stm32f412zg_discovery/mpconfigboard.h index 6b9ab64678..3ae0761c7a 100644 --- a/ports/stm/boards/stm32f412zg_discovery/mpconfigboard.h +++ b/ports/stm/boards/stm32f412zg_discovery/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "STM32F412G_DISCO" #define MICROPY_HW_MCU_NAME "STM32F412xGS" diff --git a/ports/stm/boards/stm32f412zg_discovery/pins.c b/ports/stm/boards/stm32f412zg_discovery/pins.c index ab90b04558..84e646ca7f 100644 --- a/ports/stm/boards/stm32f412zg_discovery/pins.c +++ b/ports/stm/boards/stm32f412zg_discovery/pins.c @@ -1,94 +1,94 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR_PE02), MP_ROM_PTR(&pin_PE02) }, - { MP_ROM_QSTR(MP_QSTR_PE03), MP_ROM_PTR(&pin_PE03) }, - { MP_ROM_QSTR(MP_QSTR_PE04), MP_ROM_PTR(&pin_PE04) }, - { MP_ROM_QSTR(MP_QSTR_PE05), MP_ROM_PTR(&pin_PE05) }, - { MP_ROM_QSTR(MP_QSTR_PE06), MP_ROM_PTR(&pin_PE06) }, - { MP_ROM_QSTR(MP_QSTR_PC13), MP_ROM_PTR(&pin_PC13) }, - { MP_ROM_QSTR(MP_QSTR_PF02), MP_ROM_PTR(&pin_PF02) }, - { MP_ROM_QSTR(MP_QSTR_PF03), MP_ROM_PTR(&pin_PF03) }, - { MP_ROM_QSTR(MP_QSTR_PF10), MP_ROM_PTR(&pin_PF10) }, - { MP_ROM_QSTR(MP_QSTR_PC00), MP_ROM_PTR(&pin_PC00) }, - { MP_ROM_QSTR(MP_QSTR_PC01), MP_ROM_PTR(&pin_PC01) }, - { MP_ROM_QSTR(MP_QSTR_PC02), MP_ROM_PTR(&pin_PC02) }, - { MP_ROM_QSTR(MP_QSTR_PC03), MP_ROM_PTR(&pin_PC03) }, - { MP_ROM_QSTR(MP_QSTR_PA01), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_PA02), MP_ROM_PTR(&pin_PA02) }, - { MP_ROM_QSTR(MP_QSTR_PA03), MP_ROM_PTR(&pin_PA03) }, - { MP_ROM_QSTR(MP_QSTR_PA04), MP_ROM_PTR(&pin_PA04) }, - { MP_ROM_QSTR(MP_QSTR_PA05), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_PA06), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_PA07), MP_ROM_PTR(&pin_PA07) }, - { MP_ROM_QSTR(MP_QSTR_PC04), MP_ROM_PTR(&pin_PC04) }, - { MP_ROM_QSTR(MP_QSTR_PC05), MP_ROM_PTR(&pin_PC05) }, - { MP_ROM_QSTR(MP_QSTR_PB00), MP_ROM_PTR(&pin_PB00) }, - { MP_ROM_QSTR(MP_QSTR_PB01), MP_ROM_PTR(&pin_PB01) }, - { MP_ROM_QSTR(MP_QSTR_PF11), MP_ROM_PTR(&pin_PF11) }, - { MP_ROM_QSTR(MP_QSTR_PF13), MP_ROM_PTR(&pin_PF13) }, - { MP_ROM_QSTR(MP_QSTR_PB10), MP_ROM_PTR(&pin_PB10) }, - { MP_ROM_QSTR(MP_QSTR_PB11), MP_ROM_PTR(&pin_PB11) }, - { MP_ROM_QSTR(MP_QSTR_PB12), MP_ROM_PTR(&pin_PB12) }, - { MP_ROM_QSTR(MP_QSTR_PB13), MP_ROM_PTR(&pin_PB13) }, - { MP_ROM_QSTR(MP_QSTR_PB14), MP_ROM_PTR(&pin_PB14) }, - { MP_ROM_QSTR(MP_QSTR_PB15), MP_ROM_PTR(&pin_PB15) }, - { MP_ROM_QSTR(MP_QSTR_PD12), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_PD13), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_PG02), MP_ROM_PTR(&pin_PG02) }, - { MP_ROM_QSTR(MP_QSTR_PC06), MP_ROM_PTR(&pin_PC06) }, - { MP_ROM_QSTR(MP_QSTR_PC07), MP_ROM_PTR(&pin_PC07) }, - { MP_ROM_QSTR(MP_QSTR_PC09), MP_ROM_PTR(&pin_PC09) }, - { MP_ROM_QSTR(MP_QSTR_PA08), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, - { MP_ROM_QSTR(MP_QSTR_PA13), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_PA14), MP_ROM_PTR(&pin_PA14) }, - { MP_ROM_QSTR(MP_QSTR_PA15), MP_ROM_PTR(&pin_PA15) }, - { MP_ROM_QSTR(MP_QSTR_PD06), MP_ROM_PTR(&pin_PD06) }, - { MP_ROM_QSTR(MP_QSTR_PG09), MP_ROM_PTR(&pin_PG09) }, - { MP_ROM_QSTR(MP_QSTR_PG10), MP_ROM_PTR(&pin_PG10) }, - { MP_ROM_QSTR(MP_QSTR_PG11), MP_ROM_PTR(&pin_PG11) }, - { MP_ROM_QSTR(MP_QSTR_PG12), MP_ROM_PTR(&pin_PG12) }, - { MP_ROM_QSTR(MP_QSTR_PG13), MP_ROM_PTR(&pin_PG13) }, - { MP_ROM_QSTR(MP_QSTR_PG14), MP_ROM_PTR(&pin_PG14) }, - { MP_ROM_QSTR(MP_QSTR_PB03), MP_ROM_PTR(&pin_PB03) }, - { MP_ROM_QSTR(MP_QSTR_PB04), MP_ROM_PTR(&pin_PB04) }, - { MP_ROM_QSTR(MP_QSTR_PB05), MP_ROM_PTR(&pin_PB05) }, - { MP_ROM_QSTR(MP_QSTR_PB06), MP_ROM_PTR(&pin_PB06) }, - { MP_ROM_QSTR(MP_QSTR_PB07), MP_ROM_PTR(&pin_PB07) }, - { MP_ROM_QSTR(MP_QSTR_PB08), MP_ROM_PTR(&pin_PB08) }, - { MP_ROM_QSTR(MP_QSTR_PB09), MP_ROM_PTR(&pin_PB09) }, - { MP_ROM_QSTR(MP_QSTR_PE00), MP_ROM_PTR(&pin_PE00) }, - { MP_ROM_QSTR(MP_QSTR_PE01), MP_ROM_PTR(&pin_PE01) }, - { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PB10) }, - { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB09) }, - { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA07) }, - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PA15) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PB08) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PG10) }, - { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PG11) }, - { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PF03) }, - { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PF10) }, - { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PG12) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PF04) }, - { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PG13) }, - { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PG14) }, //USART6 TX - { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PG09) }, //USART6 RX - { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PC01) }, - { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PC03) }, - { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PC04) }, - { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PC05) }, //alt PB09, see F401ZG-DISCO manual - { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PB00) }, //alt PB10, see F401ZG-DISCO manual - { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PB10) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PB09) }, - { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PE00) }, - { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PE01) }, - { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PE02) }, - { MP_ROM_QSTR(MP_QSTR_LED4), MP_ROM_PTR(&pin_PE03) }, + { MP_ROM_QSTR(MP_QSTR_PE02), MP_ROM_PTR(&pin_PE02) }, + { MP_ROM_QSTR(MP_QSTR_PE03), MP_ROM_PTR(&pin_PE03) }, + { MP_ROM_QSTR(MP_QSTR_PE04), MP_ROM_PTR(&pin_PE04) }, + { MP_ROM_QSTR(MP_QSTR_PE05), MP_ROM_PTR(&pin_PE05) }, + { MP_ROM_QSTR(MP_QSTR_PE06), MP_ROM_PTR(&pin_PE06) }, + { MP_ROM_QSTR(MP_QSTR_PC13), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_PF02), MP_ROM_PTR(&pin_PF02) }, + { MP_ROM_QSTR(MP_QSTR_PF03), MP_ROM_PTR(&pin_PF03) }, + { MP_ROM_QSTR(MP_QSTR_PF10), MP_ROM_PTR(&pin_PF10) }, + { MP_ROM_QSTR(MP_QSTR_PC00), MP_ROM_PTR(&pin_PC00) }, + { MP_ROM_QSTR(MP_QSTR_PC01), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_PC02), MP_ROM_PTR(&pin_PC02) }, + { MP_ROM_QSTR(MP_QSTR_PC03), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_PA01), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_PA02), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_PA03), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_PA04), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_PA05), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_PA06), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_PA07), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_PC04), MP_ROM_PTR(&pin_PC04) }, + { MP_ROM_QSTR(MP_QSTR_PC05), MP_ROM_PTR(&pin_PC05) }, + { MP_ROM_QSTR(MP_QSTR_PB00), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_PB01), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_PF11), MP_ROM_PTR(&pin_PF11) }, + { MP_ROM_QSTR(MP_QSTR_PF13), MP_ROM_PTR(&pin_PF13) }, + { MP_ROM_QSTR(MP_QSTR_PB10), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_PB11), MP_ROM_PTR(&pin_PB11) }, + { MP_ROM_QSTR(MP_QSTR_PB12), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_PB13), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_PB14), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_PB15), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_PD12), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_PD13), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_PG02), MP_ROM_PTR(&pin_PG02) }, + { MP_ROM_QSTR(MP_QSTR_PC06), MP_ROM_PTR(&pin_PC06) }, + { MP_ROM_QSTR(MP_QSTR_PC07), MP_ROM_PTR(&pin_PC07) }, + { MP_ROM_QSTR(MP_QSTR_PC09), MP_ROM_PTR(&pin_PC09) }, + { MP_ROM_QSTR(MP_QSTR_PA08), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_PA13), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_PA14), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_PA15), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_PD06), MP_ROM_PTR(&pin_PD06) }, + { MP_ROM_QSTR(MP_QSTR_PG09), MP_ROM_PTR(&pin_PG09) }, + { MP_ROM_QSTR(MP_QSTR_PG10), MP_ROM_PTR(&pin_PG10) }, + { MP_ROM_QSTR(MP_QSTR_PG11), MP_ROM_PTR(&pin_PG11) }, + { MP_ROM_QSTR(MP_QSTR_PG12), MP_ROM_PTR(&pin_PG12) }, + { MP_ROM_QSTR(MP_QSTR_PG13), MP_ROM_PTR(&pin_PG13) }, + { MP_ROM_QSTR(MP_QSTR_PG14), MP_ROM_PTR(&pin_PG14) }, + { MP_ROM_QSTR(MP_QSTR_PB03), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_PB04), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_PB05), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_PB06), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_PB07), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_PB08), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_PB09), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_PE00), MP_ROM_PTR(&pin_PE00) }, + { MP_ROM_QSTR(MP_QSTR_PE01), MP_ROM_PTR(&pin_PE01) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PG10) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PG11) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PF03) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PF10) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PG12) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PF04) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PG13) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PG14) }, // USART6 TX + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PG09) }, // USART6 RX + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PC04) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PC05) }, // alt PB09, see F401ZG-DISCO manual + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PB00) }, // alt PB10, see F401ZG-DISCO manual + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PE00) }, + { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PE01) }, + { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PE02) }, + { MP_ROM_QSTR(MP_QSTR_LED4), MP_ROM_PTR(&pin_PE03) }, - { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/stm/boards/stm32f4_discovery/board.c b/ports/stm/boards/stm32f4_discovery/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/stm32f4_discovery/board.c +++ b/ports/stm/boards/stm32f4_discovery/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/stm32f4_discovery/mpconfigboard.h b/ports/stm/boards/stm32f4_discovery/mpconfigboard.h index 44ee073780..410c21ec9a 100644 --- a/ports/stm/boards/stm32f4_discovery/mpconfigboard.h +++ b/ports/stm/boards/stm32f4_discovery/mpconfigboard.h @@ -24,7 +24,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "STM32F4_DISCO" #define MICROPY_HW_MCU_NAME "STM32F407VG" diff --git a/ports/stm/boards/stm32f4_discovery/pins.c b/ports/stm/boards/stm32f4_discovery/pins.c index 712932145a..ee53fbd784 100644 --- a/ports/stm/boards/stm32f4_discovery/pins.c +++ b/ports/stm/boards/stm32f4_discovery/pins.c @@ -1,107 +1,107 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { - //P1 - { MP_ROM_QSTR(MP_QSTR_PC00), MP_ROM_PTR(&pin_PC00) }, - { MP_ROM_QSTR(MP_QSTR_PC01), MP_ROM_PTR(&pin_PC01) }, - { MP_ROM_QSTR(MP_QSTR_PC02), MP_ROM_PTR(&pin_PC02) }, - { MP_ROM_QSTR(MP_QSTR_PC03), MP_ROM_PTR(&pin_PC03) }, - { MP_ROM_QSTR(MP_QSTR_PA00), MP_ROM_PTR(&pin_PA00) }, - { MP_ROM_QSTR(MP_QSTR_PA01), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_PA02), MP_ROM_PTR(&pin_PA02) }, - { MP_ROM_QSTR(MP_QSTR_PA03), MP_ROM_PTR(&pin_PA03) }, - { MP_ROM_QSTR(MP_QSTR_PA04), MP_ROM_PTR(&pin_PA04) }, - { MP_ROM_QSTR(MP_QSTR_PA05), MP_ROM_PTR(&pin_PA05) }, - { MP_ROM_QSTR(MP_QSTR_PA06), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_PA07), MP_ROM_PTR(&pin_PA07) }, - { MP_ROM_QSTR(MP_QSTR_PC04), MP_ROM_PTR(&pin_PC04) }, - { MP_ROM_QSTR(MP_QSTR_PC05), MP_ROM_PTR(&pin_PC05) }, - { MP_ROM_QSTR(MP_QSTR_PB00), MP_ROM_PTR(&pin_PB00) }, - { MP_ROM_QSTR(MP_QSTR_PB01), MP_ROM_PTR(&pin_PB01) }, - { MP_ROM_QSTR(MP_QSTR_PB02), MP_ROM_PTR(&pin_PB02) }, - { MP_ROM_QSTR(MP_QSTR_PE07), MP_ROM_PTR(&pin_PE07) }, - { MP_ROM_QSTR(MP_QSTR_PE08), MP_ROM_PTR(&pin_PE08) }, - { MP_ROM_QSTR(MP_QSTR_PE09), MP_ROM_PTR(&pin_PE09) }, - { MP_ROM_QSTR(MP_QSTR_PE10), MP_ROM_PTR(&pin_PE10) }, - { MP_ROM_QSTR(MP_QSTR_PE11), MP_ROM_PTR(&pin_PE11) }, - { MP_ROM_QSTR(MP_QSTR_PE12), MP_ROM_PTR(&pin_PE12) }, - { MP_ROM_QSTR(MP_QSTR_PE13), MP_ROM_PTR(&pin_PE13) }, - { MP_ROM_QSTR(MP_QSTR_PE14), MP_ROM_PTR(&pin_PE14) }, - { MP_ROM_QSTR(MP_QSTR_PE15), MP_ROM_PTR(&pin_PE15) }, - { MP_ROM_QSTR(MP_QSTR_PB11), MP_ROM_PTR(&pin_PB11) }, // Differs from F411 - { MP_ROM_QSTR(MP_QSTR_PB10), MP_ROM_PTR(&pin_PB10) }, - { MP_ROM_QSTR(MP_QSTR_PB12), MP_ROM_PTR(&pin_PB12) }, - { MP_ROM_QSTR(MP_QSTR_PB13), MP_ROM_PTR(&pin_PB13) }, - { MP_ROM_QSTR(MP_QSTR_PB14), MP_ROM_PTR(&pin_PB14) }, - { MP_ROM_QSTR(MP_QSTR_PB15), MP_ROM_PTR(&pin_PB15) }, - { MP_ROM_QSTR(MP_QSTR_PD08), MP_ROM_PTR(&pin_PD08) }, - { MP_ROM_QSTR(MP_QSTR_PD09), MP_ROM_PTR(&pin_PD09) }, - { MP_ROM_QSTR(MP_QSTR_PD10), MP_ROM_PTR(&pin_PD10) }, - { MP_ROM_QSTR(MP_QSTR_PD11), MP_ROM_PTR(&pin_PD11) }, - { MP_ROM_QSTR(MP_QSTR_PD12), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_PD13), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_PD14), MP_ROM_PTR(&pin_PD14) }, - { MP_ROM_QSTR(MP_QSTR_PD15), MP_ROM_PTR(&pin_PD15) }, - //P2 - { MP_ROM_QSTR(MP_QSTR_PC14), MP_ROM_PTR(&pin_PC14) }, - { MP_ROM_QSTR(MP_QSTR_PC15), MP_ROM_PTR(&pin_PC15) }, - { MP_ROM_QSTR(MP_QSTR_PC13), MP_ROM_PTR(&pin_PC13) }, - { MP_ROM_QSTR(MP_QSTR_PE06), MP_ROM_PTR(&pin_PE06) }, - { MP_ROM_QSTR(MP_QSTR_PE05), MP_ROM_PTR(&pin_PE05) }, - { MP_ROM_QSTR(MP_QSTR_PE04), MP_ROM_PTR(&pin_PE04) }, - { MP_ROM_QSTR(MP_QSTR_PE03), MP_ROM_PTR(&pin_PE03) }, - { MP_ROM_QSTR(MP_QSTR_PE02), MP_ROM_PTR(&pin_PE02) }, - { MP_ROM_QSTR(MP_QSTR_PE01), MP_ROM_PTR(&pin_PE01) }, - { MP_ROM_QSTR(MP_QSTR_PE00), MP_ROM_PTR(&pin_PE00) }, - { MP_ROM_QSTR(MP_QSTR_PB09), MP_ROM_PTR(&pin_PB09) }, - { MP_ROM_QSTR(MP_QSTR_PB08), MP_ROM_PTR(&pin_PB08) }, - { MP_ROM_QSTR(MP_QSTR_PB07), MP_ROM_PTR(&pin_PB07) }, - { MP_ROM_QSTR(MP_QSTR_PB06), MP_ROM_PTR(&pin_PB06) }, - { MP_ROM_QSTR(MP_QSTR_PB05), MP_ROM_PTR(&pin_PB05) }, - { MP_ROM_QSTR(MP_QSTR_PB04), MP_ROM_PTR(&pin_PB04) }, - { MP_ROM_QSTR(MP_QSTR_PB03), MP_ROM_PTR(&pin_PB03) }, - { MP_ROM_QSTR(MP_QSTR_PD07), MP_ROM_PTR(&pin_PD07) }, - { MP_ROM_QSTR(MP_QSTR_PD06), MP_ROM_PTR(&pin_PD06) }, - { MP_ROM_QSTR(MP_QSTR_PD05), MP_ROM_PTR(&pin_PD05) }, - { MP_ROM_QSTR(MP_QSTR_PD04), MP_ROM_PTR(&pin_PD04) }, - { MP_ROM_QSTR(MP_QSTR_PD03), MP_ROM_PTR(&pin_PD03) }, - { MP_ROM_QSTR(MP_QSTR_PD02), MP_ROM_PTR(&pin_PD02) }, - { MP_ROM_QSTR(MP_QSTR_PD01), MP_ROM_PTR(&pin_PD01) }, - { MP_ROM_QSTR(MP_QSTR_PD00), MP_ROM_PTR(&pin_PD00) }, - { MP_ROM_QSTR(MP_QSTR_PC12), MP_ROM_PTR(&pin_PC12) }, - { MP_ROM_QSTR(MP_QSTR_PC11), MP_ROM_PTR(&pin_PC11) }, - { MP_ROM_QSTR(MP_QSTR_PC10), MP_ROM_PTR(&pin_PC10) }, - { MP_ROM_QSTR(MP_QSTR_PA15), MP_ROM_PTR(&pin_PA15) }, - { MP_ROM_QSTR(MP_QSTR_PA14), MP_ROM_PTR(&pin_PA14) }, - { MP_ROM_QSTR(MP_QSTR_PA13), MP_ROM_PTR(&pin_PA13) }, - { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, - { MP_ROM_QSTR(MP_QSTR_PA09), MP_ROM_PTR(&pin_PA09) }, - { MP_ROM_QSTR(MP_QSTR_PA08), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_PC09), MP_ROM_PTR(&pin_PC09) }, - { MP_ROM_QSTR(MP_QSTR_PC08), MP_ROM_PTR(&pin_PC08) }, - { MP_ROM_QSTR(MP_QSTR_PC07), MP_ROM_PTR(&pin_PC07) }, - { MP_ROM_QSTR(MP_QSTR_PC06), MP_ROM_PTR(&pin_PC06) }, - //ST LED names - { MP_ROM_QSTR(MP_QSTR_LD3), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_LD4), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_LD5), MP_ROM_PTR(&pin_PD14) }, - { MP_ROM_QSTR(MP_QSTR_LD6), MP_ROM_PTR(&pin_PD15) }, - //more useful LED names - { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PD14) }, - { MP_ROM_QSTR(MP_QSTR_LED4), MP_ROM_PTR(&pin_PD15) }, - //AnalogIO names - { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA00) }, - { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA01) }, - { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA02) }, - { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PA03) }, - { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA04) }, - { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA05) }, - //actual LED names - { MP_ROM_QSTR(MP_QSTR_LED_ORANGE), MP_ROM_PTR(&pin_PD13) }, - { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_PD12) }, - { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_PD14) }, - { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_PD15) }, + // P1 + { MP_ROM_QSTR(MP_QSTR_PC00), MP_ROM_PTR(&pin_PC00) }, + { MP_ROM_QSTR(MP_QSTR_PC01), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_PC02), MP_ROM_PTR(&pin_PC02) }, + { MP_ROM_QSTR(MP_QSTR_PC03), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_PA00), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_PA01), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_PA02), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_PA03), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_PA04), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_PA05), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_PA06), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_PA07), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_PC04), MP_ROM_PTR(&pin_PC04) }, + { MP_ROM_QSTR(MP_QSTR_PC05), MP_ROM_PTR(&pin_PC05) }, + { MP_ROM_QSTR(MP_QSTR_PB00), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_PB01), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_PB02), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_PE07), MP_ROM_PTR(&pin_PE07) }, + { MP_ROM_QSTR(MP_QSTR_PE08), MP_ROM_PTR(&pin_PE08) }, + { MP_ROM_QSTR(MP_QSTR_PE09), MP_ROM_PTR(&pin_PE09) }, + { MP_ROM_QSTR(MP_QSTR_PE10), MP_ROM_PTR(&pin_PE10) }, + { MP_ROM_QSTR(MP_QSTR_PE11), MP_ROM_PTR(&pin_PE11) }, + { MP_ROM_QSTR(MP_QSTR_PE12), MP_ROM_PTR(&pin_PE12) }, + { MP_ROM_QSTR(MP_QSTR_PE13), MP_ROM_PTR(&pin_PE13) }, + { MP_ROM_QSTR(MP_QSTR_PE14), MP_ROM_PTR(&pin_PE14) }, + { MP_ROM_QSTR(MP_QSTR_PE15), MP_ROM_PTR(&pin_PE15) }, + { MP_ROM_QSTR(MP_QSTR_PB11), MP_ROM_PTR(&pin_PB11) }, // Differs from F411 + { MP_ROM_QSTR(MP_QSTR_PB10), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_PB12), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_PB13), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_PB14), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_PB15), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_PD08), MP_ROM_PTR(&pin_PD08) }, + { MP_ROM_QSTR(MP_QSTR_PD09), MP_ROM_PTR(&pin_PD09) }, + { MP_ROM_QSTR(MP_QSTR_PD10), MP_ROM_PTR(&pin_PD10) }, + { MP_ROM_QSTR(MP_QSTR_PD11), MP_ROM_PTR(&pin_PD11) }, + { MP_ROM_QSTR(MP_QSTR_PD12), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_PD13), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_PD14), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_PD15), MP_ROM_PTR(&pin_PD15) }, + // P2 + { MP_ROM_QSTR(MP_QSTR_PC14), MP_ROM_PTR(&pin_PC14) }, + { MP_ROM_QSTR(MP_QSTR_PC15), MP_ROM_PTR(&pin_PC15) }, + { MP_ROM_QSTR(MP_QSTR_PC13), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_PE06), MP_ROM_PTR(&pin_PE06) }, + { MP_ROM_QSTR(MP_QSTR_PE05), MP_ROM_PTR(&pin_PE05) }, + { MP_ROM_QSTR(MP_QSTR_PE04), MP_ROM_PTR(&pin_PE04) }, + { MP_ROM_QSTR(MP_QSTR_PE03), MP_ROM_PTR(&pin_PE03) }, + { MP_ROM_QSTR(MP_QSTR_PE02), MP_ROM_PTR(&pin_PE02) }, + { MP_ROM_QSTR(MP_QSTR_PE01), MP_ROM_PTR(&pin_PE01) }, + { MP_ROM_QSTR(MP_QSTR_PE00), MP_ROM_PTR(&pin_PE00) }, + { MP_ROM_QSTR(MP_QSTR_PB09), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_PB08), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_PB07), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_PB06), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_PB05), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_PB04), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_PB03), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_PD07), MP_ROM_PTR(&pin_PD07) }, + { MP_ROM_QSTR(MP_QSTR_PD06), MP_ROM_PTR(&pin_PD06) }, + { MP_ROM_QSTR(MP_QSTR_PD05), MP_ROM_PTR(&pin_PD05) }, + { MP_ROM_QSTR(MP_QSTR_PD04), MP_ROM_PTR(&pin_PD04) }, + { MP_ROM_QSTR(MP_QSTR_PD03), MP_ROM_PTR(&pin_PD03) }, + { MP_ROM_QSTR(MP_QSTR_PD02), MP_ROM_PTR(&pin_PD02) }, + { MP_ROM_QSTR(MP_QSTR_PD01), MP_ROM_PTR(&pin_PD01) }, + { MP_ROM_QSTR(MP_QSTR_PD00), MP_ROM_PTR(&pin_PD00) }, + { MP_ROM_QSTR(MP_QSTR_PC12), MP_ROM_PTR(&pin_PC12) }, + { MP_ROM_QSTR(MP_QSTR_PC11), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_PC10), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_PA15), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_PA14), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_PA13), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_PA09), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_PA08), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_PC09), MP_ROM_PTR(&pin_PC09) }, + { MP_ROM_QSTR(MP_QSTR_PC08), MP_ROM_PTR(&pin_PC08) }, + { MP_ROM_QSTR(MP_QSTR_PC07), MP_ROM_PTR(&pin_PC07) }, + { MP_ROM_QSTR(MP_QSTR_PC06), MP_ROM_PTR(&pin_PC06) }, + // ST LED names + { MP_ROM_QSTR(MP_QSTR_LD3), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_LD4), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_LD5), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_LD6), MP_ROM_PTR(&pin_PD15) }, + // more useful LED names + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_LED4), MP_ROM_PTR(&pin_PD15) }, + // AnalogIO names + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PA03) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA05) }, + // actual LED names + { MP_ROM_QSTR(MP_QSTR_LED_ORANGE), MP_ROM_PTR(&pin_PD13) }, + { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_PD12) }, + { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_PD15) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/stm/boards/stm32f746g_discovery/board.c b/ports/stm/boards/stm32f746g_discovery/board.c index db2c727271..68bf157b63 100644 --- a/ports/stm/boards/stm32f746g_discovery/board.c +++ b/ports/stm/boards/stm32f746g_discovery/board.c @@ -49,7 +49,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/stm32f746g_discovery/mpconfigboard.h b/ports/stm/boards/stm32f746g_discovery/mpconfigboard.h index 769990a98c..afcefe0ce3 100644 --- a/ports/stm/boards/stm32f746g_discovery/mpconfigboard.h +++ b/ports/stm/boards/stm32f746g_discovery/mpconfigboard.h @@ -25,7 +25,7 @@ * THE SOFTWARE. */ -//Micropython setup +// Micropython setup #define MICROPY_HW_BOARD_NAME "ST STM32F746G Discovery" #define MICROPY_HW_MCU_NAME "STM32F746" diff --git a/ports/stm/boards/stm32f746g_discovery/pins.c b/ports/stm/boards/stm32f746g_discovery/pins.c index a859c8d190..bd9c1dcb15 100644 --- a/ports/stm/boards/stm32f746g_discovery/pins.c +++ b/ports/stm/boards/stm32f746g_discovery/pins.c @@ -1,110 +1,110 @@ #include "shared-bindings/board/__init__.h" STATIC const mp_rom_map_elem_t board_module_globals_table[] = { -{ MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA00) }, -{ MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PF10) }, -{ MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PF09) }, -{ MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PF08) }, -{ MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PF07) }, -{ MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PF06) }, -{ MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PC07) }, -{ MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PC06) }, -{ MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PG06) }, -{ MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PB04) }, -{ MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PG07) }, -{ MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PA08) }, -{ MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PH06) }, -{ MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PI03) }, -{ MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PI02) }, -{ MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PA15) }, -{ MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PI00) }, -{ MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PB15) }, -{ MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PB14) }, -{ MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PI01) }, -{ MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB09) }, -{ MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PB08) }, -{ MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PI01) }, -{ MP_ROM_QSTR(MP_QSTR_SW), MP_ROM_PTR(&pin_PI11) }, -{ MP_ROM_QSTR(MP_QSTR_TP1), MP_ROM_PTR(&pin_PH02) }, -{ MP_ROM_QSTR(MP_QSTR_TP2), MP_ROM_PTR(&pin_PI08) }, -{ MP_ROM_QSTR(MP_QSTR_TP3), MP_ROM_PTR(&pin_PH15) }, -{ MP_ROM_QSTR(MP_QSTR_AUDIO_INT), MP_ROM_PTR(&pin_PD06) }, -{ MP_ROM_QSTR(MP_QSTR_AUDIO_SDA), MP_ROM_PTR(&pin_PH08) }, -{ MP_ROM_QSTR(MP_QSTR_AUDIO_SCL), MP_ROM_PTR(&pin_PH07) }, -{ MP_ROM_QSTR(MP_QSTR_EXT_SDA), MP_ROM_PTR(&pin_PB09) }, -{ MP_ROM_QSTR(MP_QSTR_EXT_SCL), MP_ROM_PTR(&pin_PB08) }, -{ MP_ROM_QSTR(MP_QSTR_EXT_RST), MP_ROM_PTR(&pin_PG03) }, -{ MP_ROM_QSTR(MP_QSTR_SD_D0), MP_ROM_PTR(&pin_PC08) }, -{ MP_ROM_QSTR(MP_QSTR_SD_D1), MP_ROM_PTR(&pin_PC09) }, -{ MP_ROM_QSTR(MP_QSTR_SD_D2), MP_ROM_PTR(&pin_PC10) }, -{ MP_ROM_QSTR(MP_QSTR_SD_D3), MP_ROM_PTR(&pin_PC11) }, -{ MP_ROM_QSTR(MP_QSTR_SD_CK), MP_ROM_PTR(&pin_PC12) }, -{ MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_PD02) }, -{ MP_ROM_QSTR(MP_QSTR_SD_SW), MP_ROM_PTR(&pin_PC13) }, -{ MP_ROM_QSTR(MP_QSTR_LCD_BL_CTRL), MP_ROM_PTR(&pin_PK03) }, -{ MP_ROM_QSTR(MP_QSTR_LCD_INT), MP_ROM_PTR(&pin_PI13) }, -{ MP_ROM_QSTR(MP_QSTR_LCD_SDA), MP_ROM_PTR(&pin_PH08) }, -{ MP_ROM_QSTR(MP_QSTR_LCD_SCL), MP_ROM_PTR(&pin_PH07) }, -{ MP_ROM_QSTR(MP_QSTR_OTG_FS_POWER), MP_ROM_PTR(&pin_PD05) }, -{ MP_ROM_QSTR(MP_QSTR_OTG_FS_OVER_CURRENT), MP_ROM_PTR(&pin_PD04) }, -{ MP_ROM_QSTR(MP_QSTR_OTG_HS_OVER_CURRENT), MP_ROM_PTR(&pin_PE03) }, -{ MP_ROM_QSTR(MP_QSTR_USB_VBUS), MP_ROM_PTR(&pin_PJ12) }, -{ MP_ROM_QSTR(MP_QSTR_USB_ID), MP_ROM_PTR(&pin_PA10) }, -{ MP_ROM_QSTR(MP_QSTR_USB_DM), MP_ROM_PTR(&pin_PA11) }, -{ MP_ROM_QSTR(MP_QSTR_USB_DP), MP_ROM_PTR(&pin_PA12) }, -{ MP_ROM_QSTR(MP_QSTR_VCP_TX), MP_ROM_PTR(&pin_PA09) }, -{ MP_ROM_QSTR(MP_QSTR_VCP_RX), MP_ROM_PTR(&pin_PB07) }, -{ MP_ROM_QSTR(MP_QSTR_CAN_TX), MP_ROM_PTR(&pin_PB13) }, -{ MP_ROM_QSTR(MP_QSTR_CAN_RX), MP_ROM_PTR(&pin_PB12) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_MDC), MP_ROM_PTR(&pin_PC01) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_MDIO), MP_ROM_PTR(&pin_PA02) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_REF_CLK), MP_ROM_PTR(&pin_PA01) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_CRS_DV), MP_ROM_PTR(&pin_PA07) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXD0), MP_ROM_PTR(&pin_PC04) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXD1), MP_ROM_PTR(&pin_PC05) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXER), MP_ROM_PTR(&pin_PG02) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_TX_EN), MP_ROM_PTR(&pin_PG11) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_TXD0), MP_ROM_PTR(&pin_PG13) }, -{ MP_ROM_QSTR(MP_QSTR_ETH_RMII_TXD1), MP_ROM_PTR(&pin_PG14) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_SDCKE0), MP_ROM_PTR(&pin_PC03) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_SDNE0), MP_ROM_PTR(&pin_PH03) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_SDCLK), MP_ROM_PTR(&pin_PG08) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_SDNCAS), MP_ROM_PTR(&pin_PG15) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_SDNRAS), MP_ROM_PTR(&pin_PF11) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_SDNWE), MP_ROM_PTR(&pin_PH05) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_BA0), MP_ROM_PTR(&pin_PG04) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_BA1), MP_ROM_PTR(&pin_PG05) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_NBL0), MP_ROM_PTR(&pin_PE00) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_NBL1), MP_ROM_PTR(&pin_PE01) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A0), MP_ROM_PTR(&pin_PF00) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A1), MP_ROM_PTR(&pin_PF01) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A2), MP_ROM_PTR(&pin_PF02) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A3), MP_ROM_PTR(&pin_PF03) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A4), MP_ROM_PTR(&pin_PF04) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A5), MP_ROM_PTR(&pin_PF05) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A6), MP_ROM_PTR(&pin_PF12) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A7), MP_ROM_PTR(&pin_PF13) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A8), MP_ROM_PTR(&pin_PF14) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A9), MP_ROM_PTR(&pin_PF15) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A10), MP_ROM_PTR(&pin_PG00) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_A11), MP_ROM_PTR(&pin_PG01) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D0), MP_ROM_PTR(&pin_PD14) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D1), MP_ROM_PTR(&pin_PD15) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D2), MP_ROM_PTR(&pin_PD00) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D3), MP_ROM_PTR(&pin_PD01) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D4), MP_ROM_PTR(&pin_PE07) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D5), MP_ROM_PTR(&pin_PE08) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D6), MP_ROM_PTR(&pin_PE09) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D7), MP_ROM_PTR(&pin_PE10) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D8), MP_ROM_PTR(&pin_PE11) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D9), MP_ROM_PTR(&pin_PE12) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D10), MP_ROM_PTR(&pin_PE13) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D11), MP_ROM_PTR(&pin_PE14) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D12), MP_ROM_PTR(&pin_PE15) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D13), MP_ROM_PTR(&pin_PD08) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D14), MP_ROM_PTR(&pin_PD09) }, -{ MP_ROM_QSTR(MP_QSTR_SDRAM_D15), MP_ROM_PTR(&pin_PD10) }, -{ MP_ROM_QSTR(MP_QSTR_I2C3_SDA), MP_ROM_PTR(&pin_PH08) }, -{ MP_ROM_QSTR(MP_QSTR_I2C3_SCL), MP_ROM_PTR(&pin_PH07) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PA00) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PF10) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PF09) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PF08) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PF07) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PF06) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PC07) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PC06) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PG06) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PG07) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PH06) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PI03) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PI02) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PI00) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PI01) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PI01) }, + { MP_ROM_QSTR(MP_QSTR_SW), MP_ROM_PTR(&pin_PI11) }, + { MP_ROM_QSTR(MP_QSTR_TP1), MP_ROM_PTR(&pin_PH02) }, + { MP_ROM_QSTR(MP_QSTR_TP2), MP_ROM_PTR(&pin_PI08) }, + { MP_ROM_QSTR(MP_QSTR_TP3), MP_ROM_PTR(&pin_PH15) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_INT), MP_ROM_PTR(&pin_PD06) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_SDA), MP_ROM_PTR(&pin_PH08) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_SCL), MP_ROM_PTR(&pin_PH07) }, + { MP_ROM_QSTR(MP_QSTR_EXT_SDA), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_EXT_SCL), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_EXT_RST), MP_ROM_PTR(&pin_PG03) }, + { MP_ROM_QSTR(MP_QSTR_SD_D0), MP_ROM_PTR(&pin_PC08) }, + { MP_ROM_QSTR(MP_QSTR_SD_D1), MP_ROM_PTR(&pin_PC09) }, + { MP_ROM_QSTR(MP_QSTR_SD_D2), MP_ROM_PTR(&pin_PC10) }, + { MP_ROM_QSTR(MP_QSTR_SD_D3), MP_ROM_PTR(&pin_PC11) }, + { MP_ROM_QSTR(MP_QSTR_SD_CK), MP_ROM_PTR(&pin_PC12) }, + { MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_PD02) }, + { MP_ROM_QSTR(MP_QSTR_SD_SW), MP_ROM_PTR(&pin_PC13) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BL_CTRL), MP_ROM_PTR(&pin_PK03) }, + { MP_ROM_QSTR(MP_QSTR_LCD_INT), MP_ROM_PTR(&pin_PI13) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SDA), MP_ROM_PTR(&pin_PH08) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SCL), MP_ROM_PTR(&pin_PH07) }, + { MP_ROM_QSTR(MP_QSTR_OTG_FS_POWER), MP_ROM_PTR(&pin_PD05) }, + { MP_ROM_QSTR(MP_QSTR_OTG_FS_OVER_CURRENT), MP_ROM_PTR(&pin_PD04) }, + { MP_ROM_QSTR(MP_QSTR_OTG_HS_OVER_CURRENT), MP_ROM_PTR(&pin_PE03) }, + { MP_ROM_QSTR(MP_QSTR_USB_VBUS), MP_ROM_PTR(&pin_PJ12) }, + { MP_ROM_QSTR(MP_QSTR_USB_ID), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_USB_DM), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_USB_DP), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_VCP_TX), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_VCP_RX), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_CAN_TX), MP_ROM_PTR(&pin_PB13) }, + { MP_ROM_QSTR(MP_QSTR_CAN_RX), MP_ROM_PTR(&pin_PB12) }, + { MP_ROM_QSTR(MP_QSTR_ETH_MDC), MP_ROM_PTR(&pin_PC01) }, + { MP_ROM_QSTR(MP_QSTR_ETH_MDIO), MP_ROM_PTR(&pin_PA02) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_REF_CLK), MP_ROM_PTR(&pin_PA01) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_CRS_DV), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXD0), MP_ROM_PTR(&pin_PC04) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXD1), MP_ROM_PTR(&pin_PC05) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_RXER), MP_ROM_PTR(&pin_PG02) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_TX_EN), MP_ROM_PTR(&pin_PG11) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_TXD0), MP_ROM_PTR(&pin_PG13) }, + { MP_ROM_QSTR(MP_QSTR_ETH_RMII_TXD1), MP_ROM_PTR(&pin_PG14) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_SDCKE0), MP_ROM_PTR(&pin_PC03) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_SDNE0), MP_ROM_PTR(&pin_PH03) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_SDCLK), MP_ROM_PTR(&pin_PG08) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_SDNCAS), MP_ROM_PTR(&pin_PG15) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_SDNRAS), MP_ROM_PTR(&pin_PF11) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_SDNWE), MP_ROM_PTR(&pin_PH05) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_BA0), MP_ROM_PTR(&pin_PG04) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_BA1), MP_ROM_PTR(&pin_PG05) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_NBL0), MP_ROM_PTR(&pin_PE00) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_NBL1), MP_ROM_PTR(&pin_PE01) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A0), MP_ROM_PTR(&pin_PF00) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A1), MP_ROM_PTR(&pin_PF01) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A2), MP_ROM_PTR(&pin_PF02) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A3), MP_ROM_PTR(&pin_PF03) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A4), MP_ROM_PTR(&pin_PF04) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A5), MP_ROM_PTR(&pin_PF05) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A6), MP_ROM_PTR(&pin_PF12) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A7), MP_ROM_PTR(&pin_PF13) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A8), MP_ROM_PTR(&pin_PF14) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A9), MP_ROM_PTR(&pin_PF15) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A10), MP_ROM_PTR(&pin_PG00) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_A11), MP_ROM_PTR(&pin_PG01) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D0), MP_ROM_PTR(&pin_PD14) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D1), MP_ROM_PTR(&pin_PD15) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D2), MP_ROM_PTR(&pin_PD00) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D3), MP_ROM_PTR(&pin_PD01) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D4), MP_ROM_PTR(&pin_PE07) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D5), MP_ROM_PTR(&pin_PE08) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D6), MP_ROM_PTR(&pin_PE09) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D7), MP_ROM_PTR(&pin_PE10) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D8), MP_ROM_PTR(&pin_PE11) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D9), MP_ROM_PTR(&pin_PE12) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D10), MP_ROM_PTR(&pin_PE13) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D11), MP_ROM_PTR(&pin_PE14) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D12), MP_ROM_PTR(&pin_PE15) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D13), MP_ROM_PTR(&pin_PD08) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D14), MP_ROM_PTR(&pin_PD09) }, + { MP_ROM_QSTR(MP_QSTR_SDRAM_D15), MP_ROM_PTR(&pin_PD10) }, + { MP_ROM_QSTR(MP_QSTR_I2C3_SDA), MP_ROM_PTR(&pin_PH08) }, + { MP_ROM_QSTR(MP_QSTR_I2C3_SCL), MP_ROM_PTR(&pin_PH07) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/stm/boards/system_stm32f4xx.c b/ports/stm/boards/system_stm32f4xx.c index d8c745dbbd..39dc727053 100644 --- a/ports/stm/boards/system_stm32f4xx.c +++ b/ports/stm/boards/system_stm32f4xx.c @@ -89,11 +89,11 @@ #include "stm32f4xx.h" #include "py/mpconfig.h" -#if !defined (HSE_VALUE) +#if !defined(HSE_VALUE) #define HSE_VALUE ((uint32_t)25000000) /*!< Default value of the External oscillator in Hz */ #endif /* HSE_VALUE */ -#if !defined (HSI_VALUE) +#if !defined(HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ @@ -115,15 +115,15 @@ /************************* Miscellaneous Configuration ************************/ /*!< Uncomment the following line if you need to use external SRAM or SDRAM as data memory */ -#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\ - || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) +#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) \ + || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) \ + || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) /* #define DATA_IN_ExtSRAM */ #endif /* STM32F40xxx || STM32F41xxx || STM32F42xxx || STM32F43xxx || STM32F469xx || STM32F479xx ||\ STM32F412Zx || STM32F412Vx */ -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) \ + || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) /* #define DATA_IN_ExtSDRAM */ #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx ||\ STM32F479xx */ @@ -150,7 +150,7 @@ /** @addtogroup STM32F4xx_System_Private_Variables * @{ */ - /* This variable is updated in three ways: +/* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetHCLKFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency @@ -160,7 +160,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}; +const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; /** * @} */ @@ -169,8 +169,8 @@ const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; * @{ */ -#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) - static void SystemInit_ExtMemCtl(void); +#if defined(DATA_IN_ExtSRAM) || defined(DATA_IN_ExtSDRAM) +static void SystemInit_ExtMemCtl(void); #endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ /** @@ -188,43 +188,42 @@ const uint8_t APBPrescTable[8] = {0, 0, 0, 0, 1, 2, 3, 4}; * @param None * @retval None */ -void SystemInit(void) -{ - /* FPU settings ------------------------------------------------------------*/ - #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) - SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ - #endif - /* Reset the RCC clock configuration to the default reset state ------------*/ - /* Set HSION bit */ - RCC->CR |= (uint32_t)0x00000001; +void SystemInit(void) { + /* FPU settings ------------------------------------------------------------*/ + #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10 and CP11 Full Access */ + #endif + /* Reset the RCC clock configuration to the default reset state ------------*/ + /* Set HSION bit */ + RCC->CR |= (uint32_t)0x00000001; - /* Reset CFGR register */ - RCC->CFGR = 0x00000000; + /* Reset CFGR register */ + RCC->CFGR = 0x00000000; - /* Reset HSEON, CSSON and PLLON bits */ - RCC->CR &= (uint32_t)0xFEF6FFFF; + /* Reset HSEON, CSSON and PLLON bits */ + RCC->CR &= (uint32_t)0xFEF6FFFF; - /* Reset PLLCFGR register */ - RCC->PLLCFGR = 0x24003010; + /* Reset PLLCFGR register */ + RCC->PLLCFGR = 0x24003010; - /* Reset HSEBYP bit */ - RCC->CR &= (uint32_t)0xFFFBFFFF; + /* Reset HSEBYP bit */ + RCC->CR &= (uint32_t)0xFFFBFFFF; - /* Disable all interrupts */ - RCC->CIR = 0x00000000; + /* Disable all interrupts */ + RCC->CIR = 0x00000000; -#if defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) - SystemInit_ExtMemCtl(); -#endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ + #if defined(DATA_IN_ExtSRAM) || defined(DATA_IN_ExtSDRAM) + SystemInit_ExtMemCtl(); + #endif /* DATA_IN_ExtSRAM || DATA_IN_ExtSDRAM */ - /* Configure the Vector Table location add offset address ------------------*/ -#if !(BOARD_VTOR_DEFER) //only set VTOR if the bootloader hasn't already - #ifdef VECT_TAB_SRAM + /* Configure the Vector Table location add offset address ------------------*/ + #if !(BOARD_VTOR_DEFER) // only set VTOR if the bootloader hasn't already + #ifdef VECT_TAB_SRAM SCB->VTOR = SRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ - #else + #else SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ - #endif -#endif + #endif + #endif } /** @@ -263,57 +262,53 @@ void SystemInit(void) * @param None * @retval None */ -void SystemCoreClockUpdate(void) -{ - uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; +void SystemCoreClockUpdate(void) { + uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; - /* Get SYSCLK source -------------------------------------------------------*/ - tmp = RCC->CFGR & RCC_CFGR_SWS; + /* Get SYSCLK source -------------------------------------------------------*/ + tmp = RCC->CFGR & RCC_CFGR_SWS; - switch (tmp) - { - case 0x00: /* HSI used as system clock source */ - SystemCoreClock = HSI_VALUE; - break; - case 0x04: /* HSE used as system clock source */ - SystemCoreClock = HSE_VALUE; - break; - case 0x08: /* PLL used as system clock source */ + switch (tmp) + { + case 0x00: /* HSI used as system clock source */ + SystemCoreClock = HSI_VALUE; + break; + case 0x04: /* HSE used as system clock source */ + SystemCoreClock = HSE_VALUE; + break; + case 0x08: /* PLL used as system clock source */ - /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N - SYSCLK = PLL_VCO / PLL_P - */ - pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22; - pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; + /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N + SYSCLK = PLL_VCO / PLL_P + */ + pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22; + pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; - if (pllsource != 0) - { - /* HSE used as PLL clock source */ - pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); - } - else - { - /* HSI used as PLL clock source */ - pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); - } + if (pllsource != 0) { + /* HSE used as PLL clock source */ + pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); + } else { + /* HSI used as PLL clock source */ + pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); + } - pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2; - SystemCoreClock = pllvco/pllp; - break; - default: - SystemCoreClock = HSI_VALUE; - break; - } - /* Compute HCLK frequency --------------------------------------------------*/ - /* Get HCLK prescaler */ - tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; - /* HCLK frequency */ - SystemCoreClock >>= tmp; + pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >> 16) + 1) * 2; + SystemCoreClock = pllvco / pllp; + break; + default: + SystemCoreClock = HSI_VALUE; + break; + } + /* Compute HCLK frequency --------------------------------------------------*/ + /* Get HCLK prescaler */ + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; + /* HCLK frequency */ + SystemCoreClock >>= tmp; } -#if defined (DATA_IN_ExtSRAM) && defined (DATA_IN_ExtSDRAM) -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F469xx) || defined(STM32F479xx) +#if defined(DATA_IN_ExtSRAM) && defined(DATA_IN_ExtSDRAM) +#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) \ + || defined(STM32F469xx) || defined(STM32F479xx) /** * @brief Setup the external memory controller. * Called in startup_stm32f4xx.s before jump to main. @@ -322,161 +317,157 @@ void SystemCoreClockUpdate(void) * @param None * @retval None */ -void SystemInit_ExtMemCtl(void) -{ - __IO uint32_t tmp = 0x00; +void SystemInit_ExtMemCtl(void) { + __IO uint32_t tmp = 0x00; - register uint32_t tmpreg = 0, timeout = 0xFFFF; - register __IO uint32_t index; + register uint32_t tmpreg = 0, timeout = 0xFFFF; + register __IO uint32_t index; - /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */ - RCC->AHB1ENR |= 0x000001F8; + /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface clock */ + RCC->AHB1ENR |= 0x000001F8; - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); - /* Connect PDx pins to FMC Alternate function */ - GPIOD->AFR[0] = 0x00CCC0CC; - GPIOD->AFR[1] = 0xCCCCCCCC; - /* Configure PDx pins in Alternate function mode */ - GPIOD->MODER = 0xAAAA0A8A; - /* Configure PDx pins speed to 100 MHz */ - GPIOD->OSPEEDR = 0xFFFF0FCF; - /* Configure PDx pins Output type to push-pull */ - GPIOD->OTYPER = 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOD->PUPDR = 0x00000000; + /* Connect PDx pins to FMC Alternate function */ + GPIOD->AFR[0] = 0x00CCC0CC; + GPIOD->AFR[1] = 0xCCCCCCCC; + /* Configure PDx pins in Alternate function mode */ + GPIOD->MODER = 0xAAAA0A8A; + /* Configure PDx pins speed to 100 MHz */ + GPIOD->OSPEEDR = 0xFFFF0FCF; + /* Configure PDx pins Output type to push-pull */ + GPIOD->OTYPER = 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOD->PUPDR = 0x00000000; - /* Connect PEx pins to FMC Alternate function */ - GPIOE->AFR[0] = 0xC00CC0CC; - GPIOE->AFR[1] = 0xCCCCCCCC; - /* Configure PEx pins in Alternate function mode */ - GPIOE->MODER = 0xAAAA828A; - /* Configure PEx pins speed to 100 MHz */ - GPIOE->OSPEEDR = 0xFFFFC3CF; - /* Configure PEx pins Output type to push-pull */ - GPIOE->OTYPER = 0x00000000; - /* No pull-up, pull-down for PEx pins */ - GPIOE->PUPDR = 0x00000000; + /* Connect PEx pins to FMC Alternate function */ + GPIOE->AFR[0] = 0xC00CC0CC; + GPIOE->AFR[1] = 0xCCCCCCCC; + /* Configure PEx pins in Alternate function mode */ + GPIOE->MODER = 0xAAAA828A; + /* Configure PEx pins speed to 100 MHz */ + GPIOE->OSPEEDR = 0xFFFFC3CF; + /* Configure PEx pins Output type to push-pull */ + GPIOE->OTYPER = 0x00000000; + /* No pull-up, pull-down for PEx pins */ + GPIOE->PUPDR = 0x00000000; - /* Connect PFx pins to FMC Alternate function */ - GPIOF->AFR[0] = 0xCCCCCCCC; - GPIOF->AFR[1] = 0xCCCCCCCC; - /* Configure PFx pins in Alternate function mode */ - GPIOF->MODER = 0xAA800AAA; - /* Configure PFx pins speed to 50 MHz */ - GPIOF->OSPEEDR = 0xAA800AAA; - /* Configure PFx pins Output type to push-pull */ - GPIOF->OTYPER = 0x00000000; - /* No pull-up, pull-down for PFx pins */ - GPIOF->PUPDR = 0x00000000; + /* Connect PFx pins to FMC Alternate function */ + GPIOF->AFR[0] = 0xCCCCCCCC; + GPIOF->AFR[1] = 0xCCCCCCCC; + /* Configure PFx pins in Alternate function mode */ + GPIOF->MODER = 0xAA800AAA; + /* Configure PFx pins speed to 50 MHz */ + GPIOF->OSPEEDR = 0xAA800AAA; + /* Configure PFx pins Output type to push-pull */ + GPIOF->OTYPER = 0x00000000; + /* No pull-up, pull-down for PFx pins */ + GPIOF->PUPDR = 0x00000000; - /* Connect PGx pins to FMC Alternate function */ - GPIOG->AFR[0] = 0xCCCCCCCC; - GPIOG->AFR[1] = 0xCCCCCCCC; - /* Configure PGx pins in Alternate function mode */ - GPIOG->MODER = 0xAAAAAAAA; - /* Configure PGx pins speed to 50 MHz */ - GPIOG->OSPEEDR = 0xAAAAAAAA; - /* Configure PGx pins Output type to push-pull */ - GPIOG->OTYPER = 0x00000000; - /* No pull-up, pull-down for PGx pins */ - GPIOG->PUPDR = 0x00000000; + /* Connect PGx pins to FMC Alternate function */ + GPIOG->AFR[0] = 0xCCCCCCCC; + GPIOG->AFR[1] = 0xCCCCCCCC; + /* Configure PGx pins in Alternate function mode */ + GPIOG->MODER = 0xAAAAAAAA; + /* Configure PGx pins speed to 50 MHz */ + GPIOG->OSPEEDR = 0xAAAAAAAA; + /* Configure PGx pins Output type to push-pull */ + GPIOG->OTYPER = 0x00000000; + /* No pull-up, pull-down for PGx pins */ + GPIOG->PUPDR = 0x00000000; - /* Connect PHx pins to FMC Alternate function */ - GPIOH->AFR[0] = 0x00C0CC00; - GPIOH->AFR[1] = 0xCCCCCCCC; - /* Configure PHx pins in Alternate function mode */ - GPIOH->MODER = 0xAAAA08A0; - /* Configure PHx pins speed to 50 MHz */ - GPIOH->OSPEEDR = 0xAAAA08A0; - /* Configure PHx pins Output type to push-pull */ - GPIOH->OTYPER = 0x00000000; - /* No pull-up, pull-down for PHx pins */ - GPIOH->PUPDR = 0x00000000; + /* Connect PHx pins to FMC Alternate function */ + GPIOH->AFR[0] = 0x00C0CC00; + GPIOH->AFR[1] = 0xCCCCCCCC; + /* Configure PHx pins in Alternate function mode */ + GPIOH->MODER = 0xAAAA08A0; + /* Configure PHx pins speed to 50 MHz */ + GPIOH->OSPEEDR = 0xAAAA08A0; + /* Configure PHx pins Output type to push-pull */ + GPIOH->OTYPER = 0x00000000; + /* No pull-up, pull-down for PHx pins */ + GPIOH->PUPDR = 0x00000000; - /* Connect PIx pins to FMC Alternate function */ - GPIOI->AFR[0] = 0xCCCCCCCC; - GPIOI->AFR[1] = 0x00000CC0; - /* Configure PIx pins in Alternate function mode */ - GPIOI->MODER = 0x0028AAAA; - /* Configure PIx pins speed to 50 MHz */ - GPIOI->OSPEEDR = 0x0028AAAA; - /* Configure PIx pins Output type to push-pull */ - GPIOI->OTYPER = 0x00000000; - /* No pull-up, pull-down for PIx pins */ - GPIOI->PUPDR = 0x00000000; + /* Connect PIx pins to FMC Alternate function */ + GPIOI->AFR[0] = 0xCCCCCCCC; + GPIOI->AFR[1] = 0x00000CC0; + /* Configure PIx pins in Alternate function mode */ + GPIOI->MODER = 0x0028AAAA; + /* Configure PIx pins speed to 50 MHz */ + GPIOI->OSPEEDR = 0x0028AAAA; + /* Configure PIx pins Output type to push-pull */ + GPIOI->OTYPER = 0x00000000; + /* No pull-up, pull-down for PIx pins */ + GPIOI->PUPDR = 0x00000000; /*-- FMC Configuration -------------------------------------------------------*/ - /* Enable the FMC interface clock */ - RCC->AHB3ENR |= 0x00000001; - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); + /* Enable the FMC interface clock */ + RCC->AHB3ENR |= 0x00000001; + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); - FMC_Bank5_6->SDCR[0] = 0x000019E4; - FMC_Bank5_6->SDTR[0] = 0x01115351; + FMC_Bank5_6->SDCR[0] = 0x000019E4; + FMC_Bank5_6->SDTR[0] = 0x01115351; - /* SDRAM initialization sequence */ - /* Clock enable command */ - FMC_Bank5_6->SDCMR = 0x00000011; - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - while((tmpreg != 0) && (timeout-- > 0)) - { + /* SDRAM initialization sequence */ + /* Clock enable command */ + FMC_Bank5_6->SDCMR = 0x00000011; tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } - /* Delay */ - for (index = 0; index<1000; index++); + /* Delay */ + for (index = 0; index < 1000; index++) {; + } - /* PALL command */ - FMC_Bank5_6->SDCMR = 0x00000012; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } + /* PALL command */ + FMC_Bank5_6->SDCMR = 0x00000012; + timeout = 0xFFFF; + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } - /* Auto refresh command */ - FMC_Bank5_6->SDCMR = 0x00000073; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } + /* Auto refresh command */ + FMC_Bank5_6->SDCMR = 0x00000073; + timeout = 0xFFFF; + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } - /* MRD register program */ - FMC_Bank5_6->SDCMR = 0x00046014; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } + /* MRD register program */ + FMC_Bank5_6->SDCMR = 0x00046014; + timeout = 0xFFFF; + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } - /* Set refresh count */ - tmpreg = FMC_Bank5_6->SDRTR; - FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); + /* Set refresh count */ + tmpreg = FMC_Bank5_6->SDRTR; + FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C << 1)); - /* Disable write protection */ - tmpreg = FMC_Bank5_6->SDCR[0]; - FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); + /* Disable write protection */ + tmpreg = FMC_Bank5_6->SDCR[0]; + FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) - /* Configure and enable Bank1_SRAM2 */ - FMC_Bank1->BTCR[2] = 0x00001011; - FMC_Bank1->BTCR[3] = 0x00000201; - FMC_Bank1E->BWTR[2] = 0x0fffffff; -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ -#if defined(STM32F469xx) || defined(STM32F479xx) - /* Configure and enable Bank1_SRAM2 */ - FMC_Bank1->BTCR[2] = 0x00001091; - FMC_Bank1->BTCR[3] = 0x00110212; - FMC_Bank1E->BWTR[2] = 0x0fffffff; -#endif /* STM32F469xx || STM32F479xx */ + #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001011; + FMC_Bank1->BTCR[3] = 0x00000201; + FMC_Bank1E->BWTR[2] = 0x0fffffff; + #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ + #if defined(STM32F469xx) || defined(STM32F479xx) + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001091; + FMC_Bank1->BTCR[3] = 0x00110212; + FMC_Bank1E->BWTR[2] = 0x0fffffff; + #endif /* STM32F469xx || STM32F479xx */ - (void)(tmp); + (void)(tmp); } #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ -#elif defined (DATA_IN_ExtSRAM) || defined (DATA_IN_ExtSDRAM) +#elif defined(DATA_IN_ExtSRAM) || defined(DATA_IN_ExtSDRAM) /** * @brief Setup the external memory controller. * Called in startup_stm32f4xx.s before jump to main. @@ -485,293 +476,289 @@ void SystemInit_ExtMemCtl(void) * @param None * @retval None */ -void SystemInit_ExtMemCtl(void) -{ - __IO uint32_t tmp = 0x00; -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) -#if defined (DATA_IN_ExtSDRAM) - register uint32_t tmpreg = 0, timeout = 0xFFFF; - register __IO uint32_t index; +void SystemInit_ExtMemCtl(void) { + __IO uint32_t tmp = 0x00; + #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) \ + || defined(STM32F446xx) || defined(STM32F469xx) || defined(STM32F479xx) + #if defined(DATA_IN_ExtSDRAM) + register uint32_t tmpreg = 0, timeout = 0xFFFF; + register __IO uint32_t index; -#if defined(STM32F446xx) - /* Enable GPIOA, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG interface - clock */ - RCC->AHB1ENR |= 0x0000007D; -#else - /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface - clock */ - RCC->AHB1ENR |= 0x000001F8; -#endif /* STM32F446xx */ - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); + #if defined(STM32F446xx) + /* Enable GPIOA, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG interface + clock */ + RCC->AHB1ENR |= 0x0000007D; + #else + /* Enable GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH and GPIOI interface + clock */ + RCC->AHB1ENR |= 0x000001F8; + #endif /* STM32F446xx */ + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIOCEN); -#if defined(STM32F446xx) - /* Connect PAx pins to FMC Alternate function */ - GPIOA->AFR[0] |= 0xC0000000; - GPIOA->AFR[1] |= 0x00000000; - /* Configure PDx pins in Alternate function mode */ - GPIOA->MODER |= 0x00008000; - /* Configure PDx pins speed to 50 MHz */ - GPIOA->OSPEEDR |= 0x00008000; - /* Configure PDx pins Output type to push-pull */ - GPIOA->OTYPER |= 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOA->PUPDR |= 0x00000000; + #if defined(STM32F446xx) + /* Connect PAx pins to FMC Alternate function */ + GPIOA->AFR[0] |= 0xC0000000; + GPIOA->AFR[1] |= 0x00000000; + /* Configure PDx pins in Alternate function mode */ + GPIOA->MODER |= 0x00008000; + /* Configure PDx pins speed to 50 MHz */ + GPIOA->OSPEEDR |= 0x00008000; + /* Configure PDx pins Output type to push-pull */ + GPIOA->OTYPER |= 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOA->PUPDR |= 0x00000000; - /* Connect PCx pins to FMC Alternate function */ - GPIOC->AFR[0] |= 0x00CC0000; - GPIOC->AFR[1] |= 0x00000000; - /* Configure PDx pins in Alternate function mode */ - GPIOC->MODER |= 0x00000A00; - /* Configure PDx pins speed to 50 MHz */ - GPIOC->OSPEEDR |= 0x00000A00; - /* Configure PDx pins Output type to push-pull */ - GPIOC->OTYPER |= 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOC->PUPDR |= 0x00000000; -#endif /* STM32F446xx */ + /* Connect PCx pins to FMC Alternate function */ + GPIOC->AFR[0] |= 0x00CC0000; + GPIOC->AFR[1] |= 0x00000000; + /* Configure PDx pins in Alternate function mode */ + GPIOC->MODER |= 0x00000A00; + /* Configure PDx pins speed to 50 MHz */ + GPIOC->OSPEEDR |= 0x00000A00; + /* Configure PDx pins Output type to push-pull */ + GPIOC->OTYPER |= 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOC->PUPDR |= 0x00000000; + #endif /* STM32F446xx */ - /* Connect PDx pins to FMC Alternate function */ - GPIOD->AFR[0] = 0x000000CC; - GPIOD->AFR[1] = 0xCC000CCC; - /* Configure PDx pins in Alternate function mode */ - GPIOD->MODER = 0xA02A000A; - /* Configure PDx pins speed to 50 MHz */ - GPIOD->OSPEEDR = 0xA02A000A; - /* Configure PDx pins Output type to push-pull */ - GPIOD->OTYPER = 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOD->PUPDR = 0x00000000; + /* Connect PDx pins to FMC Alternate function */ + GPIOD->AFR[0] = 0x000000CC; + GPIOD->AFR[1] = 0xCC000CCC; + /* Configure PDx pins in Alternate function mode */ + GPIOD->MODER = 0xA02A000A; + /* Configure PDx pins speed to 50 MHz */ + GPIOD->OSPEEDR = 0xA02A000A; + /* Configure PDx pins Output type to push-pull */ + GPIOD->OTYPER = 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOD->PUPDR = 0x00000000; - /* Connect PEx pins to FMC Alternate function */ - GPIOE->AFR[0] = 0xC00000CC; - GPIOE->AFR[1] = 0xCCCCCCCC; - /* Configure PEx pins in Alternate function mode */ - GPIOE->MODER = 0xAAAA800A; - /* Configure PEx pins speed to 50 MHz */ - GPIOE->OSPEEDR = 0xAAAA800A; - /* Configure PEx pins Output type to push-pull */ - GPIOE->OTYPER = 0x00000000; - /* No pull-up, pull-down for PEx pins */ - GPIOE->PUPDR = 0x00000000; + /* Connect PEx pins to FMC Alternate function */ + GPIOE->AFR[0] = 0xC00000CC; + GPIOE->AFR[1] = 0xCCCCCCCC; + /* Configure PEx pins in Alternate function mode */ + GPIOE->MODER = 0xAAAA800A; + /* Configure PEx pins speed to 50 MHz */ + GPIOE->OSPEEDR = 0xAAAA800A; + /* Configure PEx pins Output type to push-pull */ + GPIOE->OTYPER = 0x00000000; + /* No pull-up, pull-down for PEx pins */ + GPIOE->PUPDR = 0x00000000; - /* Connect PFx pins to FMC Alternate function */ - GPIOF->AFR[0] = 0xCCCCCCCC; - GPIOF->AFR[1] = 0xCCCCCCCC; - /* Configure PFx pins in Alternate function mode */ - GPIOF->MODER = 0xAA800AAA; - /* Configure PFx pins speed to 50 MHz */ - GPIOF->OSPEEDR = 0xAA800AAA; - /* Configure PFx pins Output type to push-pull */ - GPIOF->OTYPER = 0x00000000; - /* No pull-up, pull-down for PFx pins */ - GPIOF->PUPDR = 0x00000000; + /* Connect PFx pins to FMC Alternate function */ + GPIOF->AFR[0] = 0xCCCCCCCC; + GPIOF->AFR[1] = 0xCCCCCCCC; + /* Configure PFx pins in Alternate function mode */ + GPIOF->MODER = 0xAA800AAA; + /* Configure PFx pins speed to 50 MHz */ + GPIOF->OSPEEDR = 0xAA800AAA; + /* Configure PFx pins Output type to push-pull */ + GPIOF->OTYPER = 0x00000000; + /* No pull-up, pull-down for PFx pins */ + GPIOF->PUPDR = 0x00000000; - /* Connect PGx pins to FMC Alternate function */ - GPIOG->AFR[0] = 0xCCCCCCCC; - GPIOG->AFR[1] = 0xCCCCCCCC; - /* Configure PGx pins in Alternate function mode */ - GPIOG->MODER = 0xAAAAAAAA; - /* Configure PGx pins speed to 50 MHz */ - GPIOG->OSPEEDR = 0xAAAAAAAA; - /* Configure PGx pins Output type to push-pull */ - GPIOG->OTYPER = 0x00000000; - /* No pull-up, pull-down for PGx pins */ - GPIOG->PUPDR = 0x00000000; + /* Connect PGx pins to FMC Alternate function */ + GPIOG->AFR[0] = 0xCCCCCCCC; + GPIOG->AFR[1] = 0xCCCCCCCC; + /* Configure PGx pins in Alternate function mode */ + GPIOG->MODER = 0xAAAAAAAA; + /* Configure PGx pins speed to 50 MHz */ + GPIOG->OSPEEDR = 0xAAAAAAAA; + /* Configure PGx pins Output type to push-pull */ + GPIOG->OTYPER = 0x00000000; + /* No pull-up, pull-down for PGx pins */ + GPIOG->PUPDR = 0x00000000; -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F469xx) || defined(STM32F479xx) - /* Connect PHx pins to FMC Alternate function */ - GPIOH->AFR[0] = 0x00C0CC00; - GPIOH->AFR[1] = 0xCCCCCCCC; - /* Configure PHx pins in Alternate function mode */ - GPIOH->MODER = 0xAAAA08A0; - /* Configure PHx pins speed to 50 MHz */ - GPIOH->OSPEEDR = 0xAAAA08A0; - /* Configure PHx pins Output type to push-pull */ - GPIOH->OTYPER = 0x00000000; - /* No pull-up, pull-down for PHx pins */ - GPIOH->PUPDR = 0x00000000; + #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) \ + || defined(STM32F469xx) || defined(STM32F479xx) + /* Connect PHx pins to FMC Alternate function */ + GPIOH->AFR[0] = 0x00C0CC00; + GPIOH->AFR[1] = 0xCCCCCCCC; + /* Configure PHx pins in Alternate function mode */ + GPIOH->MODER = 0xAAAA08A0; + /* Configure PHx pins speed to 50 MHz */ + GPIOH->OSPEEDR = 0xAAAA08A0; + /* Configure PHx pins Output type to push-pull */ + GPIOH->OTYPER = 0x00000000; + /* No pull-up, pull-down for PHx pins */ + GPIOH->PUPDR = 0x00000000; - /* Connect PIx pins to FMC Alternate function */ - GPIOI->AFR[0] = 0xCCCCCCCC; - GPIOI->AFR[1] = 0x00000CC0; - /* Configure PIx pins in Alternate function mode */ - GPIOI->MODER = 0x0028AAAA; - /* Configure PIx pins speed to 50 MHz */ - GPIOI->OSPEEDR = 0x0028AAAA; - /* Configure PIx pins Output type to push-pull */ - GPIOI->OTYPER = 0x00000000; - /* No pull-up, pull-down for PIx pins */ - GPIOI->PUPDR = 0x00000000; -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ + /* Connect PIx pins to FMC Alternate function */ + GPIOI->AFR[0] = 0xCCCCCCCC; + GPIOI->AFR[1] = 0x00000CC0; + /* Configure PIx pins in Alternate function mode */ + GPIOI->MODER = 0x0028AAAA; + /* Configure PIx pins speed to 50 MHz */ + GPIOI->OSPEEDR = 0x0028AAAA; + /* Configure PIx pins Output type to push-pull */ + GPIOI->OTYPER = 0x00000000; + /* No pull-up, pull-down for PIx pins */ + GPIOI->PUPDR = 0x00000000; + #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx */ /*-- FMC Configuration -------------------------------------------------------*/ - /* Enable the FMC interface clock */ - RCC->AHB3ENR |= 0x00000001; - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); + /* Enable the FMC interface clock */ + RCC->AHB3ENR |= 0x00000001; + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); - /* Configure and enable SDRAM bank1 */ -#if defined(STM32F446xx) - FMC_Bank5_6->SDCR[0] = 0x00001954; -#else - FMC_Bank5_6->SDCR[0] = 0x000019E4; -#endif /* STM32F446xx */ - FMC_Bank5_6->SDTR[0] = 0x01115351; + /* Configure and enable SDRAM bank1 */ + #if defined(STM32F446xx) + FMC_Bank5_6->SDCR[0] = 0x00001954; + #else + FMC_Bank5_6->SDCR[0] = 0x000019E4; + #endif /* STM32F446xx */ + FMC_Bank5_6->SDTR[0] = 0x01115351; - /* SDRAM initialization sequence */ - /* Clock enable command */ - FMC_Bank5_6->SDCMR = 0x00000011; - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - while((tmpreg != 0) && (timeout-- > 0)) - { + /* SDRAM initialization sequence */ + /* Clock enable command */ + FMC_Bank5_6->SDCMR = 0x00000011; tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } - /* Delay */ - for (index = 0; index<1000; index++); + /* Delay */ + for (index = 0; index < 1000; index++) {; + } - /* PALL command */ - FMC_Bank5_6->SDCMR = 0x00000012; - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } + /* PALL command */ + FMC_Bank5_6->SDCMR = 0x00000012; + timeout = 0xFFFF; + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } - /* Auto refresh command */ -#if defined(STM32F446xx) - FMC_Bank5_6->SDCMR = 0x000000F3; -#else - FMC_Bank5_6->SDCMR = 0x00000073; -#endif /* STM32F446xx */ - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } + /* Auto refresh command */ + #if defined(STM32F446xx) + FMC_Bank5_6->SDCMR = 0x000000F3; + #else + FMC_Bank5_6->SDCMR = 0x00000073; + #endif /* STM32F446xx */ + timeout = 0xFFFF; + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } - /* MRD register program */ -#if defined(STM32F446xx) - FMC_Bank5_6->SDCMR = 0x00044014; -#else - FMC_Bank5_6->SDCMR = 0x00046014; -#endif /* STM32F446xx */ - timeout = 0xFFFF; - while((tmpreg != 0) && (timeout-- > 0)) - { - tmpreg = FMC_Bank5_6->SDSR & 0x00000020; - } + /* MRD register program */ + #if defined(STM32F446xx) + FMC_Bank5_6->SDCMR = 0x00044014; + #else + FMC_Bank5_6->SDCMR = 0x00046014; + #endif /* STM32F446xx */ + timeout = 0xFFFF; + while ((tmpreg != 0) && (timeout-- > 0)) { + tmpreg = FMC_Bank5_6->SDSR & 0x00000020; + } - /* Set refresh count */ - tmpreg = FMC_Bank5_6->SDRTR; -#if defined(STM32F446xx) - FMC_Bank5_6->SDRTR = (tmpreg | (0x0000050C<<1)); -#else - FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C<<1)); -#endif /* STM32F446xx */ + /* Set refresh count */ + tmpreg = FMC_Bank5_6->SDRTR; + #if defined(STM32F446xx) + FMC_Bank5_6->SDRTR = (tmpreg | (0x0000050C << 1)); + #else + FMC_Bank5_6->SDRTR = (tmpreg | (0x0000027C << 1)); + #endif /* STM32F446xx */ - /* Disable write protection */ - tmpreg = FMC_Bank5_6->SDCR[0]; - FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); -#endif /* DATA_IN_ExtSDRAM */ -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ + /* Disable write protection */ + tmpreg = FMC_Bank5_6->SDCR[0]; + FMC_Bank5_6->SDCR[0] = (tmpreg & 0xFFFFFDFF); + #endif /* DATA_IN_ExtSDRAM */ + #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx || STM32F446xx || STM32F469xx || STM32F479xx */ -#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx)\ - || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx)\ - || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) + #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) \ + || defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) \ + || defined(STM32F469xx) || defined(STM32F479xx) || defined(STM32F412Zx) || defined(STM32F412Vx) -#if defined(DATA_IN_ExtSRAM) + #if defined(DATA_IN_ExtSRAM) /*-- GPIOs Configuration -----------------------------------------------------*/ - /* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */ - RCC->AHB1ENR |= 0x00000078; - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN); + /* Enable GPIOD, GPIOE, GPIOF and GPIOG interface clock */ + RCC->AHB1ENR |= 0x00000078; + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB1ENR, RCC_AHB1ENR_GPIODEN); - /* Connect PDx pins to FMC Alternate function */ - GPIOD->AFR[0] = 0x00CCC0CC; - GPIOD->AFR[1] = 0xCCCCCCCC; - /* Configure PDx pins in Alternate function mode */ - GPIOD->MODER = 0xAAAA0A8A; - /* Configure PDx pins speed to 100 MHz */ - GPIOD->OSPEEDR = 0xFFFF0FCF; - /* Configure PDx pins Output type to push-pull */ - GPIOD->OTYPER = 0x00000000; - /* No pull-up, pull-down for PDx pins */ - GPIOD->PUPDR = 0x00000000; + /* Connect PDx pins to FMC Alternate function */ + GPIOD->AFR[0] = 0x00CCC0CC; + GPIOD->AFR[1] = 0xCCCCCCCC; + /* Configure PDx pins in Alternate function mode */ + GPIOD->MODER = 0xAAAA0A8A; + /* Configure PDx pins speed to 100 MHz */ + GPIOD->OSPEEDR = 0xFFFF0FCF; + /* Configure PDx pins Output type to push-pull */ + GPIOD->OTYPER = 0x00000000; + /* No pull-up, pull-down for PDx pins */ + GPIOD->PUPDR = 0x00000000; - /* Connect PEx pins to FMC Alternate function */ - GPIOE->AFR[0] = 0xC00CC0CC; - GPIOE->AFR[1] = 0xCCCCCCCC; - /* Configure PEx pins in Alternate function mode */ - GPIOE->MODER = 0xAAAA828A; - /* Configure PEx pins speed to 100 MHz */ - GPIOE->OSPEEDR = 0xFFFFC3CF; - /* Configure PEx pins Output type to push-pull */ - GPIOE->OTYPER = 0x00000000; - /* No pull-up, pull-down for PEx pins */ - GPIOE->PUPDR = 0x00000000; + /* Connect PEx pins to FMC Alternate function */ + GPIOE->AFR[0] = 0xC00CC0CC; + GPIOE->AFR[1] = 0xCCCCCCCC; + /* Configure PEx pins in Alternate function mode */ + GPIOE->MODER = 0xAAAA828A; + /* Configure PEx pins speed to 100 MHz */ + GPIOE->OSPEEDR = 0xFFFFC3CF; + /* Configure PEx pins Output type to push-pull */ + GPIOE->OTYPER = 0x00000000; + /* No pull-up, pull-down for PEx pins */ + GPIOE->PUPDR = 0x00000000; - /* Connect PFx pins to FMC Alternate function */ - GPIOF->AFR[0] = 0x00CCCCCC; - GPIOF->AFR[1] = 0xCCCC0000; - /* Configure PFx pins in Alternate function mode */ - GPIOF->MODER = 0xAA000AAA; - /* Configure PFx pins speed to 100 MHz */ - GPIOF->OSPEEDR = 0xFF000FFF; - /* Configure PFx pins Output type to push-pull */ - GPIOF->OTYPER = 0x00000000; - /* No pull-up, pull-down for PFx pins */ - GPIOF->PUPDR = 0x00000000; + /* Connect PFx pins to FMC Alternate function */ + GPIOF->AFR[0] = 0x00CCCCCC; + GPIOF->AFR[1] = 0xCCCC0000; + /* Configure PFx pins in Alternate function mode */ + GPIOF->MODER = 0xAA000AAA; + /* Configure PFx pins speed to 100 MHz */ + GPIOF->OSPEEDR = 0xFF000FFF; + /* Configure PFx pins Output type to push-pull */ + GPIOF->OTYPER = 0x00000000; + /* No pull-up, pull-down for PFx pins */ + GPIOF->PUPDR = 0x00000000; - /* Connect PGx pins to FMC Alternate function */ - GPIOG->AFR[0] = 0x00CCCCCC; - GPIOG->AFR[1] = 0x000000C0; - /* Configure PGx pins in Alternate function mode */ - GPIOG->MODER = 0x00085AAA; - /* Configure PGx pins speed to 100 MHz */ - GPIOG->OSPEEDR = 0x000CAFFF; - /* Configure PGx pins Output type to push-pull */ - GPIOG->OTYPER = 0x00000000; - /* No pull-up, pull-down for PGx pins */ - GPIOG->PUPDR = 0x00000000; + /* Connect PGx pins to FMC Alternate function */ + GPIOG->AFR[0] = 0x00CCCCCC; + GPIOG->AFR[1] = 0x000000C0; + /* Configure PGx pins in Alternate function mode */ + GPIOG->MODER = 0x00085AAA; + /* Configure PGx pins speed to 100 MHz */ + GPIOG->OSPEEDR = 0x000CAFFF; + /* Configure PGx pins Output type to push-pull */ + GPIOG->OTYPER = 0x00000000; + /* No pull-up, pull-down for PGx pins */ + GPIOG->PUPDR = 0x00000000; /*-- FMC/FSMC Configuration --------------------------------------------------*/ - /* Enable the FMC/FSMC interface clock */ - RCC->AHB3ENR |= 0x00000001; + /* Enable the FMC/FSMC interface clock */ + RCC->AHB3ENR |= 0x00000001; -#if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); - /* Configure and enable Bank1_SRAM2 */ - FMC_Bank1->BTCR[2] = 0x00001011; - FMC_Bank1->BTCR[3] = 0x00000201; - FMC_Bank1E->BWTR[2] = 0x0fffffff; -#endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ -#if defined(STM32F469xx) || defined(STM32F479xx) - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); - /* Configure and enable Bank1_SRAM2 */ - FMC_Bank1->BTCR[2] = 0x00001091; - FMC_Bank1->BTCR[3] = 0x00110212; - FMC_Bank1E->BWTR[2] = 0x0fffffff; -#endif /* STM32F469xx || STM32F479xx */ -#if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx)|| defined(STM32F417xx)\ - || defined(STM32F412Zx) || defined(STM32F412Vx) - /* Delay after an RCC peripheral clock enabling */ - tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN); - /* Configure and enable Bank1_SRAM2 */ - FSMC_Bank1->BTCR[2] = 0x00001011; - FSMC_Bank1->BTCR[3] = 0x00000201; - FSMC_Bank1E->BWTR[2] = 0x0FFFFFFF; -#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F412Zx || STM32F412Vx */ + #if defined(STM32F427xx) || defined(STM32F437xx) || defined(STM32F429xx) || defined(STM32F439xx) + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001011; + FMC_Bank1->BTCR[3] = 0x00000201; + FMC_Bank1E->BWTR[2] = 0x0fffffff; + #endif /* STM32F427xx || STM32F437xx || STM32F429xx || STM32F439xx */ + #if defined(STM32F469xx) || defined(STM32F479xx) + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FMCEN); + /* Configure and enable Bank1_SRAM2 */ + FMC_Bank1->BTCR[2] = 0x00001091; + FMC_Bank1->BTCR[3] = 0x00110212; + FMC_Bank1E->BWTR[2] = 0x0fffffff; + #endif /* STM32F469xx || STM32F479xx */ + #if defined(STM32F405xx) || defined(STM32F415xx) || defined(STM32F407xx) || defined(STM32F417xx) \ + || defined(STM32F412Zx) || defined(STM32F412Vx) + /* Delay after an RCC peripheral clock enabling */ + tmp = READ_BIT(RCC->AHB3ENR, RCC_AHB3ENR_FSMCEN); + /* Configure and enable Bank1_SRAM2 */ + FSMC_Bank1->BTCR[2] = 0x00001011; + FSMC_Bank1->BTCR[3] = 0x00000201; + FSMC_Bank1E->BWTR[2] = 0x0FFFFFFF; + #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F412Zx || STM32F412Vx */ -#endif /* DATA_IN_ExtSRAM */ -#endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ + #endif /* DATA_IN_ExtSRAM */ + #endif /* STM32F405xx || STM32F415xx || STM32F407xx || STM32F417xx || STM32F427xx || STM32F437xx ||\ STM32F429xx || STM32F439xx || STM32F469xx || STM32F479xx || STM32F412Zx || STM32F412Vx */ - (void)(tmp); + (void)(tmp); } #endif /* DATA_IN_ExtSRAM && DATA_IN_ExtSDRAM */ /** diff --git a/ports/stm/boards/system_stm32f7xx.c b/ports/stm/boards/system_stm32f7xx.c index 4aebc3d357..450283ae55 100644 --- a/ports/stm/boards/system_stm32f7xx.c +++ b/ports/stm/boards/system_stm32f7xx.c @@ -47,11 +47,11 @@ #include "stm32f7xx.h" -#if !defined (HSE_VALUE) +#if !defined(HSE_VALUE) #define HSE_VALUE ((uint32_t)25000000) /*!< Default value of the External oscillator in Hz */ #endif /* HSE_VALUE */ -#if !defined (HSI_VALUE) +#if !defined(HSI_VALUE) #define HSI_VALUE ((uint32_t)16000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ @@ -96,7 +96,7 @@ * @{ */ - /* This variable is updated in three ways: +/* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetHCLKFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency @@ -104,9 +104,9 @@ is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ - 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}; +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}; /** * @} @@ -131,21 +131,20 @@ * @param None * @retval None */ -void SystemInit(void) -{ - /* FPU settings ------------------------------------------------------------*/ -#if (__FPU_PRESENT == 1) && (__FPU_USED == 1) - SCB->CPACR |= ((3UL << 10*2)|(3UL << 11*2)); /* set CP10 and CP11 Full Access */ -#endif - - /* Configure the Vector Table location add offset address ------------------*/ -#if !(BOARD_VTOR_DEFER) //only set VTOR if the bootloader hasn't already - #ifdef VECT_TAB_SRAM - SCB->VTOR = RAMDTCM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ - #else - SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ +void SystemInit(void) { + /* FPU settings ------------------------------------------------------------*/ + #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << 10 * 2) | (3UL << 11 * 2)); /* set CP10 and CP11 Full Access */ + #endif + + /* Configure the Vector Table location add offset address ------------------*/ + #if !(BOARD_VTOR_DEFER) // only set VTOR if the bootloader hasn't already + #ifdef VECT_TAB_SRAM + SCB->VTOR = RAMDTCM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ + #else + SCB->VTOR = FLASH_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ + #endif #endif -#endif } @@ -185,52 +184,48 @@ void SystemInit(void) * @param None * @retval None */ -void SystemCoreClockUpdate(void) -{ - uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; +void SystemCoreClockUpdate(void) { + uint32_t tmp = 0, pllvco = 0, pllp = 2, pllsource = 0, pllm = 2; - /* Get SYSCLK source -------------------------------------------------------*/ - tmp = RCC->CFGR & RCC_CFGR_SWS; + /* Get SYSCLK source -------------------------------------------------------*/ + tmp = RCC->CFGR & RCC_CFGR_SWS; - switch (tmp) - { - case 0x00: /* HSI used as system clock source */ - SystemCoreClock = HSI_VALUE; - break; - case 0x04: /* HSE used as system clock source */ - SystemCoreClock = HSE_VALUE; - break; - case 0x08: /* PLL used as system clock source */ + switch (tmp) + { + case 0x00: /* HSI used as system clock source */ + SystemCoreClock = HSI_VALUE; + break; + case 0x04: /* HSE used as system clock source */ + SystemCoreClock = HSE_VALUE; + break; + case 0x08: /* PLL used as system clock source */ - /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N - SYSCLK = PLL_VCO / PLL_P - */ - pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22; - pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; + /* PLL_VCO = (HSE_VALUE or HSI_VALUE / PLL_M) * PLL_N + SYSCLK = PLL_VCO / PLL_P + */ + pllsource = (RCC->PLLCFGR & RCC_PLLCFGR_PLLSRC) >> 22; + pllm = RCC->PLLCFGR & RCC_PLLCFGR_PLLM; - if (pllsource != 0) - { - /* HSE used as PLL clock source */ - pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); - } - else - { - /* HSI used as PLL clock source */ - pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); - } + if (pllsource != 0) { + /* HSE used as PLL clock source */ + pllvco = (HSE_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); + } else { + /* HSI used as PLL clock source */ + pllvco = (HSI_VALUE / pllm) * ((RCC->PLLCFGR & RCC_PLLCFGR_PLLN) >> 6); + } - pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >>16) + 1 ) *2; - SystemCoreClock = pllvco/pllp; - break; - default: - SystemCoreClock = HSI_VALUE; - break; - } - /* Compute HCLK frequency --------------------------------------------------*/ - /* Get HCLK prescaler */ - tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; - /* HCLK frequency */ - SystemCoreClock >>= tmp; + pllp = (((RCC->PLLCFGR & RCC_PLLCFGR_PLLP) >> 16) + 1) * 2; + SystemCoreClock = pllvco / pllp; + break; + default: + SystemCoreClock = HSI_VALUE; + break; + } + /* Compute HCLK frequency --------------------------------------------------*/ + /* Get HCLK prescaler */ + tmp = AHBPrescTable[((RCC->CFGR & RCC_CFGR_HPRE) >> 4)]; + /* HCLK frequency */ + SystemCoreClock >>= tmp; } /** diff --git a/ports/stm/boards/system_stm32h7xx.c b/ports/stm/boards/system_stm32h7xx.c index bbb0f821fb..8b782e4960 100644 --- a/ports/stm/boards/system_stm32h7xx.c +++ b/ports/stm/boards/system_stm32h7xx.c @@ -71,15 +71,15 @@ #include "stm32h7xx.h" #include -#if !defined (HSE_VALUE) +#if !defined(HSE_VALUE) #define HSE_VALUE ((uint32_t)25000000) /*!< Value of the External oscillator in Hz */ #endif /* HSE_VALUE */ -#if !defined (CSI_VALUE) +#if !defined(CSI_VALUE) #define CSI_VALUE ((uint32_t)4000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* CSI_VALUE */ -#if !defined (HSI_VALUE) +#if !defined(HSI_VALUE) #define HSI_VALUE ((uint32_t)64000000) /*!< Value of the Internal oscillator in Hz*/ #endif /* HSI_VALUE */ @@ -126,7 +126,7 @@ /** @addtogroup STM32H7xx_System_Private_Variables * @{ */ - /* This variable is updated in three ways: +/* This variable is updated in three ways: 1) by calling CMSIS function SystemCoreClockUpdate() 2) by calling HAL API function HAL_RCC_GetHCLKFreq() 3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency @@ -134,9 +134,9 @@ is no need to call the 2 first functions listed above, since SystemCoreClock variable is updated automatically. */ - uint32_t SystemCoreClock = 64000000; - uint32_t SystemD2Clock = 64000000; - const uint8_t D1CorePrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, 8, 9}; +uint32_t SystemCoreClock = 64000000; +uint32_t SystemD2Clock = 64000000; +const uint8_t D1CorePrescTable[16] = {0, 0, 0, 0, 1, 2, 3, 4, 1, 2, 3, 4, 6, 7, 8, 9}; /** * @} @@ -161,117 +161,115 @@ * @param None * @retval None */ -void SystemInit (void) -{ -#if defined (DATA_IN_D2_SRAM) - __IO uint32_t tmpreg; -#endif /* DATA_IN_D2_SRAM */ +void SystemInit(void) { + #if defined(DATA_IN_D2_SRAM) + __IO uint32_t tmpreg; + #endif /* DATA_IN_D2_SRAM */ - /* FPU settings ------------------------------------------------------------*/ - #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) - SCB->CPACR |= ((3UL << (10*2))|(3UL << (11*2))); /* set CP10 and CP11 Full Access */ - #endif - /* Reset the RCC clock configuration to the default reset state ------------*/ - /* Set HSION bit */ - RCC->CR |= RCC_CR_HSION; - - /* Reset CFGR register */ - RCC->CFGR = 0x00000000; - - /* Reset HSEON, CSSON , CSION,RC48ON, CSIKERON PLL1ON, PLL2ON and PLL3ON bits */ - RCC->CR &= 0xEAF6ED7FU; - -#if defined(D3_SRAM_BASE) - /* Reset D1CFGR register */ - RCC->D1CFGR = 0x00000000; - - /* Reset D2CFGR register */ - RCC->D2CFGR = 0x00000000; - - /* Reset D3CFGR register */ - RCC->D3CFGR = 0x00000000; -#else - /* Reset CDCFGR1 register */ - RCC->CDCFGR1 = 0x00000000; - - /* Reset CDCFGR2 register */ - RCC->CDCFGR2 = 0x00000000; - - /* Reset SRDCFGR register */ - RCC->SRDCFGR = 0x00000000; -#endif - /* Reset PLLCKSELR register */ - RCC->PLLCKSELR = 0x00000000; - - /* Reset PLLCFGR register */ - RCC->PLLCFGR = 0x00000000; - /* Reset PLL1DIVR register */ - RCC->PLL1DIVR = 0x00000000; - /* Reset PLL1FRACR register */ - RCC->PLL1FRACR = 0x00000000; - - /* Reset PLL2DIVR register */ - RCC->PLL2DIVR = 0x00000000; - - /* Reset PLL2FRACR register */ - - RCC->PLL2FRACR = 0x00000000; - /* Reset PLL3DIVR register */ - RCC->PLL3DIVR = 0x00000000; - - /* Reset PLL3FRACR register */ - RCC->PLL3FRACR = 0x00000000; - - /* Reset HSEBYP bit */ - RCC->CR &= 0xFFFBFFFFU; - - /* Disable all interrupts */ - RCC->CIER = 0x00000000; - -#if (STM32H7_DEV_ID == 0x450UL) - /* dual core CM7 or single core line */ - if((DBGMCU->IDCODE & 0xFFFF0000U) < 0x20000000U) - { - /* if stm32h7 revY*/ - /* Change the switch matrix read issuing capability to 1 for the AXI SRAM target (Target 7) */ - *((__IO uint32_t*)0x51008108) = 0x000000001U; - } -#endif - -#if defined (DATA_IN_D2_SRAM) - /* in case of initialized data in D2 SRAM (AHB SRAM) , enable the D2 SRAM clock (AHB SRAM clock) */ -#if defined(RCC_AHB2ENR_D2SRAM3EN) - RCC->AHB2ENR |= (RCC_AHB2ENR_D2SRAM1EN | RCC_AHB2ENR_D2SRAM2EN | RCC_AHB2ENR_D2SRAM3EN); -#elif defined(RCC_AHB2ENR_D2SRAM2EN) - RCC->AHB2ENR |= (RCC_AHB2ENR_D2SRAM1EN | RCC_AHB2ENR_D2SRAM2EN); -#else - RCC->AHB2ENR |= (RCC_AHB2ENR_AHBSRAM1EN | RCC_AHB2ENR_AHBSRAM2EN); -#endif /* RCC_AHB2ENR_D2SRAM3EN */ - - tmpreg = RCC->AHB2ENR; - (void) tmpreg; -#endif /* DATA_IN_D2_SRAM */ - -#if defined(DUAL_CORE) && defined(CORE_CM4) - /* Configure the Vector Table location add offset address for cortex-M4 ------------------*/ -#ifdef VECT_TAB_SRAM - SCB->VTOR = D2_AHBSRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ -#else - SCB->VTOR = FLASH_BANK2_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ -#endif /* VECT_TAB_SRAM */ - -#else - - /* Configure the Vector Table location add offset address for cortex-M7 ------------------*/ -#if !(BOARD_VTOR_DEFER) //only set VTOR if the bootloader hasn't already - #ifdef VECT_TAB_SRAM - SCB->VTOR = D1_AXISRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal AXI-RAM */ - #else - SCB->VTOR = FLASH_BANK1_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ + /* FPU settings ------------------------------------------------------------*/ + #if (__FPU_PRESENT == 1) && (__FPU_USED == 1) + SCB->CPACR |= ((3UL << (10 * 2)) | (3UL << (11 * 2))); /* set CP10 and CP11 Full Access */ #endif -#endif + /* Reset the RCC clock configuration to the default reset state ------------*/ + /* Set HSION bit */ + RCC->CR |= RCC_CR_HSION; -#endif /*DUAL_CORE && CORE_CM4*/ + /* Reset CFGR register */ + RCC->CFGR = 0x00000000; + + /* Reset HSEON, CSSON , CSION,RC48ON, CSIKERON PLL1ON, PLL2ON and PLL3ON bits */ + RCC->CR &= 0xEAF6ED7FU; + + #if defined(D3_SRAM_BASE) + /* Reset D1CFGR register */ + RCC->D1CFGR = 0x00000000; + + /* Reset D2CFGR register */ + RCC->D2CFGR = 0x00000000; + + /* Reset D3CFGR register */ + RCC->D3CFGR = 0x00000000; + #else + /* Reset CDCFGR1 register */ + RCC->CDCFGR1 = 0x00000000; + + /* Reset CDCFGR2 register */ + RCC->CDCFGR2 = 0x00000000; + + /* Reset SRDCFGR register */ + RCC->SRDCFGR = 0x00000000; + #endif + /* Reset PLLCKSELR register */ + RCC->PLLCKSELR = 0x00000000; + + /* Reset PLLCFGR register */ + RCC->PLLCFGR = 0x00000000; + /* Reset PLL1DIVR register */ + RCC->PLL1DIVR = 0x00000000; + /* Reset PLL1FRACR register */ + RCC->PLL1FRACR = 0x00000000; + + /* Reset PLL2DIVR register */ + RCC->PLL2DIVR = 0x00000000; + + /* Reset PLL2FRACR register */ + + RCC->PLL2FRACR = 0x00000000; + /* Reset PLL3DIVR register */ + RCC->PLL3DIVR = 0x00000000; + + /* Reset PLL3FRACR register */ + RCC->PLL3FRACR = 0x00000000; + + /* Reset HSEBYP bit */ + RCC->CR &= 0xFFFBFFFFU; + + /* Disable all interrupts */ + RCC->CIER = 0x00000000; + + #if (STM32H7_DEV_ID == 0x450UL) + /* dual core CM7 or single core line */ + if ((DBGMCU->IDCODE & 0xFFFF0000U) < 0x20000000U) { + /* if stm32h7 revY*/ + /* Change the switch matrix read issuing capability to 1 for the AXI SRAM target (Target 7) */ + *((__IO uint32_t *)0x51008108) = 0x000000001U; + } + #endif + + #if defined(DATA_IN_D2_SRAM) + /* in case of initialized data in D2 SRAM (AHB SRAM) , enable the D2 SRAM clock (AHB SRAM clock) */ + #if defined(RCC_AHB2ENR_D2SRAM3EN) + RCC->AHB2ENR |= (RCC_AHB2ENR_D2SRAM1EN | RCC_AHB2ENR_D2SRAM2EN | RCC_AHB2ENR_D2SRAM3EN); + #elif defined(RCC_AHB2ENR_D2SRAM2EN) + RCC->AHB2ENR |= (RCC_AHB2ENR_D2SRAM1EN | RCC_AHB2ENR_D2SRAM2EN); + #else + RCC->AHB2ENR |= (RCC_AHB2ENR_AHBSRAM1EN | RCC_AHB2ENR_AHBSRAM2EN); + #endif /* RCC_AHB2ENR_D2SRAM3EN */ + + tmpreg = RCC->AHB2ENR; + (void)tmpreg; + #endif /* DATA_IN_D2_SRAM */ + + #if defined(DUAL_CORE) && defined(CORE_CM4) + /* Configure the Vector Table location add offset address for cortex-M4 ------------------*/ + #ifdef VECT_TAB_SRAM + SCB->VTOR = D2_AHBSRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal SRAM */ + #else + SCB->VTOR = FLASH_BANK2_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ + #endif /* VECT_TAB_SRAM */ + + #else + + /* Configure the Vector Table location add offset address for cortex-M7 ------------------*/ + #if !(BOARD_VTOR_DEFER) // only set VTOR if the bootloader hasn't already + #ifdef VECT_TAB_SRAM + SCB->VTOR = D1_AXISRAM_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal AXI-RAM */ + #else + SCB->VTOR = FLASH_BANK1_BASE | VECT_TAB_OFFSET; /* Vector Table Relocation in Internal FLASH */ + #endif + #endif + + #endif /*DUAL_CORE && CORE_CM4*/ } @@ -312,102 +310,98 @@ void SystemInit (void) * @param None * @retval None */ -void SystemCoreClockUpdate (void) -{ - uint32_t pllp, pllsource, pllm, pllfracen, hsivalue, tmp; - uint32_t common_system_clock; - float_t fracn1, pllvco; +void SystemCoreClockUpdate(void) { + uint32_t pllp, pllsource, pllm, pllfracen, hsivalue, tmp; + uint32_t common_system_clock; + float_t fracn1, pllvco; - /* Get SYSCLK source -------------------------------------------------------*/ + /* Get SYSCLK source -------------------------------------------------------*/ - switch (RCC->CFGR & RCC_CFGR_SWS) - { - case RCC_CFGR_SWS_HSI: /* HSI used as system clock source */ - common_system_clock = (uint32_t) (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV)>> 3)); - break; - - case RCC_CFGR_SWS_CSI: /* CSI used as system clock source */ - common_system_clock = CSI_VALUE; - break; - - case RCC_CFGR_SWS_HSE: /* HSE used as system clock source */ - common_system_clock = HSE_VALUE; - break; - - case RCC_CFGR_SWS_PLL1: /* PLL1 used as system clock source */ - - /* PLL_VCO = (HSE_VALUE or HSI_VALUE or CSI_VALUE/ PLLM) * PLLN - SYSCLK = PLL_VCO / PLLR - */ - pllsource = (RCC->PLLCKSELR & RCC_PLLCKSELR_PLLSRC); - pllm = ((RCC->PLLCKSELR & RCC_PLLCKSELR_DIVM1)>> 4) ; - pllfracen = ((RCC->PLLCFGR & RCC_PLLCFGR_PLL1FRACEN)>>RCC_PLLCFGR_PLL1FRACEN_Pos); - fracn1 = (float_t)(uint32_t)(pllfracen* ((RCC->PLL1FRACR & RCC_PLL1FRACR_FRACN1)>> 3)); - - if (pllm != 0U) + switch (RCC->CFGR & RCC_CFGR_SWS) { - switch (pllsource) - { - case RCC_PLLCKSELR_PLLSRC_HSI: /* HSI used as PLL clock source */ + case RCC_CFGR_SWS_HSI: /* HSI used as system clock source */ + common_system_clock = (uint32_t)(HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV) >> 3)); + break; - hsivalue = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV)>> 3)) ; - pllvco = ( (float_t)hsivalue / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_N1) + (fracn1/(float_t)0x2000) +(float_t)1 ); + case RCC_CFGR_SWS_CSI: /* CSI used as system clock source */ + common_system_clock = CSI_VALUE; + break; - break; + case RCC_CFGR_SWS_HSE: /* HSE used as system clock source */ + common_system_clock = HSE_VALUE; + break; - case RCC_PLLCKSELR_PLLSRC_CSI: /* CSI used as PLL clock source */ - pllvco = ((float_t)CSI_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_N1) + (fracn1/(float_t)0x2000) +(float_t)1 ); - break; + case RCC_CFGR_SWS_PLL1: /* PLL1 used as system clock source */ - case RCC_PLLCKSELR_PLLSRC_HSE: /* HSE used as PLL clock source */ - pllvco = ((float_t)HSE_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_N1) + (fracn1/(float_t)0x2000) +(float_t)1 ); - break; + /* PLL_VCO = (HSE_VALUE or HSI_VALUE or CSI_VALUE/ PLLM) * PLLN + SYSCLK = PLL_VCO / PLLR + */ + pllsource = (RCC->PLLCKSELR & RCC_PLLCKSELR_PLLSRC); + pllm = ((RCC->PLLCKSELR & RCC_PLLCKSELR_DIVM1) >> 4); + pllfracen = ((RCC->PLLCFGR & RCC_PLLCFGR_PLL1FRACEN) >> RCC_PLLCFGR_PLL1FRACEN_Pos); + fracn1 = (float_t)(uint32_t)(pllfracen * ((RCC->PLL1FRACR & RCC_PLL1FRACR_FRACN1) >> 3)); - default: - pllvco = ((float_t)CSI_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_N1) + (fracn1/(float_t)0x2000) +(float_t)1 ); - break; - } - pllp = (((RCC->PLL1DIVR & RCC_PLL1DIVR_P1) >>9) + 1U ) ; - common_system_clock = (uint32_t)(float_t)(pllvco/(float_t)pllp); + if (pllm != 0U) { + switch (pllsource) + { + case RCC_PLLCKSELR_PLLSRC_HSI: /* HSI used as PLL clock source */ + + hsivalue = (HSI_VALUE >> ((RCC->CR & RCC_CR_HSIDIV) >> 3)); + pllvco = ((float_t)hsivalue / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_N1) + (fracn1 / (float_t)0x2000) + (float_t)1); + + break; + + case RCC_PLLCKSELR_PLLSRC_CSI: /* CSI used as PLL clock source */ + pllvco = ((float_t)CSI_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_N1) + (fracn1 / (float_t)0x2000) + (float_t)1); + break; + + case RCC_PLLCKSELR_PLLSRC_HSE: /* HSE used as PLL clock source */ + pllvco = ((float_t)HSE_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_N1) + (fracn1 / (float_t)0x2000) + (float_t)1); + break; + + default: + pllvco = ((float_t)CSI_VALUE / (float_t)pllm) * ((float_t)(uint32_t)(RCC->PLL1DIVR & RCC_PLL1DIVR_N1) + (fracn1 / (float_t)0x2000) + (float_t)1); + break; + } + pllp = (((RCC->PLL1DIVR & RCC_PLL1DIVR_P1) >> 9) + 1U); + common_system_clock = (uint32_t)(float_t)(pllvco / (float_t)pllp); + } else { + common_system_clock = 0U; + } + break; + + default: + common_system_clock = CSI_VALUE; + break; } - else - { - common_system_clock = 0U; - } - break; - default: - common_system_clock = CSI_VALUE; - break; - } + /* Compute SystemClock frequency --------------------------------------------------*/ + #if defined(RCC_D1CFGR_D1CPRE) + tmp = D1CorePrescTable[(RCC->D1CFGR & RCC_D1CFGR_D1CPRE) >> RCC_D1CFGR_D1CPRE_Pos]; - /* Compute SystemClock frequency --------------------------------------------------*/ -#if defined (RCC_D1CFGR_D1CPRE) - tmp = D1CorePrescTable[(RCC->D1CFGR & RCC_D1CFGR_D1CPRE)>> RCC_D1CFGR_D1CPRE_Pos]; + /* common_system_clock frequency : CM7 CPU frequency */ + common_system_clock >>= tmp; - /* common_system_clock frequency : CM7 CPU frequency */ - common_system_clock >>= tmp; + /* SystemD2Clock frequency : CM4 CPU, AXI and AHBs Clock frequency */ + SystemD2Clock = (common_system_clock >> ((D1CorePrescTable[(RCC->D1CFGR & RCC_D1CFGR_HPRE) >> RCC_D1CFGR_HPRE_Pos]) & 0x1FU)); - /* SystemD2Clock frequency : CM4 CPU, AXI and AHBs Clock frequency */ - SystemD2Clock = (common_system_clock >> ((D1CorePrescTable[(RCC->D1CFGR & RCC_D1CFGR_HPRE)>> RCC_D1CFGR_HPRE_Pos]) & 0x1FU)); + #else + tmp = D1CorePrescTable[(RCC->CDCFGR1 & RCC_CDCFGR1_CDCPRE) >> RCC_CDCFGR1_CDCPRE_Pos]; -#else - tmp = D1CorePrescTable[(RCC->CDCFGR1 & RCC_CDCFGR1_CDCPRE)>> RCC_CDCFGR1_CDCPRE_Pos]; + /* common_system_clock frequency : CM7 CPU frequency */ + common_system_clock >>= tmp; - /* common_system_clock frequency : CM7 CPU frequency */ - common_system_clock >>= tmp; + /* SystemD2Clock frequency : AXI and AHBs Clock frequency */ + SystemD2Clock = (common_system_clock >> ((D1CorePrescTable[(RCC->CDCFGR1 & RCC_CDCFGR1_HPRE) >> RCC_CDCFGR1_HPRE_Pos]) & 0x1FU)); - /* SystemD2Clock frequency : AXI and AHBs Clock frequency */ - SystemD2Clock = (common_system_clock >> ((D1CorePrescTable[(RCC->CDCFGR1 & RCC_CDCFGR1_HPRE)>> RCC_CDCFGR1_HPRE_Pos]) & 0x1FU)); + #endif -#endif - -#if defined(DUAL_CORE) && defined(CORE_CM4) - SystemCoreClock = SystemD2Clock; -#else - SystemCoreClock = common_system_clock; -#endif /* DUAL_CORE && CORE_CM4 */ + #if defined(DUAL_CORE) && defined(CORE_CM4) + SystemCoreClock = SystemD2Clock; + #else + SystemCoreClock = common_system_clock; + #endif /* DUAL_CORE && CORE_CM4 */ } diff --git a/ports/stm/boards/thunderpack_v11/board.c b/ports/stm/boards/thunderpack_v11/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/thunderpack_v11/board.c +++ b/ports/stm/boards/thunderpack_v11/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/thunderpack_v11/mpconfigboard.h b/ports/stm/boards/thunderpack_v11/mpconfigboard.h index 7d4a8dff32..9c3c116e51 100644 --- a/ports/stm/boards/thunderpack_v11/mpconfigboard.h +++ b/ports/stm/boards/thunderpack_v11/mpconfigboard.h @@ -38,7 +38,7 @@ // Flash config #define FLASH_SIZE (0x80000) #define FLASH_PAGE_SIZE (0x4000) -#define BOARD_FLASH_SIZE (FLASH_SIZE - CIRCUITPY_INTERNAL_NVM_SIZE- 0x2000 - 0xC000) +#define BOARD_FLASH_SIZE (FLASH_SIZE - CIRCUITPY_INTERNAL_NVM_SIZE - 0x2000 - 0xC000) #define HSE_VALUE ((uint32_t)24000000U) #define BOARD_OVERWRITE_SWD (1) diff --git a/ports/stm/boards/thunderpack_v12/board.c b/ports/stm/boards/thunderpack_v12/board.c index 7817933281..688cfb4ded 100644 --- a/ports/stm/boards/thunderpack_v12/board.c +++ b/ports/stm/boards/thunderpack_v12/board.c @@ -30,7 +30,7 @@ void board_init(void) { } bool board_requests_safe_mode(void) { - return false; + return false; } void reset_board(void) { diff --git a/ports/stm/boards/thunderpack_v12/mpconfigboard.h b/ports/stm/boards/thunderpack_v12/mpconfigboard.h index fb5f389a37..34a5795ff1 100644 --- a/ports/stm/boards/thunderpack_v12/mpconfigboard.h +++ b/ports/stm/boards/thunderpack_v12/mpconfigboard.h @@ -35,7 +35,7 @@ // Flash config #define FLASH_SIZE (0x80000) #define FLASH_PAGE_SIZE (0x4000) -#define BOARD_FLASH_SIZE (FLASH_SIZE - CIRCUITPY_INTERNAL_NVM_SIZE- 0x2000 - 0xC000) +#define BOARD_FLASH_SIZE (FLASH_SIZE - CIRCUITPY_INTERNAL_NVM_SIZE - 0x2000 - 0xC000) #define INTERNAL_FLASH_FILESYSTEM_SIZE 0x8000 // On-board flash diff --git a/ports/stm/common-hal/analogio/AnalogIn.c b/ports/stm/common-hal/analogio/AnalogIn.c index 588d687ee1..35010ac7c5 100644 --- a/ports/stm/common-hal/analogio/AnalogIn.c +++ b/ports/stm/common-hal/analogio/AnalogIn.c @@ -36,8 +36,8 @@ #include "stm32f4xx_ll_adc.h" #include "stm32f4xx_ll_bus.h" -void common_hal_analogio_analogin_construct(analogio_analogin_obj_t* self, - const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, + const mcu_pin_obj_t *pin) { // No ADC function on pin if (pin->adc_unit == 0x00) { @@ -76,9 +76,9 @@ void common_hal_analogio_analogin_deinit(analogio_analogin_obj_t *self) { uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { // Something else might have used the ADC in a different way, // so we completely re-initialize it. - ADC_TypeDef * ADCx; + ADC_TypeDef *ADCx; - if(self->pin->adc_unit & 0x01) { + if (self->pin->adc_unit & 0x01) { ADCx = ADC1; } else if (self->pin->adc_unit == 0x04) { #ifdef ADC3 @@ -89,9 +89,9 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { } LL_GPIO_SetPinMode(pin_port(self->pin->port), (uint32_t)pin_mask(self->pin->number), LL_GPIO_MODE_ANALOG); - //LL_GPIO_PIN_0 + // LL_GPIO_PIN_0 - //HAL Implementation + // HAL Implementation ADC_HandleTypeDef AdcHandle; ADC_ChannelConfTypeDef sConfig; @@ -110,9 +110,9 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { AdcHandle.Init.EOCSelection = ADC_EOC_SINGLE_CONV; HAL_ADC_Init(&AdcHandle); - sConfig.Channel = (uint32_t)self->pin->adc_channel; //ADC_CHANNEL_0 <-normal iteration, not mask + sConfig.Channel = (uint32_t)self->pin->adc_channel; // ADC_CHANNEL_0 <-normal iteration, not mask sConfig.Rank = 1; - sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES; //Taken from micropython + sConfig.SamplingTime = ADC_SAMPLETIME_15CYCLES; // Taken from micropython HAL_ADC_ConfigChannel(&AdcHandle, &sConfig); HAL_ADC_Start(&AdcHandle); diff --git a/ports/stm/common-hal/analogio/AnalogIn.h b/ports/stm/common-hal/analogio/AnalogIn.h index 910092897e..c8e3e0868d 100644 --- a/ports/stm/common-hal/analogio/AnalogIn.h +++ b/ports/stm/common-hal/analogio/AnalogIn.h @@ -34,7 +34,7 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t * pin; + const mcu_pin_obj_t *pin; } analogio_analogin_obj_t; static inline uint8_t stm32_adc_units(uint8_t adc_packed) { diff --git a/ports/stm/common-hal/analogio/AnalogOut.c b/ports/stm/common-hal/analogio/AnalogOut.c index 69c1f3e045..1a3817a35d 100644 --- a/ports/stm/common-hal/analogio/AnalogOut.c +++ b/ports/stm/common-hal/analogio/AnalogOut.c @@ -39,15 +39,15 @@ #include "stm32f4xx_hal.h" -//DAC is shared between both channels. +// DAC is shared between both channels. #if HAS_DAC DAC_HandleTypeDef handle; #endif STATIC bool dac_on[2]; -void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, - const mcu_pin_obj_t *pin) { +void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, + const mcu_pin_obj_t *pin) { #if !(HAS_DAC) mp_raise_ValueError(translate("No DAC on chip")); #else @@ -61,17 +61,16 @@ void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, mp_raise_ValueError(translate("Invalid DAC pin supplied")); } - //Only init if the shared DAC is empty or reset + // Only init if the shared DAC is empty or reset if (handle.Instance == NULL || handle.State == HAL_DAC_STATE_RESET) { __HAL_RCC_DAC_CLK_ENABLE(); handle.Instance = DAC; - if (HAL_DAC_Init(&handle) != HAL_OK) - { + if (HAL_DAC_Init(&handle) != HAL_OK) { mp_raise_ValueError(translate("DAC Device Init Error")); } } - //init channel specific pin + // init channel specific pin GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitStruct.Pin = pin_mask(pin->number); GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; @@ -100,8 +99,8 @@ void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { self->pin = NULL; dac_on[self->dac_index] = false; - //turn off the DAC if both channels are off - if(dac_on[0] == false && dac_on[1] == false) { + // turn off the DAC if both channels are off + if (dac_on[0] == false && dac_on[1] == false) { __HAL_RCC_DAC_CLK_DISABLE(); HAL_DAC_DeInit(&handle); } @@ -109,7 +108,7 @@ void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { } void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, - uint16_t value) { + uint16_t value) { #if HAS_DAC HAL_DAC_SetValue(&handle, self->channel, DAC_ALIGN_12B_R, value >> 4); HAL_DAC_Start(&handle, self->channel); diff --git a/ports/stm/common-hal/analogio/AnalogOut.h b/ports/stm/common-hal/analogio/AnalogOut.h index 46312b4609..3c208a6118 100644 --- a/ports/stm/common-hal/analogio/AnalogOut.h +++ b/ports/stm/common-hal/analogio/AnalogOut.h @@ -36,12 +36,12 @@ typedef struct { mp_obj_base_t base; -#if HAS_DAC + #if HAS_DAC DAC_ChannelConfTypeDef ch_handle; -#endif - const mcu_pin_obj_t * pin; + #endif + const mcu_pin_obj_t *pin; uint8_t channel; - uint8_t dac_index:1; + uint8_t dac_index : 1; } analogio_analogout_obj_t; void analogout_reset(void); diff --git a/ports/stm/common-hal/busio/I2C.c b/ports/stm/common-hal/busio/I2C.c index 7726b5e87f..db6d86c342 100644 --- a/ports/stm/common-hal/busio/I2C.c +++ b/ports/stm/common-hal/busio/I2C.c @@ -61,11 +61,11 @@ STATIC bool never_reset_i2c[MAX_I2C]; #define ALL_CLOCKS 0xFF STATIC void i2c_clock_enable(uint8_t mask); STATIC void i2c_clock_disable(uint8_t mask); -STATIC void i2c_assign_irq(busio_i2c_obj_t *self, I2C_TypeDef * I2Cx); +STATIC void i2c_assign_irq(busio_i2c_obj_t *self, I2C_TypeDef *I2Cx); void i2c_reset(void) { uint16_t never_reset_mask = 0x00; - for(int i = 0; i < MAX_I2C; i++) { + for (int i = 0; i < MAX_I2C; i++) { if (!never_reset_i2c[i]) { reserved_i2c[i] = false; } else { @@ -76,10 +76,10 @@ void i2c_reset(void) { } void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, - const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, uint32_t frequency, uint32_t timeout) { + const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint32_t frequency, uint32_t timeout) { // Match pins to I2C objects - I2C_TypeDef * I2Cx; + I2C_TypeDef *I2Cx; uint8_t sda_len = MP_ARRAY_SIZE(mcu_i2c_sda_list); uint8_t scl_len = MP_ARRAY_SIZE(mcu_i2c_scl_list); bool i2c_taken = false; @@ -107,7 +107,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, } // Handle typedef selection, errors - if (self->sda != NULL && self->scl != NULL ) { + if (self->sda != NULL && self->scl != NULL) { I2Cx = mcu_i2c_banks[self->sda->periph_index - 1]; } else { if (i2c_taken) { @@ -171,8 +171,8 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, self->frame_in_prog = false; - //start the receive interrupt chain - HAL_NVIC_DisableIRQ(self->irq); //prevent handle lock contention + // start the receive interrupt chain + HAL_NVIC_DisableIRQ(self->irq); // prevent handle lock contention HAL_NVIC_SetPriority(self->irq, 1, 0); HAL_NVIC_EnableIRQ(self->irq); } @@ -215,15 +215,15 @@ bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { bool grabbed_lock = false; - //Critical section code that may be required at some point. + // Critical section code that may be required at some point. // uint32_t store_primask = __get_PRIMASK(); // __disable_irq(); // __DMB(); - if (!self->has_lock) { - grabbed_lock = true; - self->has_lock = true; - } + if (!self->has_lock) { + grabbed_lock = true; + self->has_lock = true; + } // __DMB(); // __set_PRIMASK(store_primask); @@ -240,7 +240,7 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { } uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, - const uint8_t *data, size_t len, bool transmit_stop_bit) { + const uint8_t *data, size_t len, bool transmit_stop_bit) { HAL_StatusTypeDef result; if (!transmit_stop_bit) { uint32_t xfer_opt; @@ -251,31 +251,29 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, xfer_opt = I2C_NEXT_FRAME; } result = HAL_I2C_Master_Seq_Transmit_IT(&(self->handle), - (uint16_t)(addr << 1), (uint8_t *)data, - (uint16_t)len, xfer_opt); - while (HAL_I2C_GetState(&(self->handle)) != HAL_I2C_STATE_READY) - { + (uint16_t)(addr << 1), (uint8_t *)data, + (uint16_t)len, xfer_opt); + while (HAL_I2C_GetState(&(self->handle)) != HAL_I2C_STATE_READY) { RUN_BACKGROUND_TASKS; } self->frame_in_prog = true; } else { result = HAL_I2C_Master_Transmit(&(self->handle), (uint16_t)(addr << 1), - (uint8_t *)data, (uint16_t)len, 500); + (uint8_t *)data, (uint16_t)len, 500); } return result == HAL_OK ? 0 : MP_EIO; } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *data, size_t len) { + uint8_t *data, size_t len) { if (!self->frame_in_prog) { - return HAL_I2C_Master_Receive(&(self->handle), (uint16_t)(addr<<1), data, (uint16_t)len, 500) - == HAL_OK ? 0 : MP_EIO; + return HAL_I2C_Master_Receive(&(self->handle), (uint16_t)(addr << 1), data, (uint16_t)len, 500) + == HAL_OK ? 0 : MP_EIO; } else { HAL_StatusTypeDef result = HAL_I2C_Master_Seq_Receive_IT(&(self->handle), - (uint16_t)(addr << 1), (uint8_t *)data, - (uint16_t)len, I2C_LAST_FRAME); - while (HAL_I2C_GetState(&(self->handle)) != HAL_I2C_STATE_READY) - { + (uint16_t)(addr << 1), (uint8_t *)data, + (uint16_t)len, I2C_LAST_FRAME); + while (HAL_I2C_GetState(&(self->handle)) != HAL_I2C_STATE_READY) { RUN_BACKGROUND_TASKS; } self->frame_in_prog = false; @@ -338,7 +336,7 @@ STATIC void i2c_clock_disable(uint8_t mask) { #endif } -STATIC void i2c_assign_irq(busio_i2c_obj_t *self, I2C_TypeDef * I2Cx) { +STATIC void i2c_assign_irq(busio_i2c_obj_t *self, I2C_TypeDef *I2Cx) { #ifdef I2C1 if (I2Cx == I2C1) { self->irq = I2C1_EV_IRQn; @@ -362,8 +360,8 @@ STATIC void i2c_assign_irq(busio_i2c_obj_t *self, I2C_TypeDef * I2Cx) { } STATIC void call_hal_irq(int i2c_num) { - //Create casted context pointer - busio_i2c_obj_t * context = (busio_i2c_obj_t*)MP_STATE_PORT(cpy_i2c_obj_all)[i2c_num - 1]; + // Create casted context pointer + busio_i2c_obj_t *context = (busio_i2c_obj_t *)MP_STATE_PORT(cpy_i2c_obj_all)[i2c_num - 1]; if (context != NULL) { HAL_NVIC_ClearPendingIRQ(context->irq); HAL_I2C_EV_IRQHandler(&context->handle); diff --git a/ports/stm/common-hal/busio/SPI.c b/ports/stm/common-hal/busio/SPI.c index 20ee0f6e15..2f26a01cba 100644 --- a/ports/stm/common-hal/busio/SPI.c +++ b/ports/stm/common-hal/busio/SPI.c @@ -39,7 +39,7 @@ // Note that any bugs introduced in this file can cause crashes at startup // for chips using external SPI flash. -//arrays use 0 based numbering: SPI1 is stored at index 0 +// arrays use 0 based numbering: SPI1 is stored at index 0 #define MAX_SPI 6 STATIC bool reserved_spi[MAX_SPI]; @@ -49,28 +49,32 @@ STATIC bool never_reset_spi[MAX_SPI]; STATIC void spi_clock_enable(uint8_t mask); STATIC void spi_clock_disable(uint8_t mask); -STATIC uint32_t get_busclock(SPI_TypeDef * instance) { +STATIC uint32_t get_busclock(SPI_TypeDef *instance) { #if (CPY_STM32H7) - if (instance == SPI1 || instance == SPI2 || instance == SPI3) { - return HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI123); - } else if (instance == SPI4 || instance == SPI5) { - return HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI45); - } else { - return HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI6); - } + if (instance == SPI1 || instance == SPI2 || instance == SPI3) { + return HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI123); + } else if (instance == SPI4 || instance == SPI5) { + return HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI45); + } else { + return HAL_RCCEx_GetPeriphCLKFreq(RCC_PERIPHCLK_SPI6); + } #elif (CPY_STM32F4 || CPY_STM32F7) - //SPI2 and 3 are on PCLK1, if they exist. - #ifdef SPI2 - if (instance == SPI2) return HAL_RCC_GetPCLK1Freq(); - #endif - #ifdef SPI3 - if (instance == SPI3) return HAL_RCC_GetPCLK1Freq(); - #endif - return HAL_RCC_GetPCLK2Freq(); + // SPI2 and 3 are on PCLK1, if they exist. + #ifdef SPI2 + if (instance == SPI2) { + return HAL_RCC_GetPCLK1Freq(); + } + #endif + #ifdef SPI3 + if (instance == SPI3) { + return HAL_RCC_GetPCLK1Freq(); + } + #endif + return HAL_RCC_GetPCLK2Freq(); #endif } -STATIC uint32_t stm32_baud_to_spi_div(uint32_t baudrate, uint16_t * prescaler, uint32_t busclock) { +STATIC uint32_t stm32_baud_to_spi_div(uint32_t baudrate, uint16_t *prescaler, uint32_t busclock) { static const uint32_t baud_map[8][2] = { {2,SPI_BAUDRATEPRESCALER_2}, {4,SPI_BAUDRATEPRESCALER_4}, @@ -85,13 +89,13 @@ STATIC uint32_t stm32_baud_to_spi_div(uint32_t baudrate, uint16_t * prescaler, u uint16_t divisor; do { divisor = baud_map[i][0]; - if (baudrate >= (busclock/divisor)) { + if (baudrate >= (busclock / divisor)) { *prescaler = divisor; return baud_map[i][1]; } i++; } while (divisor != 256); - //only gets here if requested baud is lower than minimum + // only gets here if requested baud is lower than minimum *prescaler = 256; return SPI_BAUDRATEPRESCALER_256; } @@ -109,18 +113,18 @@ void spi_reset(void) { } STATIC const mcu_periph_obj_t *find_pin_function(const mcu_periph_obj_t *table, size_t sz, const mcu_pin_obj_t *pin, int periph_index) { - for(size_t i = 0; iperiph_index && pin == table->pin ) { + for (size_t i = 0; i < sz; i++, table++) { + if (periph_index == table->periph_index && pin == table->pin) { return table; } } return NULL; } -//match pins to SPI objects +// match pins to SPI objects STATIC int check_pins(busio_spi_obj_t *self, - const mcu_pin_obj_t * sck, const mcu_pin_obj_t * mosi, - const mcu_pin_obj_t * miso) { + const mcu_pin_obj_t *sck, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso) { bool spi_taken = false; uint8_t sck_len = MP_ARRAY_SIZE(mcu_spi_sck_list); @@ -146,7 +150,7 @@ STATIC int check_pins(busio_spi_obj_t *self, continue; } - if (reserved_spi[periph_index-1]) { + if (reserved_spi[periph_index - 1]) { spi_taken = true; continue; } @@ -166,13 +170,13 @@ STATIC int check_pins(busio_spi_obj_t *self, } void common_hal_busio_spi_construct(busio_spi_obj_t *self, - const mcu_pin_obj_t * sck, const mcu_pin_obj_t * mosi, - const mcu_pin_obj_t * miso) { + const mcu_pin_obj_t *sck, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso) { int periph_index = check_pins(self, sck, mosi, miso); - SPI_TypeDef * SPIx = mcu_spi_banks[periph_index - 1]; + SPI_TypeDef *SPIx = mcu_spi_banks[periph_index - 1]; - //Start GPIO for each pin + // Start GPIO for each pin GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitStruct.Pin = pin_mask(sck->number); GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -215,8 +219,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, self->handle.Init.TIMode = SPI_TIMODE_DISABLE; self->handle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; self->handle.Init.CRCPolynomial = 10; - if (HAL_SPI_Init(&self->handle) != HAL_OK) - { + if (HAL_SPI_Init(&self->handle) != HAL_OK) { mp_raise_ValueError(translate("SPI Init Error")); } self->baudrate = (get_busclock(SPIx) / 16); @@ -254,7 +257,7 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { if (common_hal_busio_spi_deinited(self)) { return; } - spi_clock_disable(1<<(self->sck->periph_index - 1)); + spi_clock_disable(1 << (self->sck->periph_index - 1)); reserved_spi[self->sck->periph_index - 1] = false; never_reset_spi[self->sck->periph_index - 1] = false; @@ -271,14 +274,14 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, - uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { - //This resets the SPI, so check before updating it redundantly - if (baudrate == self->baudrate && polarity== self->polarity + uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { + // This resets the SPI, so check before updating it redundantly + if (baudrate == self->baudrate && polarity == self->polarity && phase == self->phase && bits == self->bits) { return true; } - //Deinit SPI + // Deinit SPI HAL_SPI_DeInit(&self->handle); self->handle.Init.DataSize = (bits == 16) ? SPI_DATASIZE_16BIT : SPI_DATASIZE_8BIT; @@ -286,10 +289,9 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, self->handle.Init.CLKPhase = (phase) ? SPI_PHASE_2EDGE : SPI_PHASE_1EDGE; self->handle.Init.BaudRatePrescaler = stm32_baud_to_spi_div(baudrate, &self->prescaler, - get_busclock(self->handle.Instance)); + get_busclock(self->handle.Instance)); - if (HAL_SPI_Init(&self->handle) != HAL_OK) - { + if (HAL_SPI_Init(&self->handle) != HAL_OK) { mp_raise_ValueError(translate("SPI Re-initialization error")); } @@ -303,7 +305,7 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { bool grabbed_lock = false; - //Critical section code that may be required at some point. + // Critical section code that may be required at some point. // uint32_t store_primask = __get_PRIMASK(); // __disable_irq(); // __DMB(); @@ -328,7 +330,7 @@ void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { } bool common_hal_busio_spi_write(busio_spi_obj_t *self, - const uint8_t *data, size_t len) { + const uint8_t *data, size_t len) { if (self->mosi == NULL) { mp_raise_ValueError(translate("No MOSI Pin")); } @@ -337,7 +339,7 @@ bool common_hal_busio_spi_write(busio_spi_obj_t *self, } bool common_hal_busio_spi_read(busio_spi_obj_t *self, - uint8_t *data, size_t len, uint8_t write_value) { + uint8_t *data, size_t len, uint8_t write_value) { if (self->miso == NULL) { mp_raise_ValueError(translate("No MISO Pin")); } @@ -352,26 +354,26 @@ bool common_hal_busio_spi_read(busio_spi_obj_t *self, } bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, - const uint8_t *data_out, uint8_t *data_in, size_t len) { + const uint8_t *data_out, uint8_t *data_in, size_t len) { if (self->miso == NULL || self->mosi == NULL) { mp_raise_ValueError(translate("Missing MISO or MOSI Pin")); } HAL_StatusTypeDef result = HAL_SPI_TransmitReceive(&self->handle, - (uint8_t *) data_out, data_in, (uint16_t)len,HAL_MAX_DELAY); + (uint8_t *)data_out, data_in, (uint16_t)len,HAL_MAX_DELAY); return result == HAL_OK; } -uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self) { - //returns actual frequency - uint32_t result = HAL_RCC_GetPCLK2Freq()/self->prescaler; +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { + // returns actual frequency + uint32_t result = HAL_RCC_GetPCLK2Freq() / self->prescaler; return result; } -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { return self->phase; } -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t* self) { +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { return self->polarity; } diff --git a/ports/stm/common-hal/busio/UART.c b/ports/stm/common-hal/busio/UART.c index b4794a31b3..ecaee84d3f 100644 --- a/ports/stm/common-hal/busio/UART.c +++ b/ports/stm/common-hal/busio/UART.c @@ -39,19 +39,19 @@ #define ALL_UARTS 0xFFFF -//arrays use 0 based numbering: UART1 is stored at index 0 +// arrays use 0 based numbering: UART1 is stored at index 0 STATIC bool reserved_uart[MAX_UART]; STATIC bool never_reset_uart[MAX_UART]; -int errflag; //Used to restart read halts +int errflag; // Used to restart read halts STATIC void uart_clock_enable(uint16_t mask); STATIC void uart_clock_disable(uint16_t mask); -STATIC void uart_assign_irq(busio_uart_obj_t* self, USART_TypeDef* USARTx); +STATIC void uart_assign_irq(busio_uart_obj_t *self, USART_TypeDef *USARTx); -STATIC USART_TypeDef * assign_uart_or_throw(busio_uart_obj_t* self, bool pin_eval, - int periph_index, bool uart_taken) { +STATIC USART_TypeDef *assign_uart_or_throw(busio_uart_obj_t *self, bool pin_eval, + int periph_index, bool uart_taken) { if (pin_eval) { - //assign a root pointer pointer for IRQ + // assign a root pointer pointer for IRQ MP_STATE_PORT(cpy_uart_obj_all)[periph_index] = self; return mcu_uart_banks[periph_index]; } else { @@ -77,40 +77,40 @@ void uart_reset(void) { } void common_hal_busio_uart_construct(busio_uart_obj_t *self, - const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, - const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, - const mcu_pin_obj_t * rs485_dir, bool rs485_invert, + const mcu_pin_obj_t *tx, const mcu_pin_obj_t *rx, + const mcu_pin_obj_t *rts, const mcu_pin_obj_t *cts, + const mcu_pin_obj_t *rs485_dir, bool rs485_invert, uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, - mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, + mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { - //match pins to UART objects - USART_TypeDef * USARTx; + // match pins to UART objects + USART_TypeDef *USARTx; uint8_t tx_len = MP_ARRAY_SIZE(mcu_uart_tx_list); uint8_t rx_len = MP_ARRAY_SIZE(mcu_uart_rx_list); bool uart_taken = false; - uint8_t periph_index = 0; //origin 0 corrected + uint8_t periph_index = 0; // origin 0 corrected if ((rts != NULL) || (cts != NULL) || (rs485_dir != NULL) || (rs485_invert == true)) { mp_raise_ValueError(translate("RTS/CTS/RS485 Not yet supported on this device")); } - //Can have both pins, or either + // Can have both pins, or either if ((tx != NULL) && (rx != NULL)) { - //normal find loop if both pins exist + // normal find loop if both pins exist for (uint i = 0; i < tx_len; i++) { if (mcu_uart_tx_list[i].pin == tx) { - //rx + // rx for (uint j = 0; j < rx_len; j++) { if (mcu_uart_rx_list[j].pin == rx && mcu_uart_rx_list[j].periph_index == mcu_uart_tx_list[i].periph_index) { - //keep looking if the UART is taken, edge case + // keep looking if the UART is taken, edge case if (reserved_uart[mcu_uart_tx_list[i].periph_index - 1]) { uart_taken = true; continue; } - //store pins if not + // store pins if not self->tx = &mcu_uart_tx_list[i]; self->rx = &mcu_uart_rx_list[j]; break; @@ -125,15 +125,15 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, USARTx = assign_uart_or_throw(self, (self->tx != NULL && self->rx != NULL), periph_index, uart_taken); } else if (tx == NULL) { - //If there is no tx, run only rx + // If there is no tx, run only rx for (uint i = 0; i < rx_len; i++) { if (mcu_uart_rx_list[i].pin == rx) { - //keep looking if the UART is taken, edge case + // keep looking if the UART is taken, edge case if (reserved_uart[mcu_uart_rx_list[i].periph_index - 1]) { uart_taken = true; continue; } - //store pins if not + // store pins if not self->rx = &mcu_uart_rx_list[i]; break; } @@ -142,15 +142,15 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, USARTx = assign_uart_or_throw(self, (self->rx != NULL), periph_index, uart_taken); } else if (rx == NULL) { - //If there is no rx, run only tx + // If there is no rx, run only tx for (uint i = 0; i < tx_len; i++) { if (mcu_uart_tx_list[i].pin == tx) { - //keep looking if the UART is taken, edge case + // keep looking if the UART is taken, edge case if (reserved_uart[mcu_uart_tx_list[i].periph_index - 1]) { uart_taken = true; continue; } - //store pins if not + // store pins if not self->tx = &mcu_uart_tx_list[i]; break; } @@ -159,22 +159,22 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, USARTx = assign_uart_or_throw(self, (self->tx != NULL), periph_index, uart_taken); } else { - //both pins cannot be empty + // both pins cannot be empty mp_raise_ValueError(translate("Supply at least one UART pin")); } - //Other errors - if ( receiver_buffer_size == 0 ) { + // Other errors + if (receiver_buffer_size == 0) { mp_raise_ValueError(translate("Invalid buffer size")); } - if ( bits != 8 && bits != 9 ) { + if (bits != 8 && bits != 9) { mp_raise_ValueError(translate("Invalid word/bit length")); } - if ( USARTx == NULL) { //this can only be hit if the periph file is wrong + if (USARTx == NULL) { // this can only be hit if the periph file is wrong mp_raise_ValueError(translate("Internal define error")); } - //GPIO Init + // GPIO Init GPIO_InitTypeDef GPIO_InitStruct = {0}; if (self->tx != NULL) { GPIO_InitStruct.Pin = pin_mask(tx->number); @@ -193,7 +193,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, HAL_GPIO_Init(pin_port(rx->port), &GPIO_InitStruct); } - //reserve uart and enable the peripheral + // reserve uart and enable the peripheral reserved_uart[periph_index] = true; uart_clock_enable(1 << (periph_index)); uart_assign_irq(self, USARTx); @@ -203,15 +203,14 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, self->handle.Init.WordLength = (bits == 9) ? UART_WORDLENGTH_9B : UART_WORDLENGTH_8B; self->handle.Init.StopBits = (stop > 1) ? UART_STOPBITS_2 : UART_STOPBITS_1; self->handle.Init.Parity = (parity == BUSIO_UART_PARITY_ODD) ? UART_PARITY_ODD : - (parity == BUSIO_UART_PARITY_EVEN) ? UART_PARITY_EVEN : - UART_PARITY_NONE; + (parity == BUSIO_UART_PARITY_EVEN) ? UART_PARITY_EVEN : + UART_PARITY_NONE; self->handle.Init.Mode = (self->tx != NULL && self->rx != NULL) ? UART_MODE_TX_RX : - (self->tx != NULL) ? UART_MODE_TX : - UART_MODE_RX; + (self->tx != NULL) ? UART_MODE_TX : + UART_MODE_RX; self->handle.Init.HwFlowCtl = UART_HWCONTROL_NONE; self->handle.Init.OverSampling = UART_OVERSAMPLING_16; - if (HAL_UART_Init(&self->handle) != HAL_OK) - { + if (HAL_UART_Init(&self->handle) != HAL_OK) { mp_raise_ValueError(translate("UART Init Error")); } @@ -219,7 +218,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, // Init buffer for rx and claim pins if (self->rx != NULL) { if (receiver_buffer != NULL) { - self->ringbuf = (ringbuf_t){ receiver_buffer, receiver_buffer_size }; + self->ringbuf = (ringbuf_t) { receiver_buffer, receiver_buffer_size }; } else { if (!ringbuf_alloc(&self->ringbuf, receiver_buffer_size, true)) { mp_raise_ValueError(translate("UART Buffer allocation error")); @@ -234,13 +233,13 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, self->timeout_ms = timeout * 1000; self->sigint_enabled = sigint_enabled; - //start the interrupt series + // start the interrupt series if ((HAL_UART_GetState(&self->handle) & HAL_UART_STATE_BUSY_RX) == HAL_UART_STATE_BUSY_RX) { mp_raise_ValueError(translate("Could not start interrupt, RX busy")); } - //start the receive interrupt chain - HAL_NVIC_DisableIRQ(self->irq); //prevent handle lock contention + // start the receive interrupt chain + HAL_NVIC_DisableIRQ(self->irq); // prevent handle lock contention HAL_UART_Receive_IT(&self->handle, &self->rx_char, 1); HAL_NVIC_SetPriority(self->irq, UART_IRQPRI, UART_IRQSUB_PRI); HAL_NVIC_EnableIRQ(self->irq); @@ -260,11 +259,13 @@ void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { } bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { - return (self->tx->pin == NULL && self->rx->pin == NULL); + return self->tx->pin == NULL && self->rx->pin == NULL; } void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { - if (common_hal_busio_uart_deinited(self)) return; + if (common_hal_busio_uart_deinited(self)) { + return; + } for (size_t i = 0; i < MP_ARRAY_SIZE(mcu_uart_banks); i++) { if (mcu_uart_banks[i] == self->handle.Instance) { @@ -294,14 +295,14 @@ size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t uint64_t start_ticks = supervisor_ticks_ms64(); // Wait for all bytes received or timeout, same as nrf - while ( (ringbuf_num_filled(&self->ringbuf) < len) && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms) ) { + while ((ringbuf_num_filled(&self->ringbuf) < len) && (supervisor_ticks_ms64() - start_ticks < self->timeout_ms)) { RUN_BACKGROUND_TASKS; - //restart if it failed in the callback + // restart if it failed in the callback if (errflag != HAL_OK) { errflag = HAL_UART_Receive_IT(&self->handle, &self->rx_char, 1); } // Allow user to break out of a timeout with a KeyboardInterrupt. - if ( mp_hal_is_interrupted() ) { + if (mp_hal_is_interrupted()) { return 0; } } @@ -324,10 +325,10 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, if (self->tx == NULL) { mp_raise_ValueError(translate("No TX pin")); } - bool write_err = false; //write error shouldn't disable interrupts + bool write_err = false; // write error shouldn't disable interrupts HAL_NVIC_DisableIRQ(self->irq); - HAL_StatusTypeDef ret = HAL_UART_Transmit(&self->handle, (uint8_t*)data, len, HAL_MAX_DELAY); + HAL_StatusTypeDef ret = HAL_UART_Transmit(&self->handle, (uint8_t *)data, len, HAL_MAX_DELAY); if (ret != HAL_OK) { write_err = true; } @@ -340,13 +341,12 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, return len; } -void HAL_UART_RxCpltCallback(UART_HandleTypeDef *handle) -{ +void HAL_UART_RxCpltCallback(UART_HandleTypeDef *handle) { for (int i = 0; i < 7; i++) { - //get context pointer and cast it as struct pointer - busio_uart_obj_t * context = (busio_uart_obj_t*)MP_STATE_PORT(cpy_uart_obj_all)[i]; + // get context pointer and cast it as struct pointer + busio_uart_obj_t *context = (busio_uart_obj_t *)MP_STATE_PORT(cpy_uart_obj_all)[i]; if (handle == &context->handle) { - //check if transaction is ongoing + // check if transaction is ongoing if ((HAL_UART_GetState(handle) & HAL_UART_STATE_BUSY_RX) == HAL_UART_STATE_BUSY_RX) { return; } @@ -364,8 +364,7 @@ void HAL_UART_RxCpltCallback(UART_HandleTypeDef *handle) } } -void HAL_UART_ErrorCallback(UART_HandleTypeDef *UartHandle) -{ +void HAL_UART_ErrorCallback(UART_HandleTypeDef *UartHandle) { if (__HAL_UART_GET_FLAG(UartHandle, UART_FLAG_PE) != RESET) { __HAL_UART_CLEAR_PEFLAG(UartHandle); } else if (__HAL_UART_GET_FLAG(UartHandle, UART_FLAG_FE) != RESET) { @@ -375,9 +374,9 @@ void HAL_UART_ErrorCallback(UART_HandleTypeDef *UartHandle) } else if (__HAL_UART_GET_FLAG(UartHandle, UART_FLAG_ORE) != RESET) { __HAL_UART_CLEAR_OREFLAG(UartHandle); } - //restart serial read after an error + // restart serial read after an error for (int i = 0; i < 7; i++) { - busio_uart_obj_t * context = (busio_uart_obj_t *)MP_STATE_PORT(cpy_uart_obj_all)[i]; + busio_uart_obj_t *context = (busio_uart_obj_t *)MP_STATE_PORT(cpy_uart_obj_all)[i]; if (UartHandle == &context->handle) { HAL_UART_Receive_IT(UartHandle, &context->rx_char, 1); return; @@ -391,10 +390,12 @@ uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { } void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrate) { - //Don't reset if it's the same value - if (baudrate == self->baudrate) return; + // Don't reset if it's the same value + if (baudrate == self->baudrate) { + return; + } - //Otherwise de-init and set new rate + // Otherwise de-init and set new rate if (HAL_UART_DeInit(&self->handle) != HAL_OK) { mp_raise_ValueError(translate("UART De-init error")); } @@ -407,7 +408,7 @@ void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrat } mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { - return (mp_float_t) (self->timeout_ms / 1000.0f); + return (mp_float_t)(self->timeout_ms / 1000.0f); } void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { @@ -430,8 +431,8 @@ bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { } STATIC void call_hal_irq(int uart_num) { - //Create casted context pointer - busio_uart_obj_t * context = (busio_uart_obj_t*)MP_STATE_PORT(cpy_uart_obj_all)[uart_num - 1]; + // Create casted context pointer + busio_uart_obj_t *context = (busio_uart_obj_t *)MP_STATE_PORT(cpy_uart_obj_all)[uart_num - 1]; if (context != NULL) { HAL_NVIC_ClearPendingIRQ(context->irq); HAL_UART_IRQHandler(&context->handle); @@ -609,7 +610,7 @@ STATIC void uart_clock_disable(uint16_t mask) { #endif } -STATIC void uart_assign_irq(busio_uart_obj_t *self, USART_TypeDef * USARTx) { +STATIC void uart_assign_irq(busio_uart_obj_t *self, USART_TypeDef *USARTx) { #ifdef USART1 if (USARTx == USART1) { self->irq = USART1_IRQn; diff --git a/ports/stm/common-hal/canio/CAN.c b/ports/stm/common-hal/canio/CAN.c index 52d5cad1fe..091421fd1e 100644 --- a/ports/stm/common-hal/canio/CAN.c +++ b/ports/stm/common-hal/canio/CAN.c @@ -38,7 +38,7 @@ STATIC bool reserved_can[MP_ARRAY_SIZE(mcu_can_banks)]; STATIC const mcu_periph_obj_t *find_pin_function(const mcu_periph_obj_t *table, size_t sz, const mcu_pin_obj_t *pin, int periph_index) { - for(size_t i = 0; iperiph_index) { continue; } @@ -50,9 +50,8 @@ STATIC const mcu_periph_obj_t *find_pin_function(const mcu_periph_obj_t *table, } -void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mcu_pin_obj_t *rx, int baudrate, bool loopback, bool silent) -{ -#define DIV_ROUND(a, b) (((a) + (b)/2) / (b)) +void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mcu_pin_obj_t *rx, int baudrate, bool loopback, bool silent) { +#define DIV_ROUND(a, b) (((a) + (b) / 2) / (b)) #define DIV_ROUND_UP(a, b) (((a) + (b) - 1) / (b)) const uint8_t can_tx_len = MP_ARRAY_SIZE(mcu_can_tx_list); @@ -110,7 +109,7 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mc __HAL_RCC_CAN1_CLK_ENABLE(); - if(hw == CAN2) { + if (hw == CAN2) { __HAL_RCC_CAN2_CLK_ENABLE(); self->start_filter_bank = 14; self->end_filter_bank = 28; @@ -126,9 +125,9 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mc .AutoBusOff = ENABLE, .Prescaler = divisor, .Mode = (loopback ? CAN_MODE_LOOPBACK : 0) | (silent ? CAN_MODE_SILENT_LOOPBACK : 0), - .SyncJumpWidth = (sjw-1) << CAN_BTR_SJW_Pos, - .TimeSeg1 = (tq_to_sample-2) << CAN_BTR_TS1_Pos, - .TimeSeg2 = (tq_after_sample-1) << CAN_BTR_TS2_Pos, + .SyncJumpWidth = (sjw - 1) << CAN_BTR_SJW_Pos, + .TimeSeg1 = (tq_to_sample - 2) << CAN_BTR_TS1_Pos, + .TimeSeg2 = (tq_after_sample - 1) << CAN_BTR_TS2_Pos, }; self->periph_index = periph_index; @@ -149,7 +148,7 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mc // Clear every filter enable bit for this can HW uint32_t fa1r = self->filter_hw->FA1R; - for (int i = self->start_filter_bank; iend_filter_bank; i++) { + for (int i = self->start_filter_bank; i < self->end_filter_bank; i++) { fa1r &= ~(1 << i); } self->filter_hw->FA1R = fa1r; @@ -160,23 +159,19 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, mcu_pin_obj_t *tx, mc reserved_can[periph_index] = true; } -bool common_hal_canio_can_loopback_get(canio_can_obj_t *self) -{ +bool common_hal_canio_can_loopback_get(canio_can_obj_t *self) { return self->loopback; } -int common_hal_canio_can_baudrate_get(canio_can_obj_t *self) -{ +int common_hal_canio_can_baudrate_get(canio_can_obj_t *self) { return self->baudrate; } -int common_hal_canio_can_transmit_error_count_get(canio_can_obj_t *self) -{ +int common_hal_canio_can_transmit_error_count_get(canio_can_obj_t *self) { return (self->handle.Instance->ESR & CAN_ESR_TEC) >> CAN_ESR_TEC_Pos; } -int common_hal_canio_can_receive_error_count_get(canio_can_obj_t *self) -{ +int common_hal_canio_can_receive_error_count_get(canio_can_obj_t *self) { return (self->handle.Instance->ESR & CAN_ESR_REC) >> CAN_ESR_REC_Pos; } @@ -213,15 +208,14 @@ bool common_hal_canio_can_auto_restart_get(canio_can_obj_t *self) { } void common_hal_canio_can_auto_restart_set(canio_can_obj_t *self, bool value) { - if(value) { + if (value) { SET_BIT(self->handle.Instance->MCR, CAN_MCR_ABOM); } else { CLEAR_BIT(self->handle.Instance->MCR, CAN_MCR_ABOM); } } -void common_hal_canio_can_send(canio_can_obj_t *self, mp_obj_t message_in) -{ +void common_hal_canio_can_send(canio_can_obj_t *self, mp_obj_t message_in) { canio_message_obj_t *message = message_in; uint32_t mailbox; bool rtr = message->base.type == &canio_remote_transmission_request_type; @@ -278,8 +272,7 @@ void common_hal_canio_can_check_for_deinit(canio_can_obj_t *self) { } } -void common_hal_canio_can_deinit(canio_can_obj_t *self) -{ +void common_hal_canio_can_deinit(canio_can_obj_t *self) { if (self->handle.Instance) { SET_BIT(self->handle.Instance->MCR, CAN_MCR_RESET); while (READ_BIT(self->handle.Instance->MCR, CAN_MCR_RESET)) { @@ -290,7 +283,7 @@ void common_hal_canio_can_deinit(canio_can_obj_t *self) } void common_hal_canio_reset(void) { - for (size_t i=0; iMCR, CAN_MCR_RESET); reserved_can[i] = 0; } diff --git a/ports/stm/common-hal/canio/CAN.h b/ports/stm/common-hal/canio/CAN.h index 3157d0a036..16bb8fd1e4 100644 --- a/ports/stm/common-hal/canio/CAN.h +++ b/ports/stm/common-hal/canio/CAN.h @@ -45,12 +45,12 @@ typedef struct canio_can_obj { int baudrate; const mcu_pin_obj_t *rx_pin; const mcu_pin_obj_t *tx_pin; - bool loopback:1; - bool silent:1; - bool auto_restart:1; - bool fifo0_in_use:1; - bool fifo1_in_use:1; - uint8_t periph_index:2; + bool loopback : 1; + bool silent : 1; + bool auto_restart : 1; + bool fifo0_in_use : 1; + bool fifo1_in_use : 1; + uint8_t periph_index : 2; uint8_t cancel_mailbox; uint8_t start_filter_bank; uint8_t end_filter_bank; diff --git a/ports/stm/common-hal/canio/Listener.c b/ports/stm/common-hal/canio/Listener.c index 09456d39dd..23634eba69 100644 --- a/ports/stm/common-hal/canio/Listener.c +++ b/ports/stm/common-hal/canio/Listener.c @@ -46,7 +46,7 @@ STATIC void prevent_filter_change(canio_can_obj_t *can) { } STATIC bool filter_in_use(canio_can_obj_t *can, int idx) { - return can->filter_hw->FA1R & (1<filter_hw->FA1R & (1 << idx); } // One filter bank can hold: @@ -62,19 +62,19 @@ STATIC size_t num_filters_needed(size_t nmatch, canio_match_obj_t **matches) { } size_t num_extended_mask = 0; size_t num_standard_mask = 1; - for(size_t i=0; iextended) { num_extended_mask += 1; } else { num_standard_mask += 1; } } - return num_extended_mask + num_standard_mask/2; + return num_extended_mask + num_standard_mask / 2; } STATIC size_t num_filters_available(canio_can_obj_t *can) { size_t available = 0; - for(size_t i = can->start_filter_bank; i < can->end_filter_bank; i++) { + for (size_t i = can->start_filter_bank; i < can->end_filter_bank; i++) { if (!filter_in_use(can, i)) { available++; } @@ -87,9 +87,9 @@ STATIC void clear_filters(canio_listener_obj_t *self) { allow_filter_change(can); uint32_t fa1r = can->filter_hw->FA1R; - for(size_t i = can->start_filter_bank; i < can->end_filter_bank; i++) { + for (size_t i = can->start_filter_bank; i < can->end_filter_bank; i++) { if (((can->filter_hw->FFA1R >> i) & 1) == self->fifo_idx) { - fa1r &= ~(1<filter_hw->FA1R = fa1r; @@ -98,8 +98,8 @@ STATIC void clear_filters(canio_listener_obj_t *self) { STATIC int next_filter(canio_can_obj_t *can) { uint32_t fa1r = can->filter_hw->FA1R; - for(size_t i = can->start_filter_bank; i < can->end_filter_bank; i++) { - if (!(fa1r & (1<start_filter_bank; i < can->end_filter_bank; i++) { + if (!(fa1r & (1 << i))) { return i; } } @@ -109,8 +109,8 @@ STATIC int next_filter(canio_can_obj_t *can) { // IDE = "extended ID" flag of packet header. We always add this bit to the // mask because a match is always for just one kind of address length -#define FILTER16_IDE (1<<3) -#define FILTER32_IDE (1<<2) +#define FILTER16_IDE (1 << 3) +#define FILTER32_IDE (1 << 2) STATIC void install_standard_filter(canio_listener_obj_t *self, canio_match_obj_t *match1, canio_match_obj_t *match2) { int bank = next_filter(self->can); @@ -201,8 +201,8 @@ void set_filters(canio_listener_obj_t *self, size_t nmatch, canio_match_obj_t ** install_all_match_filter(self); } else { canio_match_obj_t *first_match = NULL; - for(size_t i = 0; iextended) { + for (size_t i = 0; i < nmatch; i++) { + if (matches[i]->extended) { install_extended_filter(self, matches[i]); } else { if (first_match) { diff --git a/ports/stm/common-hal/digitalio/DigitalInOut.c b/ports/stm/common-hal/digitalio/DigitalInOut.c index a676aeb155..fbefdb79ab 100644 --- a/ports/stm/common-hal/digitalio/DigitalInOut.c +++ b/ports/stm/common-hal/digitalio/DigitalInOut.c @@ -40,12 +40,12 @@ #endif void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { never_reset_pin_number(self->pin->port, self->pin->number); } digitalinout_result_t common_hal_digitalio_digitalinout_construct( - digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { + digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { common_hal_mcu_pin_claim(pin); self->pin = pin; @@ -74,7 +74,7 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self } void common_hal_digitalio_digitalinout_switch_to_input( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitStruct.Pin = pin_mask(self->pin->number); @@ -87,8 +87,8 @@ void common_hal_digitalio_digitalinout_switch_to_input( } digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( - digitalio_digitalinout_obj_t *self, bool value, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, bool value, + digitalio_drive_mode_t drive_mode) { common_hal_digitalio_digitalinout_set_drive_mode(self, drive_mode); common_hal_digitalio_digitalinout_set_value(self, value); @@ -96,27 +96,27 @@ digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( } digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { return (LL_GPIO_GetPinMode(pin_port(self->pin->port), pin_mask(self->pin->number)) == LL_GPIO_MODE_INPUT) ? DIRECTION_INPUT : DIRECTION_OUTPUT; } void common_hal_digitalio_digitalinout_set_value( - digitalio_digitalinout_obj_t *self, bool value) { + digitalio_digitalinout_obj_t *self, bool value) { HAL_GPIO_WritePin(pin_port(self->pin->port), pin_mask(self->pin->number), value); } bool common_hal_digitalio_digitalinout_get_value( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { return (LL_GPIO_GetPinMode(pin_port(self->pin->port), pin_mask(self->pin->number)) == LL_GPIO_MODE_INPUT) ? HAL_GPIO_ReadPin(pin_port(self->pin->port), pin_mask(self->pin->number)) : LL_GPIO_IsOutputPinSet(pin_port(self->pin->port), pin_mask(self->pin->number)); } digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( - digitalio_digitalinout_obj_t *self, - digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self, + digitalio_drive_mode_t drive_mode) { GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitStruct.Pin = pin_mask(self->pin->number); GPIO_InitStruct.Mode = (drive_mode == DRIVE_MODE_OPEN_DRAIN ? @@ -128,14 +128,14 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( } digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { return LL_GPIO_GetPinOutputType(pin_port(self->pin->port), pin_mask(self->pin->number)) - == LL_GPIO_OUTPUT_OPENDRAIN ? DRIVE_MODE_OPEN_DRAIN : DRIVE_MODE_PUSH_PULL; + == LL_GPIO_OUTPUT_OPENDRAIN ? DRIVE_MODE_OPEN_DRAIN : DRIVE_MODE_PUSH_PULL; } void common_hal_digitalio_digitalinout_set_pull( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { switch (pull) { case PULL_UP: @@ -153,7 +153,7 @@ void common_hal_digitalio_digitalinout_set_pull( } digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( - digitalio_digitalinout_obj_t *self) { + digitalio_digitalinout_obj_t *self) { switch (LL_GPIO_GetPinPull(pin_port(self->pin->port), pin_mask(self->pin->number))) { case LL_GPIO_PULL_UP: diff --git a/ports/stm/common-hal/displayio/ParallelBus.c b/ports/stm/common-hal/displayio/ParallelBus.c index fd07d38af4..4788deb9bd 100644 --- a/ports/stm/common-hal/displayio/ParallelBus.c +++ b/ports/stm/common-hal/displayio/ParallelBus.c @@ -33,19 +33,19 @@ #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/microcontroller/__init__.h" -void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* self, - const mcu_pin_obj_t* data0, const mcu_pin_obj_t* command, const mcu_pin_obj_t* chip_select, - const mcu_pin_obj_t* write, const mcu_pin_obj_t* read, const mcu_pin_obj_t* reset) { +void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t *self, + const mcu_pin_obj_t *data0, const mcu_pin_obj_t *command, const mcu_pin_obj_t *chip_select, + const mcu_pin_obj_t *write, const mcu_pin_obj_t *read, const mcu_pin_obj_t *reset) { mp_raise_NotImplementedError(translate("ParallelBus not yet supported")); } -void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self) { +void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t *self) { } bool common_hal_displayio_parallelbus_reset(mp_obj_t obj) { - return false; + return false; } bool common_hal_displayio_parallelbus_bus_free(mp_obj_t obj) { diff --git a/ports/stm/common-hal/microcontroller/Pin.c b/ports/stm/common-hal/microcontroller/Pin.c index 37c202d86e..80cb9defc8 100644 --- a/ports/stm/common-hal/microcontroller/Pin.c +++ b/ports/stm/common-hal/microcontroller/Pin.c @@ -41,15 +41,15 @@ bool apa102_mosi_in_use; #endif #if defined(TFBGA216) - GPIO_TypeDef * ports[] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH, GPIOI, GPIOJ, GPIOK}; +GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG, GPIOH, GPIOI, GPIOJ, GPIOK}; #elif defined(LQFP144) - GPIO_TypeDef * ports[] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG}; +GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE, GPIOF, GPIOG}; #elif defined(LQFP100_f4) || (LQFP100_x7) - GPIO_TypeDef * ports[] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE}; +GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE}; #elif defined(LQFP64) - GPIO_TypeDef * ports[] = {GPIOA, GPIOB, GPIOC, GPIOD}; +GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC, GPIOD}; #elif defined(UFQFPN48) - GPIO_TypeDef * ports[] = {GPIOA, GPIOB, GPIOC}; +GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC}; #endif @@ -78,7 +78,7 @@ void reset_all_pins(void) { // Mark pin as free and return it to a quiescent state. void reset_pin_number(uint8_t pin_port, uint8_t pin_number) { - if ( pin_number == NO_PIN ) { + if (pin_number == NO_PIN) { return; } @@ -86,9 +86,9 @@ void reset_pin_number(uint8_t pin_port, uint8_t pin_number) { return; } // Clear claimed bit & reset - claimed_pins[pin_port] &= ~(1<port && pin_number == MICROPY_HW_NEOPIXEL->number) { @@ -101,8 +101,7 @@ void reset_pin_number(uint8_t pin_port, uint8_t pin_number) { if ( (pin_port == MICROPY_HW_APA102_MOSI->port && pin_number == MICROPY_HW_APA102_MOSI->number) || (pin_port == MICROPY_HW_APA102_SCK->port && pin_number == MICROPY_HW_APA102_MOSI->number) - ) - { + ) { apa102_mosi_in_use = false; apa102_sck_in_use = false; rgb_led_status_init(); @@ -112,19 +111,19 @@ void reset_pin_number(uint8_t pin_port, uint8_t pin_number) { } void never_reset_pin_number(uint8_t pin_port, uint8_t pin_number) { - if ( pin_number == NO_PIN ) { + if (pin_number == NO_PIN) { return; } - never_reset_pins[pin_port] |= 1<port, pin->number); } -void common_hal_reset_pin(const mcu_pin_obj_t* pin) { +void common_hal_reset_pin(const mcu_pin_obj_t *pin) { if (pin == NULL) { return; } @@ -133,11 +132,11 @@ void common_hal_reset_pin(const mcu_pin_obj_t* pin) { void claim_pin(uint8_t pin_port, uint8_t pin_number) { // Set bit in claimed_pins bitmask. - claimed_pins[pin_port] |= 1<port, pin->number); } -GPIO_TypeDef * pin_port(uint8_t pin_port) { +GPIO_TypeDef *pin_port(uint8_t pin_port) { return ports[pin_port]; } uint16_t pin_mask(uint8_t pin_number) { - return 1<port * 16 + pin->number; } -void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) { +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { claim_pin(pin->port, pin->number); #ifdef MICROPY_HW_NEOPIXEL if (pin == MICROPY_HW_NEOPIXEL) { @@ -180,12 +177,10 @@ void common_hal_mcu_pin_claim(const mcu_pin_obj_t* pin) { } #endif #if defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) - if (pin == MICROPY_HW_APA102_MOSI) - { + if (pin == MICROPY_HW_APA102_MOSI) { apa102_mosi_in_use = true; } - if (pin == MICROPY_HW_APA102_SCK) - { + if (pin == MICROPY_HW_APA102_SCK) { apa102_sck_in_use = true; } #endif diff --git a/ports/stm/common-hal/microcontroller/Pin.h b/ports/stm/common-hal/microcontroller/Pin.h index f461d3813f..4a33979421 100644 --- a/ports/stm/common-hal/microcontroller/Pin.h +++ b/ports/stm/common-hal/microcontroller/Pin.h @@ -46,7 +46,7 @@ void reset_pin_number(uint8_t pin_port, uint8_t pin_number); void claim_pin(uint8_t pin_port, uint8_t pin_number); bool pin_number_is_free(uint8_t pin_port, uint8_t pin_number); void never_reset_pin_number(uint8_t pin_port, uint8_t pin_number); -GPIO_TypeDef * pin_port(uint8_t pin_port); +GPIO_TypeDef *pin_port(uint8_t pin_port); uint16_t pin_mask(uint8_t pin_number); #endif // MICROPY_INCLUDED_STM32_COMMON_HAL_MICROCONTROLLER_PIN_H diff --git a/ports/stm/common-hal/microcontroller/Processor.c b/ports/stm/common-hal/microcontroller/Processor.c index dd04c56dce..b33d96e736 100644 --- a/ports/stm/common-hal/microcontroller/Processor.c +++ b/ports/stm/common-hal/microcontroller/Processor.c @@ -37,10 +37,10 @@ #define STM32_UUID ((uint32_t *)0x1FFF7A10) -//Factory calibration locations +// Factory calibration locations #define ADC_CAL_ADDRESS (0x1fff7a2a) -#define ADC_CAL1 ((uint16_t*)(ADC_CAL_ADDRESS + 2)) -#define ADC_CAL2 ((uint16_t*)(ADC_CAL_ADDRESS + 4)) +#define ADC_CAL1 ((uint16_t *)(ADC_CAL_ADDRESS + 2)) +#define ADC_CAL2 ((uint16_t *)(ADC_CAL_ADDRESS + 4)) #define VREFIN_CAL ((uint16_t *)ADC_CAL_ADDRESS) // correction factor for reference value @@ -68,7 +68,7 @@ float common_hal_mcu_processor_get_temperature(void) { #if CPY_STM32F4 __HAL_RCC_ADC1_CLK_ENABLE(); - //HAL Implementation + // HAL Implementation ADC_HandleTypeDef AdcHandle; ADC_ChannelConfTypeDef sConfig; set_adc_params(&AdcHandle); @@ -77,7 +77,7 @@ float common_hal_mcu_processor_get_temperature(void) { ADC->CCR |= ADC_CCR_TSVREFE; ADC->CCR &= ~ADC_CCR_VBATE; // If this somehow got turned on, it'll return bad values. - sConfig.Channel = ADC_CHANNEL_TEMPSENSOR; //either 16 or 18, depending on chip + sConfig.Channel = ADC_CHANNEL_TEMPSENSOR; // either 16 or 18, depending on chip sConfig.Rank = 1; sConfig.SamplingTime = ADC_SAMPLETIME_480CYCLES; // Temp sensor likes 10us minimum HAL_ADC_ConfigChannel(&AdcHandle, &sConfig); @@ -89,7 +89,7 @@ float common_hal_mcu_processor_get_temperature(void) { uint32_t value = (uint32_t)HAL_ADC_GetValue(&AdcHandle); HAL_ADC_Stop(&AdcHandle); - //There's no F4 specific appnote for this but it works the same as the L1 in AN3964 + // There's no F4 specific appnote for this but it works the same as the L1 in AN3964 float core_temp_avg_slope = (*ADC_CAL2 - *ADC_CAL1) / 80.0; return (((float)value * adc_refcor - *ADC_CAL1) / core_temp_avg_slope) + 30.0f; #else @@ -101,7 +101,7 @@ float common_hal_mcu_processor_get_voltage(void) { #if CPY_STM32F4 __HAL_RCC_ADC1_CLK_ENABLE(); - //HAL Implementation + // HAL Implementation ADC_HandleTypeDef AdcHandle; ADC_ChannelConfTypeDef sConfig; set_adc_params(&AdcHandle); @@ -121,7 +121,7 @@ float common_hal_mcu_processor_get_voltage(void) { uint32_t value = (uint32_t)HAL_ADC_GetValue(&AdcHandle); HAL_ADC_Stop(&AdcHandle); - //This value could be used to actively correct ADC values. + // This value could be used to actively correct ADC values. adc_refcor = ((float)(*VREFIN_CAL)) / ((float)value); return adc_refcor * 3.3f; @@ -136,8 +136,8 @@ uint32_t common_hal_mcu_processor_get_frequency(void) { void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { #if CPY_STM32F4 - for (int i=0; i<3; i++) { - ((uint32_t*) raw_id)[i] = STM32_UUID[i]; + for (int i = 0; i < 3; i++) { + ((uint32_t *)raw_id)[i] = STM32_UUID[i]; } #endif } diff --git a/ports/stm/common-hal/microcontroller/__init__.c b/ports/stm/common-hal/microcontroller/__init__.c index a827399ccb..28e06c9135 100644 --- a/ports/stm/common-hal/microcontroller/__init__.c +++ b/ports/stm/common-hal/microcontroller/__init__.c @@ -41,11 +41,12 @@ #include "supervisor/shared/safe_mode.h" void common_hal_mcu_delay_us(uint32_t delay) { - uint32_t ticks_per_us = HAL_RCC_GetSysClockFreq()/1000000; + uint32_t ticks_per_us = HAL_RCC_GetSysClockFreq() / 1000000; delay *= ticks_per_us; SysTick->LOAD = delay; SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk; - while ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == 0) {} + while ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == 0) { + } SysTick->CTRL = 0; } @@ -61,7 +62,7 @@ void common_hal_mcu_enable_interrupts(void) { if (nesting_count == 0) { // This is very very bad because it means there was mismatched disable/enables so we // "HardFault". - asm("bkpt"); + asm ("bkpt"); } nesting_count--; if (nesting_count > 0) { @@ -72,12 +73,13 @@ void common_hal_mcu_enable_interrupts(void) { } void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { - if(runmode == RUNMODE_SAFE_MODE) - safe_mode_on_next_reset(PROGRAMMATIC_SAFE_MODE); + if (runmode == RUNMODE_SAFE_MODE) { + safe_mode_on_next_reset(PROGRAMMATIC_SAFE_MODE); + } } void common_hal_mcu_reset(void) { - filesystem_flush(); //TODO: implement as part of flash improvements + filesystem_flush(); // TODO: implement as part of flash improvements NVIC_SystemReset(); } @@ -96,6 +98,6 @@ const nvm_bytearray_obj_t common_hal_mcu_nvm_obj = { .type = &nvm_bytearray_type, }, .len = NVM_BYTEARRAY_BUFFER_SIZE, - .start_address = (uint8_t*) (CIRCUITPY_INTERNAL_NVM_START_ADDR) + .start_address = (uint8_t *)(CIRCUITPY_INTERNAL_NVM_START_ADDR) }; #endif diff --git a/ports/stm/common-hal/neopixel_write/__init__.c b/ports/stm/common-hal/neopixel_write/__init__.c index c8852403b2..f5dabe7f99 100644 --- a/ports/stm/common-hal/neopixel_write/__init__.c +++ b/ports/stm/common-hal/neopixel_write/__init__.c @@ -36,7 +36,7 @@ uint64_t next_start_raw_ticks = 0; -//sysclock divisors +// sysclock divisors #define MAGIC_800_INT 900000 // ~1.11 us -> 1.2 field #define MAGIC_800_T0H 2800000 // ~0.36 us -> 0.44 field #define MAGIC_800_T1H 1350000 // ~0.74 us -> 0.84 field @@ -44,25 +44,26 @@ uint64_t next_start_raw_ticks = 0; #pragma GCC push_options #pragma GCC optimize ("Os") -void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout, uint8_t *pixels, - uint32_t numBytes) { +void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, uint8_t *pixels, + uint32_t numBytes) { uint8_t *p = pixels, *end = p + numBytes, pix = *p++, mask = 0x80; uint32_t start = 0; uint32_t cyc = 0; - //assumes 800_000Hz frequency - //Theoretical values here are 800_000 -> 1.25us, 2500000->0.4us, 1250000->0.8us - //TODO: try to get dynamic weighting working again + // assumes 800_000Hz frequency + // Theoretical values here are 800_000 -> 1.25us, 2500000->0.4us, 1250000->0.8us + // TODO: try to get dynamic weighting working again uint32_t sys_freq = HAL_RCC_GetSysClockFreq(); - uint32_t interval = sys_freq/MAGIC_800_INT; - uint32_t t0 = (sys_freq/MAGIC_800_T0H); - uint32_t t1 = (sys_freq/MAGIC_800_T1H); + uint32_t interval = sys_freq / MAGIC_800_INT; + uint32_t t0 = (sys_freq / MAGIC_800_T0H); + uint32_t t1 = (sys_freq / MAGIC_800_T1H); // Wait to make sure we don't append onto the last transmission. This should only be a tick or // two. - while (port_get_raw_ticks(NULL) < next_start_raw_ticks) {} + while (port_get_raw_ticks(NULL) < next_start_raw_ticks) { + } - GPIO_TypeDef * p_port = pin_port(digitalinout->pin->port); + GPIO_TypeDef *p_port = pin_port(digitalinout->pin->port); uint32_t p_mask = pin_mask(digitalinout->pin->number); __disable_irq(); @@ -71,16 +72,22 @@ void common_hal_neopixel_write (const digitalio_digitalinout_obj_t* digitalinout DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; DWT->CYCCNT = 0; - for(;;) { + for (;;) { cyc = (pix & mask) ? t1 : t0; start = DWT->CYCCNT; LL_GPIO_SetOutputPin(p_port, p_mask); - while((DWT->CYCCNT - start) < cyc); + while ((DWT->CYCCNT - start) < cyc) { + ; + } LL_GPIO_ResetOutputPin(p_port, p_mask); - while((DWT->CYCCNT - start) < interval); - if(!(mask >>= 1)) { - if(p >= end) break; - pix = *p++; + while ((DWT->CYCCNT - start) < interval) { + ; + } + if (!(mask >>= 1)) { + if (p >= end) { + break; + } + pix = *p++; mask = 0x80; } } diff --git a/ports/stm/common-hal/nvm/ByteArray.c b/ports/stm/common-hal/nvm/ByteArray.c index b7a1ff0351..6ef2eb3928 100644 --- a/ports/stm/common-hal/nvm/ByteArray.c +++ b/ports/stm/common-hal/nvm/ByteArray.c @@ -38,7 +38,7 @@ uint32_t common_hal_nvm_bytearray_get_length(nvm_bytearray_obj_t *self) { } bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, - uint32_t start_index, uint8_t* values, uint32_t len) { + uint32_t start_index, uint8_t *values, uint32_t len) { // Copy flash to buffer uint8_t buffer[self->len]; memcpy(buffer, self->start_address, self->len); @@ -48,7 +48,7 @@ bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, // Erase flash sector HAL_FLASH_Unlock(); - __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR ); + __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); FLASH_Erase_Sector(CIRCUITPY_INTERNAL_NVM_SECTOR, VOLTAGE_RANGE_3); // Write bytes to flash @@ -68,6 +68,6 @@ bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, // NVM memory is memory mapped so reading it is easy. void common_hal_nvm_bytearray_get_bytes(nvm_bytearray_obj_t *self, - uint32_t start_index, uint32_t len, uint8_t* values) { + uint32_t start_index, uint32_t len, uint8_t *values) { memcpy(values, self->start_address + start_index, len); } diff --git a/ports/stm/common-hal/nvm/ByteArray.h b/ports/stm/common-hal/nvm/ByteArray.h index b6ea36de3f..b88d919764 100644 --- a/ports/stm/common-hal/nvm/ByteArray.h +++ b/ports/stm/common-hal/nvm/ByteArray.h @@ -38,7 +38,7 @@ typedef struct { mp_obj_base_t base; - uint8_t* start_address; + uint8_t *start_address; uint32_t len; } nvm_bytearray_obj_t; diff --git a/ports/stm/common-hal/os/__init__.c b/ports/stm/common-hal/os/__init__.c index 8da7243a30..66dfd9f768 100644 --- a/ports/stm/common-hal/os/__init__.c +++ b/ports/stm/common-hal/os/__init__.c @@ -55,7 +55,7 @@ STATIC MP_DEFINE_ATTRTUPLE( (mp_obj_t)&os_uname_info_release_obj, (mp_obj_t)&os_uname_info_version_obj, (mp_obj_t)&os_uname_info_machine_obj -); + ); mp_obj_t common_hal_os_uname(void) { return (mp_obj_t)&os_uname_info_obj; @@ -65,19 +65,23 @@ mp_obj_t common_hal_os_uname(void) { bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { #if (HAS_TRNG) - //init the RNG + // init the RNG __HAL_RCC_RNG_CLK_ENABLE(); RNG_HandleTypeDef handle; handle.Instance = RNG; - if (HAL_RNG_Init(&handle) != HAL_OK) mp_raise_ValueError(translate("RNG Init Error")); + if (HAL_RNG_Init(&handle) != HAL_OK) { + mp_raise_ValueError(translate("RNG Init Error")); + } - //Assign bytes + // Assign bytes uint32_t i = 0; while (i < length) { uint32_t new_random; uint32_t start = HAL_GetTick(); - //the HAL function has a timeout, but it isn't long enough, and isn't adjustable - while(!(__HAL_RNG_GET_FLAG(&handle,RNG_FLAG_DRDY)) && ((HAL_GetTick() - start) < RNG_TIMEOUT)); + // the HAL function has a timeout, but it isn't long enough, and isn't adjustable + while (!(__HAL_RNG_GET_FLAG(&handle,RNG_FLAG_DRDY)) && ((HAL_GetTick() - start) < RNG_TIMEOUT)) { + ; + } if (HAL_RNG_GenerateRandomNumber(&handle, &new_random) != HAL_OK) { mp_raise_ValueError(translate("Random number generation error")); } @@ -88,8 +92,10 @@ bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { } } - //shut down the peripheral - if (HAL_RNG_DeInit(&handle) != HAL_OK) mp_raise_ValueError(translate("RNG DeInit Error")); + // shut down the peripheral + if (HAL_RNG_DeInit(&handle) != HAL_OK) { + mp_raise_ValueError(translate("RNG DeInit Error")); + } __HAL_RCC_RNG_CLK_DISABLE(); return true; diff --git a/ports/stm/common-hal/pulseio/PulseIn.c b/ports/stm/common-hal/pulseio/PulseIn.c index 015ee8536d..ece02f66a8 100644 --- a/ports/stm/common-hal/pulseio/PulseIn.c +++ b/ports/stm/common-hal/pulseio/PulseIn.c @@ -38,21 +38,18 @@ #include STM32_HAL_H #define STM32_GPIO_PORT_SIZE 16 -static pulseio_pulsein_obj_t* _objs[STM32_GPIO_PORT_SIZE]; +static pulseio_pulsein_obj_t *_objs[STM32_GPIO_PORT_SIZE]; STATIC TIM_HandleTypeDef tim_handle; static uint32_t overflow_count = 0; STATIC uint8_t refcount = 0; -static void assign_EXTI_Interrupt(pulseio_pulsein_obj_t* self, uint8_t num); +static void assign_EXTI_Interrupt(pulseio_pulsein_obj_t *self, uint8_t num); -void pulsein_timer_event_handler(void) -{ +void pulsein_timer_event_handler(void) { // Detect TIM Update event - if (__HAL_TIM_GET_FLAG(&tim_handle, TIM_FLAG_UPDATE) != RESET) - { - if (__HAL_TIM_GET_IT_SOURCE(&tim_handle, TIM_IT_UPDATE) != RESET) - { + if (__HAL_TIM_GET_FLAG(&tim_handle, TIM_FLAG_UPDATE) != RESET) { + if (__HAL_TIM_GET_IT_SOURCE(&tim_handle, TIM_IT_UPDATE) != RESET) { __HAL_TIM_CLEAR_IT(&tim_handle, TIM_IT_UPDATE); overflow_count++; } @@ -67,13 +64,15 @@ static void pulsein_exti_event_handler(uint8_t num) { // Interrupt register must be cleared manually EXTI->PR = 1 << num; - pulseio_pulsein_obj_t* self = _objs[num]; - if ( !self ) return; + pulseio_pulsein_obj_t *self = _objs[num]; + if (!self) { + return; + } if (self->first_edge) { // first pulse is opposite state from idle bool state = HAL_GPIO_ReadPin(pin_port(self->pin->port), pin_mask(self->pin->number)); - if ( self->idle_state != state ) { + if (self->idle_state != state) { self->first_edge = false; } } else { @@ -109,20 +108,20 @@ void pulsein_reset(void) { refcount = 0; } -void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu_pin_obj_t* pin, - uint16_t maxlen, bool idle_state) { +void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin, + uint16_t maxlen, bool idle_state) { // STM32 has one shared EXTI for each pin number, 0-15 uint8_t p_num = pin->number; - if(_objs[p_num]) { + if (_objs[p_num]) { mp_raise_ValueError(translate("Pin number already reserved by EXTI")); } _objs[p_num] = self; // Allocate pulse buffer - self->buffer = (uint16_t *) m_malloc(maxlen * sizeof(uint16_t), false); + self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t), false); if (self->buffer == NULL) { mp_raise_msg_varg(&mp_type_MemoryError, translate("Failed to allocate RX buffer of %d bytes"), - maxlen * sizeof(uint16_t)); + maxlen * sizeof(uint16_t)); } // Set internal variables @@ -138,12 +137,12 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu if (HAL_TIM_Base_GetState(&tim_handle) == HAL_TIM_STATE_RESET) { // Find a suitable timer - TIM_TypeDef * tim_instance = stm_peripherals_find_timer(); + TIM_TypeDef *tim_instance = stm_peripherals_find_timer(); stm_peripherals_timer_reserve(tim_instance); // Set ticks to 1us uint32_t source = stm_peripherals_timer_get_source_freq(tim_instance); - uint32_t prescaler = source/1000000; + uint32_t prescaler = source / 1000000; // Enable clocks and IRQ, set callback stm_peripherals_timer_preinit(tim_instance, 4, pulsein_timer_event_handler); @@ -151,7 +150,7 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu // Set the new period tim_handle.Instance = tim_instance; tim_handle.Init.Prescaler = prescaler - 1; - tim_handle.Init.Period = 0x10000 - 1; //65 ms period (maximum) + tim_handle.Init.Period = 0x10000 - 1; // 65 ms period (maximum) HAL_TIM_Base_Init(&tim_handle); // Set registers manually @@ -178,15 +177,15 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, const mcu common_hal_mcu_pin_claim(pin); } -bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t* self) { - return (self->pin == NULL); +bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self) { + return self->pin == NULL; } -void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { if (common_hal_pulseio_pulsein_deinited(self)) { return; } - //Remove pulsein slot from shared array + // Remove pulsein slot from shared array _objs[self->pin->number] = NULL; reset_pin_number(self->pin->port, self->pin->number); self->pin = NULL; @@ -197,14 +196,14 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self) { } } -void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self) { HAL_NVIC_DisableIRQ(self->irq); self->paused = true; } -void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, uint16_t trigger_duration) { +void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t *self, uint16_t trigger_duration) { // Make sure we're paused. - if ( !self->paused ) { + if (!self->paused) { common_hal_pulseio_pulsein_pause(self); } @@ -235,14 +234,14 @@ void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, uint16_t tri HAL_NVIC_EnableIRQ(self->irq); } -void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t* self) { +void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t *self) { HAL_NVIC_DisableIRQ(self->irq); self->start = 0; self->len = 0; HAL_NVIC_EnableIRQ(self->irq); } -uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, int16_t index) { +uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t *self, int16_t index) { HAL_NVIC_DisableIRQ(self->irq); if (index < 0) { index += self->len; @@ -256,7 +255,7 @@ uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, int16_ return value; } -uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t *self) { if (self->len == 0) { mp_raise_IndexError_varg(translate("pop from empty %q"), MP_QSTR_PulseIn); } @@ -269,19 +268,19 @@ uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self) { return value; } -uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t *self) { return self->maxlen; } -bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t* self) { +bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t *self) { return self->paused; } -uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t* self) { +uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t *self) { return self->len; } -static void assign_EXTI_Interrupt(pulseio_pulsein_obj_t* self, uint8_t num) { +static void assign_EXTI_Interrupt(pulseio_pulsein_obj_t *self, uint8_t num) { if (num == 0) { self->irq = EXTI0_IRQn; } else if (num == 1) { @@ -292,49 +291,42 @@ static void assign_EXTI_Interrupt(pulseio_pulsein_obj_t* self, uint8_t num) { self->irq = EXTI3_IRQn; } else if (num == 4) { self->irq = EXTI4_IRQn; - } else if (num >= 5 && num <= 9 ) { + } else if (num >= 5 && num <= 9) { self->irq = EXTI9_5_IRQn; } else if (num >= 10 && num <= 15) { self->irq = EXTI15_10_IRQn; } } -void EXTI0_IRQHandler(void) -{ +void EXTI0_IRQHandler(void) { pulsein_exti_event_handler(0); } -void EXTI1_IRQHandler(void) -{ +void EXTI1_IRQHandler(void) { pulsein_exti_event_handler(1); } -void EXTI2_IRQHandler(void) -{ +void EXTI2_IRQHandler(void) { pulsein_exti_event_handler(2); } -void EXTI3_IRQHandler(void) -{ +void EXTI3_IRQHandler(void) { pulsein_exti_event_handler(3); } -void EXTI4_IRQHandler(void) -{ +void EXTI4_IRQHandler(void) { pulsein_exti_event_handler(4); } -void EXTI9_5_IRQHandler(void) -{ +void EXTI9_5_IRQHandler(void) { uint32_t pending = EXTI->PR; for (uint i = 5; i <= 9; i++) { - if(pending & (1 << i)) { + if (pending & (1 << i)) { pulsein_exti_event_handler(i); } } } -void EXTI15_10_IRQHandler(void) -{ +void EXTI15_10_IRQHandler(void) { uint32_t pending = EXTI->PR; for (uint i = 10; i <= 15; i++) { - if(pending & (1 << i)) { + if (pending & (1 << i)) { pulsein_exti_event_handler(i); } } diff --git a/ports/stm/common-hal/pulseio/PulseIn.h b/ports/stm/common-hal/pulseio/PulseIn.h index 34d0cc731a..8de60b9cd5 100644 --- a/ports/stm/common-hal/pulseio/PulseIn.h +++ b/ports/stm/common-hal/pulseio/PulseIn.h @@ -34,13 +34,13 @@ typedef struct { mp_obj_base_t base; - const mcu_pin_obj_t* pin; + const mcu_pin_obj_t *pin; IRQn_Type irq; bool idle_state; bool paused; volatile bool first_edge; - uint16_t* buffer; + uint16_t *buffer; uint16_t maxlen; volatile uint16_t start; diff --git a/ports/stm/common-hal/pulseio/PulseOut.c b/ports/stm/common-hal/pulseio/PulseOut.c index 38027606f9..9e28002a69 100644 --- a/ports/stm/common-hal/pulseio/PulseOut.c +++ b/ports/stm/common-hal/pulseio/PulseOut.c @@ -45,7 +45,7 @@ STATIC uint8_t refcount = 0; STATIC uint16_t *pulse_array = NULL; STATIC volatile uint16_t pulse_array_index = 0; STATIC uint16_t pulse_array_length; -//Timer is shared, must be accessible by interrupt +// Timer is shared, must be accessible by interrupt STATIC TIM_HandleTypeDef tim_handle; STATIC pulseio_pulseout_obj_t *curr_pulseout = NULL; @@ -60,7 +60,7 @@ STATIC void turn_off(pulseio_pulseout_obj_t *pulseout) { HAL_TIM_PWM_Stop(&(pulseout->pwmout->handle), pulseout->pwmout->channel); // Make sure pin is low. HAL_GPIO_WritePin(pin_port(pulseout->pwmout->tim->pin->port), - pin_mask(pulseout->pwmout->tim->pin->number), 0); + pin_mask(pulseout->pwmout->tim->pin->number), 0); } STATIC void start_timer(void) { @@ -77,13 +77,11 @@ STATIC void start_timer(void) { STATIC void pulseout_event_handler(void) { // Detect TIM Update event - if (__HAL_TIM_GET_FLAG(&tim_handle, TIM_FLAG_UPDATE) != RESET) - { - if (__HAL_TIM_GET_IT_SOURCE(&tim_handle, TIM_IT_UPDATE) != RESET) - { + if (__HAL_TIM_GET_FLAG(&tim_handle, TIM_FLAG_UPDATE) != RESET) { + if (__HAL_TIM_GET_IT_SOURCE(&tim_handle, TIM_IT_UPDATE) != RESET) { __HAL_TIM_CLEAR_IT(&tim_handle, TIM_IT_UPDATE); if (curr_pulseout->pwmout == NULL) { - return; //invalid interrupt + return; // invalid interrupt } pulse_array_index++; @@ -112,27 +110,27 @@ void pulseout_reset() { refcount = 0; } -void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, - const pwmio_pwmout_obj_t* carrier, - const mcu_pin_obj_t* pin, - uint32_t frequency, - uint16_t duty_cycle) { +void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, + const pwmio_pwmout_obj_t *carrier, + const mcu_pin_obj_t *pin, + uint32_t frequency, + uint16_t duty_cycle) { if (!carrier || pin || frequency) { mp_raise_NotImplementedError(translate("Port does not accept pins or frequency. Construct and pass a PWMOut Carrier instead")); } // Add to active PulseOuts refcount++; - TIM_TypeDef * tim_instance = stm_peripherals_find_timer(); + TIM_TypeDef *tim_instance = stm_peripherals_find_timer(); stm_peripherals_timer_reserve(tim_instance); - //calculate a 1ms period + // calculate a 1ms period uint32_t source = stm_peripherals_timer_get_source_freq(tim_instance); - uint32_t prescaler = source/1000000; //1us intervals + uint32_t prescaler = source / 1000000; // 1us intervals stm_peripherals_timer_preinit(tim_instance, 4, pulseout_event_handler); tim_handle.Instance = tim_instance; - tim_handle.Init.Period = 100; //immediately replaced. + tim_handle.Init.Period = 100; // immediately replaced. tim_handle.Init.Prescaler = prescaler - 1; tim_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; tim_handle.Init.CounterMode = TIM_COUNTERMODE_UP; @@ -142,15 +140,15 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, tim_handle.Instance->SR = 0; // The HAL can't work with const, recast required. - self->pwmout = (pwmio_pwmout_obj_t*)carrier; + self->pwmout = (pwmio_pwmout_obj_t *)carrier; turn_off(self); } -bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t* self) { +bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t *self) { return self->pwmout == NULL; } -void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { +void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { if (common_hal_pulseio_pulseout_deinited(self)) { return; } @@ -163,7 +161,7 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self) { } } -void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pulses, uint16_t length) { +void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pulses, uint16_t length) { pulse_array = pulses; pulse_array_index = 0; pulse_array_length = length; @@ -177,7 +175,7 @@ void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pu // Use when debugging, or issues are irrecoverable // uint32_t starttime = supervisor_ticks_ms64(); // uint32_t timeout = 10000; - while(pulse_array_index < length) { + while (pulse_array_index < length) { // Do other things while we wait. The interrupts will handle sending the // signal. RUN_BACKGROUND_TASKS; @@ -187,6 +185,6 @@ void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, uint16_t* pu // mp_raise_RuntimeError(translate("Error: Send Timeout")); // } } - //turn off timer counter. + // turn off timer counter. tim_handle.Instance->CR1 &= ~TIM_CR1_CEN; } diff --git a/ports/stm/common-hal/pwmio/PWMOut.c b/ports/stm/common-hal/pwmio/PWMOut.c index 85427185e5..c463cac431 100644 --- a/ports/stm/common-hal/pwmio/PWMOut.c +++ b/ports/stm/common-hal/pwmio/PWMOut.c @@ -44,13 +44,13 @@ STATIC uint32_t tim_frequencies[TIM_BANK_ARRAY_LEN]; STATIC bool never_reset_tim[TIM_BANK_ARRAY_LEN]; STATIC uint32_t timer_get_internal_duty(uint16_t duty, uint32_t period) { - //duty cycle is duty/0xFFFF fraction x (number of pulses per period) - return (duty*period) / ((1 << 16) - 1); + // duty cycle is duty/0xFFFF fraction x (number of pulses per period) + return (duty * period) / ((1 << 16) - 1); } -STATIC void timer_get_optimal_divisors(uint32_t*period, uint32_t*prescaler, - uint32_t frequency, uint32_t source_freq) { - //Find the largest possible period supported by this frequency +STATIC void timer_get_optimal_divisors(uint32_t *period, uint32_t *prescaler, + uint32_t frequency, uint32_t source_freq) { + // Find the largest possible period supported by this frequency for (int i = 0; i < (1 << 16); i++) { *period = source_freq / (i * frequency); if (*period < (1 << 16) && *period >= 2) { @@ -75,12 +75,12 @@ void pwmout_reset(void) { } } -pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, - const mcu_pin_obj_t* pin, - uint16_t duty, - uint32_t frequency, - bool variable_frequency) { - TIM_TypeDef * TIMx; +pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, + const mcu_pin_obj_t *pin, + uint16_t duty, + uint32_t frequency, + bool variable_frequency) { + TIM_TypeDef *TIMx; uint8_t tim_num = MP_ARRAY_SIZE(mcu_tim_pin_list); bool tim_taken_internal = false; bool tim_chan_taken = false; @@ -89,47 +89,47 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, bool first_time_setup = true; for (uint i = 0; i < tim_num; i++) { - const mcu_tim_pin_obj_t * l_tim = &mcu_tim_pin_list[i]; + const mcu_tim_pin_obj_t *l_tim = &mcu_tim_pin_list[i]; uint8_t l_tim_index = l_tim->tim_index - 1; uint8_t l_tim_channel = l_tim->channel_index - 1; - //if pin is same + // if pin is same if (l_tim->pin == pin) { - //check if the timer has a channel active, or is reserved by main timer system + // check if the timer has a channel active, or is reserved by main timer system if (l_tim_index < TIM_BANK_ARRAY_LEN && reserved_tim[l_tim_index] != 0) { // Timer has already been reserved by an internal module if (stm_peripherals_timer_is_reserved(mcu_tim_banks[l_tim_index])) { tim_taken_internal = true; - continue; //keep looking + continue; // keep looking } - //is it the same channel? (or all channels reserved by a var-freq) + // is it the same channel? (or all channels reserved by a var-freq) if (reserved_tim[l_tim_index] & 1 << (l_tim_channel)) { tim_chan_taken = true; - continue; //keep looking, might be another viable option + continue; // keep looking, might be another viable option } - //If the frequencies are the same it's ok + // If the frequencies are the same it's ok if (tim_frequencies[l_tim_index] != frequency) { tim_taken_f_mismatch = true; - continue; //keep looking + continue; // keep looking } - //you can't put a variable frequency on a partially reserved timer + // you can't put a variable frequency on a partially reserved timer if (variable_frequency) { var_freq_mismatch = true; - continue; //keep looking + continue; // keep looking } - first_time_setup = false; //skip setting up the timer + first_time_setup = false; // skip setting up the timer } - //No problems taken, so set it up + // No problems taken, so set it up self->tim = l_tim; break; } } - //handle valid/invalid timer instance + // handle valid/invalid timer instance if (self->tim != NULL) { - //create instance + // create instance TIMx = mcu_tim_banks[self->tim->tim_index - 1]; - //reserve timer/channel + // reserve timer/channel if (variable_frequency) { reserved_tim[self->tim->tim_index - 1] = 0x0F; } else { @@ -137,7 +137,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, } tim_frequencies[self->tim->tim_index - 1] = frequency; stm_peripherals_timer_reserve(TIMx); - } else { //no match found + } else { // no match found if (tim_chan_taken) { mp_raise_ValueError(translate("No more timers available on this pin.")); } else if (tim_taken_internal) { @@ -161,15 +161,15 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, tim_clock_enable(1 << (self->tim->tim_index - 1)); - //translate channel into handle value + // translate channel into handle value self->channel = 4 * (self->tim->channel_index - 1); - uint32_t prescaler = 0; //prescaler is 15 bit - uint32_t period = 0; //period is 16 bit + uint32_t prescaler = 0; // prescaler is 15 bit + uint32_t period = 0; // period is 16 bit uint32_t source_freq = stm_peripherals_timer_get_source_freq(TIMx); timer_get_optimal_divisors(&period, &prescaler, frequency, source_freq); - //Timer init + // Timer init self->handle.Instance = TIMx; self->handle.Init.Period = period - 1; self->handle.Init.Prescaler = prescaler - 1; @@ -177,14 +177,14 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, self->handle.Init.CounterMode = TIM_COUNTERMODE_UP; self->handle.Init.RepetitionCounter = 0; - //only run init if this is the first instance of this timer + // only run init if this is the first instance of this timer if (first_time_setup) { if (HAL_TIM_PWM_Init(&self->handle) != HAL_OK) { mp_raise_ValueError(translate("Could not initialize timer")); } } - //Channel/PWM init + // Channel/PWM init self->chan_handle.OCMode = TIM_OCMODE_PWM1; self->chan_handle.Pulse = timer_get_internal_duty(duty, period); self->chan_handle.OCPolarity = TIM_OCPOLARITY_HIGH; @@ -215,7 +215,7 @@ void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { } void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { - for(size_t i = 0; i < TIM_BANK_ARRAY_LEN; i++) { + for (size_t i = 0; i < TIM_BANK_ARRAY_LEN; i++) { if (mcu_tim_banks[i] == self->handle.Instance) { never_reset_tim[i] = false; break; @@ -223,15 +223,15 @@ void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { } } -bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { return self->tim == NULL; } -void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { +void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { if (common_hal_pwmio_pwmout_deinited(self)) { return; } - //var freq shuts down entire timer, others just their channel + // var freq shuts down entire timer, others just their channel if (self->variable_frequency) { reserved_tim[self->tim->tim_index - 1] = 0x00; } else { @@ -240,7 +240,7 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { } reset_pin_number(self->tim->pin->port,self->tim->pin->number); - //if reserved timer has no active channels, we can disable it + // if reserved timer has no active channels, we can disable it if (!reserved_tim[self->tim->tim_index - 1]) { tim_frequencies[self->tim->tim_index - 1] = 0x00; stm_peripherals_timer_free(self->handle.Instance); @@ -249,18 +249,18 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self) { self->tim = NULL; } -void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t* self, uint16_t duty) { +void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty) { uint32_t internal_duty_cycle = timer_get_internal_duty(duty, self->period); __HAL_TIM_SET_COMPARE(&self->handle, self->channel, internal_duty_cycle); self->duty_cycle = duty; } -uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t* self) { +uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t *self) { return self->duty_cycle; } -void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t frequency) { - //don't halt setup for the same frequency +void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, uint32_t frequency) { + // don't halt setup for the same frequency if (frequency == self->frequency) { return; } @@ -270,14 +270,14 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t fr uint32_t source_freq = stm_peripherals_timer_get_source_freq(self->handle.Instance); timer_get_optimal_divisors(&period, &prescaler, frequency, source_freq); - //shut down + // shut down HAL_TIM_PWM_Stop(&self->handle, self->channel); - //Only change altered values + // Only change altered values self->handle.Init.Period = period - 1; self->handle.Init.Prescaler = prescaler - 1; - //restart everything, adjusting for new speed + // restart everything, adjusting for new speed if (HAL_TIM_PWM_Init(&self->handle) != HAL_OK) { mp_raise_ValueError(translate("Could not re-init timer")); } @@ -296,10 +296,10 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t fr self->period = period; } -uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t* self) { +uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t *self) { return self->frequency; } -bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t* self) { +bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *self) { return self->variable_frequency; } diff --git a/ports/stm/common-hal/pwmio/PWMOut.h b/ports/stm/common-hal/pwmio/PWMOut.h index 5d8001202c..4cf2b1c670 100644 --- a/ports/stm/common-hal/pwmio/PWMOut.h +++ b/ports/stm/common-hal/pwmio/PWMOut.h @@ -39,8 +39,8 @@ typedef struct { TIM_HandleTypeDef handle; TIM_OC_InitTypeDef chan_handle; const mcu_tim_pin_obj_t *tim; - uint8_t channel: 7; - bool variable_frequency: 1; + uint8_t channel : 7; + bool variable_frequency : 1; uint16_t duty_cycle; uint32_t frequency; uint32_t period; diff --git a/ports/stm/common-hal/rgbmatrix/RGBMatrix.c b/ports/stm/common-hal/rgbmatrix/RGBMatrix.c index 36ed6d0183..4c0ad94b07 100644 --- a/ports/stm/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/stm/common-hal/rgbmatrix/RGBMatrix.c @@ -34,24 +34,24 @@ extern void _PM_IRQ_HANDLER(void); void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self) { - TIM_TypeDef * timer = stm_peripherals_find_timer(); + TIM_TypeDef *timer = stm_peripherals_find_timer(); stm_peripherals_timer_reserve(timer); stm_peripherals_timer_never_reset(timer); return timer; } -void common_hal_rgbmatrix_timer_enable(void* ptr) { - TIM_TypeDef *tim = (TIM_TypeDef*)ptr; +void common_hal_rgbmatrix_timer_enable(void *ptr) { + TIM_TypeDef *tim = (TIM_TypeDef *)ptr; HAL_NVIC_EnableIRQ(stm_peripherals_timer_get_irqnum(tim)); } -void common_hal_rgbmatrix_timer_disable(void* ptr) { - TIM_TypeDef *tim = (TIM_TypeDef*)ptr; +void common_hal_rgbmatrix_timer_disable(void *ptr) { + TIM_TypeDef *tim = (TIM_TypeDef *)ptr; tim->DIER &= ~TIM_DIER_UIE; } -void common_hal_rgbmatrix_timer_free(void* ptr) { - TIM_TypeDef *tim = (TIM_TypeDef*)ptr; +void common_hal_rgbmatrix_timer_free(void *ptr) { + TIM_TypeDef *tim = (TIM_TypeDef *)ptr; stm_peripherals_timer_free(tim); common_hal_rgbmatrix_timer_disable(ptr); } diff --git a/ports/stm/common-hal/rgbmatrix/RGBMatrix.h b/ports/stm/common-hal/rgbmatrix/RGBMatrix.h index 2debb6a76e..cc4b82da0a 100644 --- a/ports/stm/common-hal/rgbmatrix/RGBMatrix.h +++ b/ports/stm/common-hal/rgbmatrix/RGBMatrix.h @@ -30,8 +30,8 @@ #include "shared-module/rgbmatrix/RGBMatrix.h" void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self); -void common_hal_rgbmatrix_timer_enable(void*); -void common_hal_rgbmatrix_timer_disable(void*); -void common_hal_rgbmatrix_timer_free(void*); +void common_hal_rgbmatrix_timer_enable(void *); +void common_hal_rgbmatrix_timer_disable(void *); +void common_hal_rgbmatrix_timer_free(void *); #endif diff --git a/ports/stm/common-hal/sdioio/SDCard.c b/ports/stm/common-hal/sdioio/SDCard.c index de0e8d1119..e09e2e1b3b 100644 --- a/ports/stm/common-hal/sdioio/SDCard.c +++ b/ports/stm/common-hal/sdioio/SDCard.c @@ -40,18 +40,18 @@ STATIC bool reserved_sdio[MP_ARRAY_SIZE(mcu_sdio_banks)]; STATIC bool never_reset_sdio[MP_ARRAY_SIZE(mcu_sdio_banks)]; STATIC const mcu_periph_obj_t *find_pin_function(const mcu_periph_obj_t *table, size_t sz, const mcu_pin_obj_t *pin, int periph_index) { - for(size_t i = 0; iperiph_index && pin == table->pin ) { + for (size_t i = 0; i < sz; i++, table++) { + if (periph_index == table->periph_index && pin == table->pin) { return table; } } return NULL; } -//match pins to SDIO objects +// match pins to SDIO objects STATIC int check_pins(sdioio_sdcard_obj_t *self, - const mcu_pin_obj_t * clock, const mcu_pin_obj_t * command, - uint8_t num_data, mcu_pin_obj_t ** data) { + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, + uint8_t num_data, mcu_pin_obj_t **data) { bool sdio_taken = false; const uint8_t sdio_clock_len = MP_ARRAY_SIZE(mcu_sdio_clock_list); @@ -78,26 +78,26 @@ STATIC int check_pins(sdioio_sdcard_obj_t *self, } const mcu_periph_obj_t *mcu_sdio_data0 = NULL; - if(!(mcu_sdio_data0 = find_pin_function(mcu_sdio_data0_list, sdio_data0_len, data[0], periph_index))) { + if (!(mcu_sdio_data0 = find_pin_function(mcu_sdio_data0_list, sdio_data0_len, data[0], periph_index))) { continue; } const mcu_periph_obj_t *mcu_sdio_data1 = NULL; - if(num_data > 1 && !(mcu_sdio_data1 = find_pin_function(mcu_sdio_data1_list, sdio_data1_len, data[1], periph_index))) { + if (num_data > 1 && !(mcu_sdio_data1 = find_pin_function(mcu_sdio_data1_list, sdio_data1_len, data[1], periph_index))) { continue; } const mcu_periph_obj_t *mcu_sdio_data2 = NULL; - if(num_data > 2 && !(mcu_sdio_data2 = find_pin_function(mcu_sdio_data2_list, sdio_data2_len, data[2], periph_index))) { + if (num_data > 2 && !(mcu_sdio_data2 = find_pin_function(mcu_sdio_data2_list, sdio_data2_len, data[2], periph_index))) { continue; } const mcu_periph_obj_t *mcu_sdio_data3 = NULL; - if(num_data > 3 && !(mcu_sdio_data3 = find_pin_function(mcu_sdio_data3_list, sdio_data3_len, data[3], periph_index))) { + if (num_data > 3 && !(mcu_sdio_data3 = find_pin_function(mcu_sdio_data3_list, sdio_data3_len, data[3], periph_index))) { continue; } - if (reserved_sdio[periph_index-1]) { + if (reserved_sdio[periph_index - 1]) { sdio_taken = true; continue; } @@ -121,16 +121,16 @@ STATIC int check_pins(sdioio_sdcard_obj_t *self, void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, - const mcu_pin_obj_t * clock, const mcu_pin_obj_t * command, - uint8_t num_data, mcu_pin_obj_t ** data, uint32_t frequency) { + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, + uint8_t num_data, mcu_pin_obj_t **data, uint32_t frequency) { int periph_index = check_pins(self, clock, command, num_data, data); - SDIO_TypeDef * SDIOx = mcu_sdio_banks[periph_index - 1]; + SDIO_TypeDef *SDIOx = mcu_sdio_banks[periph_index - 1]; GPIO_InitTypeDef GPIO_InitStruct = {0}; /* Configure data pins */ - for (int i=0; inumber); GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -186,7 +186,7 @@ void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, common_hal_mcu_pin_claim(clock); common_hal_mcu_pin_claim(command); - for (int i=0; ihandle); HAL_Delay(1); }; @@ -293,7 +293,7 @@ void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { reset_mcu_periph(self->clock); self->command = NULL; - for (size_t i=0; idata); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(self->data); i++) { reset_mcu_periph(self->data[i]); self->data[i] = NULL; } @@ -313,13 +313,13 @@ void common_hal_sdioio_sdcard_never_reset(sdioio_sdcard_obj_t *self) { never_reset_mcu_periph(self->command); never_reset_mcu_periph(self->clock); - for (size_t i=0; idata); i++) { + for (size_t i = 0; i < MP_ARRAY_SIZE(self->data); i++) { never_reset_mcu_periph(self->data[i]); } } void sdioio_reset() { - for (size_t i=0; i 1) the timer clock is twice its // respective APB clock. See DM00031020 Rev 4, page 115. -uint32_t stm_peripherals_timer_get_source_freq(TIM_TypeDef * timer) { + uint32_t stm_peripherals_timer_get_source_freq(TIM_TypeDef *timer) { size_t tim_id = stm_peripherals_timer_get_index(timer); uint32_t source, clk_div; if (tim_id == 1 || (8 <= tim_id && tim_id <= 11)) { @@ -158,12 +158,12 @@ uint32_t stm_peripherals_timer_get_source_freq(TIM_TypeDef * timer) { return source; } -size_t stm_peripherals_timer_get_irqnum(TIM_TypeDef * instance) { + size_t stm_peripherals_timer_get_irqnum(TIM_TypeDef *instance) { size_t tim_id = stm_peripherals_timer_get_index(instance); return irq_map[tim_id]; } -void timers_reset(void) { + void timers_reset(void) { uint16_t never_reset_mask = 0x00; for (size_t i = 0; i < MP_ARRAY_SIZE(mcu_tim_banks); i++) { if (!stm_timer_never_reset[i]) { @@ -175,18 +175,18 @@ void timers_reset(void) { tim_clock_disable(ALL_CLOCKS & ~(never_reset_mask)); } -TIM_TypeDef * stm_peripherals_find_timer(void) { + TIM_TypeDef *stm_peripherals_find_timer(void) { // Check for timers on pins outside the package size for (size_t i = 0; i < MP_ARRAY_SIZE(mcu_tim_banks); i++) { bool timer_in_package = false; // Find each timer instance on the given bank for (size_t j = 0; j < MP_ARRAY_SIZE(mcu_tim_pin_list); j++) { // If a pin is claimed, we skip it - if ( (mcu_tim_pin_list[j].tim_index == i + 1) - && (common_hal_mcu_pin_is_free(mcu_tim_pin_list[j].pin) == true) ) { + if ((mcu_tim_pin_list[j].tim_index == i + 1) + && (common_hal_mcu_pin_is_free(mcu_tim_pin_list[j].pin) == true)) { // Search whether any pins in the package array match it for (size_t k = 0; k < mcu_pin_globals.map.alloc; k++) { - if ( (mcu_tim_pin_list[j].pin == (mcu_pin_obj_t*)(mcu_pin_globals.map.table[k].value)) ) { + if ((mcu_tim_pin_list[j].pin == (mcu_pin_obj_t *)(mcu_pin_globals.map.table[k].value))) { timer_in_package = true; } } @@ -198,7 +198,7 @@ TIM_TypeDef * stm_peripherals_find_timer(void) { return mcu_tim_banks[i]; } } - //TODO: secondary search for timers outside the pins in the board profile + // TODO: secondary search for timers outside the pins in the board profile // Work backwards - higher index timers have fewer pin allocations for (size_t i = (MP_ARRAY_SIZE(mcu_tim_banks) - 1); i >= 0; i--) { @@ -210,7 +210,7 @@ TIM_TypeDef * stm_peripherals_find_timer(void) { return NULL; } -void stm_peripherals_timer_preinit(TIM_TypeDef * instance, uint8_t prio, void (*callback)(void)) { + void stm_peripherals_timer_preinit(TIM_TypeDef *instance, uint8_t prio, void (*callback)(void)) { size_t tim_idx = stm_peripherals_timer_get_index(instance); stm_timer_callback[tim_idx] = callback; tim_clock_enable(1 << tim_idx); @@ -218,16 +218,16 @@ void stm_peripherals_timer_preinit(TIM_TypeDef * instance, uint8_t prio, void (* HAL_NVIC_EnableIRQ(irq_map[tim_idx]); } -void stm_peripherals_timer_reserve(TIM_TypeDef * instance) { + void stm_peripherals_timer_reserve(TIM_TypeDef *instance) { size_t tim_idx = stm_peripherals_timer_get_index(instance); stm_timer_reserved[tim_idx] = true; } -void stm_peripherals_timer_set_callback(void(*callback)(void), TIM_TypeDef * timer) { + void stm_peripherals_timer_set_callback(void (*callback)(void), TIM_TypeDef *timer) { stm_timer_callback[stm_peripherals_timer_get_index(timer)] = callback; } -void stm_peripherals_timer_free(TIM_TypeDef * instance) { + void stm_peripherals_timer_free(TIM_TypeDef *instance) { size_t tim_idx = stm_peripherals_timer_get_index(instance); HAL_NVIC_DisableIRQ(irq_map[tim_idx]); stm_timer_callback[tim_idx] = NULL; @@ -236,24 +236,24 @@ void stm_peripherals_timer_free(TIM_TypeDef * instance) { stm_timer_never_reset[tim_idx] = false; } -void stm_peripherals_timer_never_reset(TIM_TypeDef * instance) { + void stm_peripherals_timer_never_reset(TIM_TypeDef *instance) { size_t tim_idx = stm_peripherals_timer_get_index(instance); stm_timer_never_reset[tim_idx] = true; } -void stm_peripherals_timer_reset_ok(TIM_TypeDef * instance) { + void stm_peripherals_timer_reset_ok(TIM_TypeDef *instance) { size_t tim_idx = stm_peripherals_timer_get_index(instance); stm_timer_never_reset[tim_idx] = false; } -bool stm_peripherals_timer_is_never_reset(TIM_TypeDef * instance){ + bool stm_peripherals_timer_is_never_reset(TIM_TypeDef *instance) { size_t tim_idx = stm_peripherals_timer_get_index(instance); return stm_timer_never_reset[tim_idx]; } -bool stm_peripherals_timer_is_reserved(TIM_TypeDef * instance) { + bool stm_peripherals_timer_is_reserved(TIM_TypeDef *instance) { size_t tim_idx = stm_peripherals_timer_get_index(instance); return stm_timer_reserved[tim_idx]; } -size_t stm_peripherals_timer_get_index(TIM_TypeDef * instance) { + size_t stm_peripherals_timer_get_index(TIM_TypeDef *instance) { for (size_t i = 0; i < MP_ARRAY_SIZE(mcu_tim_banks); i++) { if (instance == mcu_tim_banks[i]) { return i; @@ -262,7 +262,7 @@ size_t stm_peripherals_timer_get_index(TIM_TypeDef * instance) { return ~(size_t)0; } -void tim_clock_enable(uint16_t mask) { + void tim_clock_enable(uint16_t mask) { #ifdef TIM1 if (mask & (1 << 0)) { __HAL_RCC_TIM1_CLK_ENABLE(); @@ -288,7 +288,7 @@ void tim_clock_enable(uint16_t mask) { __HAL_RCC_TIM5_CLK_ENABLE(); } #endif - //6 and 7 are reserved ADC timers + // 6 and 7 are reserved ADC timers #ifdef TIM8 if (mask & (1 << 7)) { __HAL_RCC_TIM8_CLK_ENABLE(); @@ -326,7 +326,7 @@ void tim_clock_enable(uint16_t mask) { #endif } -void tim_clock_disable(uint16_t mask) { + void tim_clock_disable(uint16_t mask) { #ifdef TIM1 if (mask & (1 << 0)) { __HAL_RCC_TIM1_CLK_DISABLE(); @@ -352,7 +352,7 @@ void tim_clock_disable(uint16_t mask) { __HAL_RCC_TIM5_CLK_DISABLE(); } #endif - //6 and 7 are reserved ADC timers + // 6 and 7 are reserved ADC timers #ifdef TIM8 if (mask & (1 << 7)) { __HAL_RCC_TIM8_CLK_DISABLE(); @@ -390,65 +390,65 @@ void tim_clock_disable(uint16_t mask) { #endif } -STATIC void callback_router(size_t index) { + STATIC void callback_router(size_t index) { if (stm_timer_callback[index - 1]) { (*stm_timer_callback[index - 1])(); } } -void TIM1_CC_IRQHandler(void) { // Advanced timer + void TIM1_CC_IRQHandler(void) { // Advanced timer callback_router(1); } -void TIM2_IRQHandler(void) { + void TIM2_IRQHandler(void) { callback_router(2); } -void TIM3_IRQHandler(void) { + void TIM3_IRQHandler(void) { callback_router(3); } -void TIM4_IRQHandler(void) { + void TIM4_IRQHandler(void) { callback_router(4); } -void TIM5_IRQHandler(void) { + void TIM5_IRQHandler(void) { callback_router(5); } -void TIM6_DAC_IRQHandler(void) { // Basic timer (DAC) + void TIM6_DAC_IRQHandler(void) { // Basic timer (DAC) callback_router(6); } -void TIM7_IRQHandler(void) { // Basic timer + void TIM7_IRQHandler(void) { // Basic timer callback_router(7); } -void TIM8_CC_IRQHandler(void) { // Advanced timer + void TIM8_CC_IRQHandler(void) { // Advanced timer callback_router(8); } // Advanced timer interrupts are currently unused. -void TIM1_BRK_TIM9_IRQHandler(void) { + void TIM1_BRK_TIM9_IRQHandler(void) { callback_router(9); } -void TIM1_UP_TIM10_IRQHandler(void) { + void TIM1_UP_TIM10_IRQHandler(void) { callback_router(10); } -void TIM1_TRG_COM_TIM11_IRQHandler(void) { + void TIM1_TRG_COM_TIM11_IRQHandler(void) { callback_router(11); } -void TIM8_BRK_TIM12_IRQHandler(void) { + void TIM8_BRK_TIM12_IRQHandler(void) { callback_router(12); } -void TIM8_UP_TIM13_IRQHandler(void) { + void TIM8_UP_TIM13_IRQHandler(void) { callback_router(13); } -void TIM8_TRG_COM_TIM14_IRQHandler(void) { + void TIM8_TRG_COM_TIM14_IRQHandler(void) { callback_router(14); } #if (CPY_STM32H7) -void TIM15_IRQHandler(void) { + void TIM15_IRQHandler(void) { callback_router(15); } -void TIM16_IRQHandler(void) { + void TIM16_IRQHandler(void) { callback_router(16); } -void TIM17_IRQHandler(void) { + void TIM17_IRQHandler(void) { callback_router(17); } #endif diff --git a/ports/stm/peripherals/timers.h b/ports/stm/peripherals/timers.h index c4b6c63673..26cba88a03 100644 --- a/ports/stm/peripherals/timers.h +++ b/ports/stm/peripherals/timers.h @@ -32,15 +32,15 @@ void tim_clock_enable(uint16_t mask); void tim_clock_disable(uint16_t mask); -uint32_t stm_peripherals_timer_get_source_freq(TIM_TypeDef * timer); -size_t stm_peripherals_timer_get_irqnum(TIM_TypeDef * instance); +uint32_t stm_peripherals_timer_get_source_freq(TIM_TypeDef *timer); +size_t stm_peripherals_timer_get_irqnum(TIM_TypeDef *instance); void timers_reset(void); -TIM_TypeDef * stm_peripherals_find_timer(void); -void stm_peripherals_timer_preinit(TIM_TypeDef * instance, uint8_t prio, void (*callback)(void)); -void stm_peripherals_timer_reserve(TIM_TypeDef * instance); -void stm_peripherals_timer_free(TIM_TypeDef * instance); -void stm_peripherals_timer_never_reset(TIM_TypeDef * instance); -void stm_peripherals_timer_reset_ok(TIM_TypeDef * instance); -bool stm_peripherals_timer_is_never_reset(TIM_TypeDef * instance); -bool stm_peripherals_timer_is_reserved(TIM_TypeDef * instance); -size_t stm_peripherals_timer_get_index(TIM_TypeDef * instance); +TIM_TypeDef *stm_peripherals_find_timer(void); +void stm_peripherals_timer_preinit(TIM_TypeDef *instance, uint8_t prio, void (*callback)(void)); +void stm_peripherals_timer_reserve(TIM_TypeDef *instance); +void stm_peripherals_timer_free(TIM_TypeDef *instance); +void stm_peripherals_timer_never_reset(TIM_TypeDef *instance); +void stm_peripherals_timer_reset_ok(TIM_TypeDef *instance); +bool stm_peripherals_timer_is_never_reset(TIM_TypeDef *instance); +bool stm_peripherals_timer_is_reserved(TIM_TypeDef *instance); +size_t stm_peripherals_timer_get_index(TIM_TypeDef *instance); diff --git a/ports/stm/supervisor/internal_flash.c b/ports/stm/supervisor/internal_flash.c index 78ee4f3e60..5600810138 100644 --- a/ports/stm/supervisor/internal_flash.c +++ b/ports/stm/supervisor/internal_flash.c @@ -52,47 +52,47 @@ typedef struct { #if defined(STM32F4) - STATIC const flash_layout_t flash_layout[] = { - { 0x08000000, 0x04000, 4 }, - { 0x08010000, 0x10000, 1 }, - { 0x08020000, 0x20000, 3 }, - #if defined(FLASH_SECTOR_8) - { 0x08080000, 0x20000, 4 }, - #endif - #if defined(FLASH_SECTOR_12) - { 0x08100000, 0x04000, 4 }, - { 0x08110000, 0x10000, 1 }, - { 0x08120000, 0x20000, 7 }, - #endif - }; - STATIC uint8_t _flash_cache[0x4000] __attribute__((aligned(4))); +STATIC const flash_layout_t flash_layout[] = { + { 0x08000000, 0x04000, 4 }, + { 0x08010000, 0x10000, 1 }, + { 0x08020000, 0x20000, 3 }, + #if defined(FLASH_SECTOR_8) + { 0x08080000, 0x20000, 4 }, + #endif + #if defined(FLASH_SECTOR_12) + { 0x08100000, 0x04000, 4 }, + { 0x08110000, 0x10000, 1 }, + { 0x08120000, 0x20000, 7 }, + #endif +}; +STATIC uint8_t _flash_cache[0x4000] __attribute__((aligned(4))); #elif defined(STM32F7) - // FLASH_FLAG_PGSERR (Programming Sequence Error) was renamed to - // FLASH_FLAG_ERSERR (Erasing Sequence Error) in STM32F7 +// FLASH_FLAG_PGSERR (Programming Sequence Error) was renamed to +// FLASH_FLAG_ERSERR (Erasing Sequence Error) in STM32F7 #define FLASH_FLAG_PGSERR FLASH_FLAG_ERSERR #if defined(STM32F722xx) || defined(STM32F723xx) || defined(STM32F732xx) || defined(STM32F733xx) - static const flash_layout_t flash_layout[] = { - { 0x08000000, 0x04000, 4 }, - { 0x08010000, 0x10000, 1 }, - { 0x08020000, 0x20000, 3 }, - }; - STATIC uint8_t _flash_cache[0x4000] __attribute__((aligned(4))); +static const flash_layout_t flash_layout[] = { + { 0x08000000, 0x04000, 4 }, + { 0x08010000, 0x10000, 1 }, + { 0x08020000, 0x20000, 3 }, +}; +STATIC uint8_t _flash_cache[0x4000] __attribute__((aligned(4))); #else - static const flash_layout_t flash_layout[] = { - { 0x08000000, 0x08000, 4 }, - { 0x08020000, 0x20000, 1 }, - { 0x08040000, 0x40000, 3 }, - }; - STATIC uint8_t _flash_cache[0x8000] __attribute__((aligned(4))); +static const flash_layout_t flash_layout[] = { + { 0x08000000, 0x08000, 4 }, + { 0x08020000, 0x20000, 1 }, + { 0x08040000, 0x40000, 3 }, +}; +STATIC uint8_t _flash_cache[0x8000] __attribute__((aligned(4))); #endif #elif defined(STM32H7) - STATIC const flash_layout_t flash_layout[] = { - { 0x08000000, 0x20000, 16 }, - }; - STATIC uint8_t _flash_cache[0x20000] __attribute__((aligned(4))); +STATIC const flash_layout_t flash_layout[] = { + { 0x08000000, 0x20000, 16 }, +}; +STATIC uint8_t _flash_cache[0x20000] __attribute__((aligned(4))); #else #error Unsupported processor @@ -125,7 +125,7 @@ STATIC uint32_t get_bank(uint32_t addr) { } #endif -//Return the sector of a given flash address. +// Return the sector of a given flash address. uint32_t flash_get_sector_info(uint32_t addr, uint32_t *start_addr, uint32_t *size) { if (addr >= flash_layout[0].base_address) { uint32_t sector_index = 0; @@ -162,13 +162,15 @@ uint32_t supervisor_flash_get_block_count(void) { } void port_internal_flash_flush(void) { - if (_cache_flash_addr == NO_CACHE) return; + if (_cache_flash_addr == NO_CACHE) { + return; + } #if defined(STM32H7) __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_ALL_ERRORS_BANK1 | FLASH_FLAG_ALL_ERRORS_BANK2); #else __HAL_FLASH_CLEAR_FLAG(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | - FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); + FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR | FLASH_FLAG_PGSERR); #endif // set up for erase @@ -200,13 +202,13 @@ void port_internal_flash_flush(void) { reset_into_safe_mode(FLASH_WRITE_FAIL); } - uint32_t * cache_addr = (uint32_t*)_flash_cache; + uint32_t *cache_addr = (uint32_t *)_flash_cache; #if defined(STM32H7) for (uint32_t i = 0; i < (sector_size / 32); i++) { // Note that the STM32H7 HAL interface differs by taking an address, not 64 bit data if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_FLASHWORD, sector_start_addr, - (uint32_t)cache_addr) != HAL_OK) { + (uint32_t)cache_addr) != HAL_OK) { // error occurred during flash write HAL_FLASH_Lock(); // lock the flash reset_into_safe_mode(FLASH_WRITE_FAIL); @@ -220,7 +222,7 @@ void port_internal_flash_flush(void) { // program the flash word by word for (uint32_t i = 0; i < sector_size / 4; i++) { if (HAL_FLASH_Program(FLASH_TYPEPROGRAM_WORD, sector_start_addr, - (uint64_t)*cache_addr) != HAL_OK) { + (uint64_t)*cache_addr) != HAL_OK) { // error occurred during flash write HAL_FLASH_Lock(); // lock the flash reset_into_safe_mode(FLASH_WRITE_FAIL); @@ -257,17 +259,17 @@ mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t n uint32_t sector_start_addr; flash_get_sector_info(src, §or_start_addr, §or_size); // Count how many blocks are left in the sector - uint32_t count = (sector_size - (src - sector_start_addr))/FILESYSTEM_BLOCK_SIZE; + uint32_t count = (sector_size - (src - sector_start_addr)) / FILESYSTEM_BLOCK_SIZE; count = MIN(num_blocks, count); if (count < num_blocks && _cache_flash_addr == sector_start_addr) { // Read is contained in the cache, so just read cache - memcpy(dest, (_flash_cache + (src-sector_start_addr)), FILESYSTEM_BLOCK_SIZE*num_blocks); + memcpy(dest, (_flash_cache + (src - sector_start_addr)), FILESYSTEM_BLOCK_SIZE * num_blocks); } else { // The read spans multiple sectors or is in another sector // Must write out anything in cache before trying to read. supervisor_flash_flush(); - memcpy(dest, (uint8_t*) src, FILESYSTEM_BLOCK_SIZE*num_blocks); + memcpy(dest, (uint8_t *)src, FILESYSTEM_BLOCK_SIZE * num_blocks); } return 0; // success @@ -294,7 +296,7 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t block_num, } // Find how many blocks are left in the sector - uint32_t count = (sector_size - (dest - sector_start_addr))/FILESYSTEM_BLOCK_SIZE; + uint32_t count = (sector_size - (dest - sector_start_addr)) / FILESYSTEM_BLOCK_SIZE; count = MIN(num_blocks, count); if (_cache_flash_addr != sector_start_addr) { @@ -308,11 +310,11 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t block_num, } // Overwrite part or all of the sector cache with the src data. - memcpy(_flash_cache + (dest-sector_start_addr), src, count * FILESYSTEM_BLOCK_SIZE); + memcpy(_flash_cache + (dest - sector_start_addr), src, count * FILESYSTEM_BLOCK_SIZE); // adjust for next run - block_num += count; - src += count * FILESYSTEM_BLOCK_SIZE; + block_num += count; + src += count * FILESYSTEM_BLOCK_SIZE; num_blocks -= count; } diff --git a/ports/stm/supervisor/internal_flash.h b/ports/stm/supervisor/internal_flash.h index 19ae03e0b3..106ff6c540 100644 --- a/ports/stm/supervisor/internal_flash.h +++ b/ports/stm/supervisor/internal_flash.h @@ -34,15 +34,15 @@ #include "py/mpconfig.h" #ifdef STM32F401xE -#define STM32_FLASH_SIZE 0x80000 //512KiB -#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 //48KiB +#define STM32_FLASH_SIZE 0x80000 // 512KiB +#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 // 48KiB #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08004000 #endif #ifdef STM32F411xE -#define STM32_FLASH_SIZE 0x80000 //512KiB +#define STM32_FLASH_SIZE 0x80000 // 512KiB #ifndef INTERNAL_FLASH_FILESYSTEM_SIZE - #define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 //48KiB + #define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 // 48KiB #endif #ifndef INTERNAL_FLASH_FILESYSTEM_START_ADDR #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08004000 @@ -50,45 +50,45 @@ #endif #ifdef STM32F412Zx -#define STM32_FLASH_SIZE 0x100000 //1MB -#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 //48KiB +#define STM32_FLASH_SIZE 0x100000 // 1MB +#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 // 48KiB #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08004000 #endif #ifdef STM32F405xx -#define STM32_FLASH_SIZE 0x100000 //1MB -#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 //48KiB +#define STM32_FLASH_SIZE 0x100000 // 1MB +#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 // 48KiB #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08004000 #endif #ifdef STM32F407xx -#define STM32_FLASH_SIZE 0x100000 //1MB -#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 //48KiB +#define STM32_FLASH_SIZE 0x100000 // 1MB +#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 // 48KiB #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08004000 #endif /* Note this applies to STM32F769xG only, STM32F746xE has 512KB */ #ifdef STM32F746xx -#define STM32_FLASH_SIZE 0x100000 //1MB -#define INTERNAL_FLASH_FILESYSTEM_SIZE 0x18000 //96KiB +#define STM32_FLASH_SIZE 0x100000 // 1MB +#define INTERNAL_FLASH_FILESYSTEM_SIZE 0x18000 // 96KiB #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08008000 #endif #ifdef STM32F767xx -#define STM32_FLASH_SIZE 0x200000 //2MB -#define INTERNAL_FLASH_FILESYSTEM_SIZE 0x18000 //96KiB +#define STM32_FLASH_SIZE 0x200000 // 2MB +#define INTERNAL_FLASH_FILESYSTEM_SIZE 0x18000 // 96KiB #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08008000 #endif #ifdef STM32H743xx -#define STM32_FLASH_SIZE 0x200000 //2MB -#define INTERNAL_FLASH_FILESYSTEM_SIZE 0x60000 //384KiB +#define STM32_FLASH_SIZE 0x200000 // 2MB +#define INTERNAL_FLASH_FILESYSTEM_SIZE 0x60000 // 384KiB #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08020000 #endif #define INTERNAL_FLASH_FILESYSTEM_NUM_BLOCKS (INTERNAL_FLASH_FILESYSTEM_SIZE / FILESYSTEM_BLOCK_SIZE) -#define STM32_FLASH_OFFSET 0x8000000 //All STM32 chips map to this flash location +#define STM32_FLASH_OFFSET 0x8000000 // All STM32 chips map to this flash location #define INTERNAL_FLASH_SYSTICK_MASK (0x1ff) // 512ms #define INTERNAL_FLASH_IDLE_TICK(tick) (((tick) & INTERNAL_FLASH_SYSTICK_MASK) == 2) diff --git a/ports/stm/supervisor/port.c b/ports/stm/supervisor/port.c index 3103a07160..4a7583eb21 100644 --- a/ports/stm/supervisor/port.c +++ b/ports/stm/supervisor/port.c @@ -98,14 +98,14 @@ extern void SystemInit(void); // This replaces the Reset_Handler in gcc/startup_*.s, calls SystemInit from system_*.c __attribute__((used, naked)) void Reset_Handler(void) { __disable_irq(); - __set_MSP((uint32_t) &_ld_stack_top); + __set_MSP((uint32_t)&_ld_stack_top); /* Disable MPU */ ARM_MPU_Disable(); // Copy all of the itcm code to run from ITCM. Do this while the MPU is disabled because we write // protect it. - for (uint32_t i = 0; i < ((size_t) &_ld_itcm_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_itcm_size) / 4; i++) { (&_ld_itcm_destination)[i] = (&_ld_itcm_flash_copy)[i]; } @@ -133,22 +133,22 @@ __attribute__((used, naked)) void Reset_Handler(void) { ARM_MPU_Enable(MPU_CTRL_PRIVDEFENA_Msk); // Copy all of the data to run from DTCM. - for (uint32_t i = 0; i < ((size_t) &_ld_dtcm_data_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_dtcm_data_size) / 4; i++) { (&_ld_dtcm_data_destination)[i] = (&_ld_dtcm_data_flash_copy)[i]; } // Clear DTCM bss. - for (uint32_t i = 0; i < ((size_t) &_ld_dtcm_bss_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_dtcm_bss_size) / 4; i++) { (&_ld_dtcm_bss_start)[i] = 0; } // Copy all of the data to run from D1 RAM. - for (uint32_t i = 0; i < ((size_t) &_ld_d1_ram_data_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_d1_ram_data_size) / 4; i++) { (&_ld_d1_ram_data_destination)[i] = (&_ld_d1_ram_data_flash_copy)[i]; } // Clear D1 RAM bss. - for (uint32_t i = 0; i < ((size_t) &_ld_d1_ram_bss_size) / 4; i++) { + for (uint32_t i = 0; i < ((size_t)&_ld_d1_ram_bss_size) / 4; i++) { (&_ld_d1_ram_bss_start)[i] = 0; } @@ -156,7 +156,7 @@ __attribute__((used, naked)) void Reset_Handler(void) { __enable_irq(); main(); } -#endif //end H7 specific code +#endif // end H7 specific code // Low power clock variables static volatile uint32_t systick_ms; @@ -173,7 +173,7 @@ safe_mode_t port_init(void) { __HAL_RCC_SYSCFG_CLK_ENABLE(); #if (CPY_STM32F4) - __HAL_RCC_PWR_CLK_ENABLE(); + __HAL_RCC_PWR_CLK_ENABLE(); #endif stm32_peripherals_clocks_init(); @@ -229,24 +229,24 @@ void SysTick_Handler(void) { void reset_port(void) { reset_all_pins(); -#if CIRCUITPY_BUSIO + #if CIRCUITPY_BUSIO i2c_reset(); spi_reset(); uart_reset(); -#endif -#if CIRCUITPY_SDIOIO + #endif + #if CIRCUITPY_SDIOIO sdioio_reset(); -#endif -#if CIRCUITPY_PULSEIO || CIRCUITPY_PWMIO + #endif + #if CIRCUITPY_PULSEIO || CIRCUITPY_PWMIO timers_reset(); -#endif -#if CIRCUITPY_PULSEIO + #endif + #if CIRCUITPY_PULSEIO pulseout_reset(); pulsein_reset(); -#endif -#if CIRCUITPY_PWMIO + #endif + #if CIRCUITPY_PWMIO pwmout_reset(); -#endif + #endif } void reset_to_bootloader(void) { @@ -290,35 +290,31 @@ uint32_t port_get_saved_word(void) { return _ebss; } -__attribute__((used)) void MemManage_Handler(void) -{ +__attribute__((used)) void MemManage_Handler(void) { reset_into_safe_mode(MEM_MANAGE); while (true) { - asm("nop;"); + asm ("nop;"); } } -__attribute__((used)) void BusFault_Handler(void) -{ +__attribute__((used)) void BusFault_Handler(void) { reset_into_safe_mode(MEM_MANAGE); while (true) { - asm("nop;"); + asm ("nop;"); } } -__attribute__((used)) void UsageFault_Handler(void) -{ +__attribute__((used)) void UsageFault_Handler(void) { reset_into_safe_mode(MEM_MANAGE); while (true) { - asm("nop;"); + asm ("nop;"); } } -__attribute__((used)) void HardFault_Handler(void) -{ +__attribute__((used)) void HardFault_Handler(void) { reset_into_safe_mode(HARD_CRASH); while (true) { - asm("nop;"); + asm ("nop;"); } } @@ -328,7 +324,7 @@ volatile uint32_t seconds_to_date = 0; volatile uint32_t cached_date = 0; volatile uint32_t seconds_to_minute = 0; volatile uint32_t cached_hours_minutes = 0; -uint64_t port_get_raw_ticks(uint8_t* subticks) { +uint64_t port_get_raw_ticks(uint8_t *subticks) { // Disable IRQs to ensure we read all of the RTC registers as close in time as possible. Read // SSR twice to make sure we didn't read across a tick. __disable_irq(); @@ -372,7 +368,7 @@ uint64_t port_get_raw_ticks(uint8_t* subticks) { *subticks = subseconds % 32; } - uint64_t raw_ticks = ((uint64_t) 1024) * (seconds_to_date + seconds_to_minute + seconds) + subseconds / 32; + uint64_t raw_ticks = ((uint64_t)1024) * (seconds_to_date + seconds_to_minute + seconds) + subseconds / 32; return raw_ticks; } @@ -424,7 +420,7 @@ void port_interrupt_after_ticks(uint32_t ticks) { } alarm.AlarmTime.SubSeconds = rtc_clock_frequency - 1 - - ((raw_ticks % 1024) * 32); + ((raw_ticks % 1024) * 32); alarm.AlarmTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; alarm.AlarmTime.StoreOperation = RTC_STOREOPERATION_SET; // Masking here means that the bits are ignored so we set none of them. @@ -438,9 +434,9 @@ void port_interrupt_after_ticks(uint32_t ticks) { void port_idle_until_interrupt(void) { // Clear the FPU interrupt because it can prevent us from sleeping. - if (__get_FPSCR() & ~(0x9f)) { - __set_FPSCR(__get_FPSCR() & ~(0x9f)); - (void) __get_FPSCR(); + if (__get_FPSCR() & ~(0x9f)) { + __set_FPSCR(__get_FPSCR() & ~(0x9f)); + (void)__get_FPSCR(); } if (alarmed_already) { return; @@ -450,7 +446,6 @@ void port_idle_until_interrupt(void) { // Required by __libc_init_array in startup code if we are compiling using // -nostdlib/-nostartfiles. -void _init(void) -{ +void _init(void) { } diff --git a/ports/stm/supervisor/qspi_flash.c b/ports/stm/supervisor/qspi_flash.c index f3915273b3..330e27dbd2 100644 --- a/ports/stm/supervisor/qspi_flash.c +++ b/ports/stm/supervisor/qspi_flash.c @@ -31,9 +31,9 @@ #include #include "py/mpconfig.h" // for EXTERNAL_FLASH_QSPI_DUAL -//#include "nrfx_qspi.h" +// #include "nrfx_qspi.h" -//#include "shared-bindings/microcontroller/__init__.h" +// #include "shared-bindings/microcontroller/__init__.h" #include "supervisor/shared/external_flash/common_commands.h" #include "supervisor/shared/external_flash/qspi_flash.h" @@ -47,10 +47,10 @@ bool spi_flash_command(uint8_t command) { // .wipwait = false, // .wren = false // }; - return false; //nrfx_qspi_cinstr_xfer(&cinstr_cfg, NULL, NULL) == NRFX_SUCCESS; + return false; // nrfx_qspi_cinstr_xfer(&cinstr_cfg, NULL, NULL) == NRFX_SUCCESS; } -bool spi_flash_read_command(uint8_t command, uint8_t* response, uint32_t length) { +bool spi_flash_read_command(uint8_t command, uint8_t *response, uint32_t length) { // nrf_qspi_cinstr_conf_t cinstr_cfg = { // .opcode = command, // .length = length + 1, @@ -64,7 +64,7 @@ bool spi_flash_read_command(uint8_t command, uint8_t* response, uint32_t length) } -bool spi_flash_write_command(uint8_t command, uint8_t* data, uint32_t length) { +bool spi_flash_write_command(uint8_t command, uint8_t *data, uint32_t length) { // nrf_qspi_cinstr_conf_t cinstr_cfg = { // .opcode = command, // .length = length + 1, @@ -85,12 +85,12 @@ bool spi_flash_sector_command(uint8_t command, uint32_t address) { return false; } -bool spi_flash_write_data(uint32_t address, uint8_t* data, uint32_t length) { +bool spi_flash_write_data(uint32_t address, uint8_t *data, uint32_t length) { // return nrfx_qspi_write(data, length, address) == NRFX_SUCCESS; return false; } -bool spi_flash_read_data(uint32_t address, uint8_t* data, uint32_t length) { +bool spi_flash_read_data(uint32_t address, uint8_t *data, uint32_t length) { // return nrfx_qspi_read(data, length, address) == NRFX_SUCCESS; return false; } @@ -139,7 +139,7 @@ void spi_flash_init(void) { // nrfx_qspi_init(&qspi_cfg, NULL, NULL); } -void spi_flash_init_device(const external_flash_device* device) { +void spi_flash_init_device(const external_flash_device *device) { // check_quad_enable(device); // // Switch to single output line if the device doesn't support quad programs. diff --git a/ports/stm/supervisor/serial.c b/ports/stm/supervisor/serial.c index 3a058ed2e1..ac6f69bbb4 100644 --- a/ports/stm/supervisor/serial.c +++ b/ports/stm/supervisor/serial.c @@ -42,8 +42,7 @@ void serial_init(void) { huart2.Init.Mode = UART_MODE_TX_RX; huart2.Init.HwFlowCtl = UART_HWCONTROL_NONE; huart2.Init.OverSampling = UART_OVERSAMPLING_16; - if (HAL_UART_Init(&huart2) == HAL_OK) - { + if (HAL_UART_Init(&huart2) == HAL_OK) { stm32f4_peripherals_status_led(1,1); } } @@ -62,7 +61,7 @@ bool serial_bytes_available(void) { return __HAL_UART_GET_FLAG(&huart2, UART_FLAG_RXNE); } -void serial_write(const char* text) { +void serial_write(const char *text) { serial_write_substring(text, strlen(text)); } @@ -70,5 +69,5 @@ void serial_write_substring(const char *text, uint32_t len) { if (len == 0) { return; } - HAL_UART_Transmit(&huart2, (uint8_t*)text, len, 5000); + HAL_UART_Transmit(&huart2, (uint8_t *)text, len, 5000); } diff --git a/ports/stm/supervisor/usb.c b/ports/stm/supervisor/usb.c index c0e012cc62..906d07f737 100644 --- a/ports/stm/supervisor/usb.c +++ b/ports/stm/supervisor/usb.c @@ -37,33 +37,33 @@ STATIC void init_usb_vbus_sense(void) { -#if (BOARD_NO_VBUS_SENSE) + #if (BOARD_NO_VBUS_SENSE) // Disable VBUS sensing #ifdef USB_OTG_GCCFG_VBDEN - // Deactivate VBUS Sensing B - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; + // Deactivate VBUS Sensing B + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; - // B-peripheral session valid override enable - USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; - USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; + // B-peripheral session valid override enable + USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; + USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; #else - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSBSEN; - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSASEN; + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSBSEN; + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSASEN; #endif -#else + #else // Enable VBUS hardware sensing #ifdef USB_OTG_GCCFG_VBDEN - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBDEN; #else - USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; - USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; // B Device sense + USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_NOVBUSSENS; + USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_VBUSBSEN; // B Device sense + #endif #endif -#endif } void init_usb_hardware(void) { - //TODO: if future chips overload this with options, move to peripherals management. + // TODO: if future chips overload this with options, move to peripherals management. GPIO_InitTypeDef GPIO_InitStruct = {0}; /**USB_OTG_FS GPIO Configuration @@ -73,7 +73,7 @@ void init_usb_hardware(void) { */ __HAL_RCC_GPIOA_CLK_ENABLE(); - /* Configure DM DP Pins */ + /* Configure DM DP Pins */ GPIO_InitStruct.Pin = GPIO_PIN_11 | GPIO_PIN_12; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -135,5 +135,5 @@ void init_usb_hardware(void) { } void OTG_FS_IRQHandler(void) { - usb_irq_handler(); + usb_irq_handler(); } diff --git a/ports/stm/tools/parse_af_csv.py b/ports/stm/tools/parse_af_csv.py index 06af3bf1e3..38608b5dac 100644 --- a/ports/stm/tools/parse_af_csv.py +++ b/ports/stm/tools/parse_af_csv.py @@ -36,40 +36,43 @@ import sys def evaluate_periph(inper, inlist, periph, subtype, altfn, pin): # ex) SPI1_SCK,SPI3_SCK/I2S3_CK # Clean anything after a '\' due to SPI/I2S mixing - if not inper.find('/') == -1: - inper = inper[:inper.find('/')] + if not inper.find("/") == -1: + inper = inper[: inper.find("/")] + + if inper[: len(periph)] == periph and inper[-len(subtype) :] == subtype: + inlist.append([inper[len(periph) : len(periph) + 1], altfn, pin]) - if inper[:len(periph)] == periph and inper[-len(subtype):] == subtype: - inlist.append([inper[len(periph):len(periph)+1], altfn, pin]) # Timers (TIM) are a special case with 4 values # timer index, alt function, channel, pin string def evaluate_tim(inper, inlist, altfn, pin): # ex) TIM2_CH1/TIM2_ETR, TIM5_CH1 # Clean anything after a '\' to filter ETR - if not inper.find('/') == -1: - inper = inper[:inper.find('/')] + if not inper.find("/") == -1: + inper = inper[: inper.find("/")] + + if inper[:3] == "TIM" and inper[5:7] == "CH" and inper[-1:] != "N": + inlist.append([inper[3:4], altfn, inper[-1:], pin]) + elif inper[:3] == "TIM" and inper[6:8] == "CH" and inper[-1:] != "N": + inlist.append([inper[3:5], altfn, inper[-1:], pin]) - if inper[:3] == "TIM" and inper[5:7] == "CH" and inper[-1:] != 'N': - inlist.append([inper[3:4],altfn,inper[-1:],pin]) - elif inper[:3] == "TIM" and inper[6:8] == "CH" and inper[-1:] != 'N': - inlist.append([inper[3:5],altfn,inper[-1:],pin]) # Open target file with open(sys.argv[1]) as csv_file: - csv_reader = csv.reader(csv_file, delimiter=',') + csv_reader = csv.reader(csv_file, delimiter=",") line_count = 0 if sys.argv[2] != "-pins-only": # List of peripheral pin types to read todo = [ - ["I2C","SDA"], - ["I2C","SCL"], - ["SPI","SCK"], - ["SPI","MOSI"], - ["SPI","MISO"], - ["UART","TX"], - ["UART","RX"]] + ["I2C", "SDA"], + ["I2C", "SCL"], + ["SPI", "SCK"], + ["SPI", "MOSI"], + ["SPI", "MISO"], + ["UART", "TX"], + ["UART", "RX"], + ] # Make a list of empty lists to populate outlist = [] @@ -85,7 +88,7 @@ with open(sys.argv[1]) as csv_file: altfn = 0 pin = row[1] if len(pin) < 4: - pin = pin[:2] + '0' + pin[2:] + pin = pin[:2] + "0" + pin[2:] for col in row: array_index = 0 # Evaluate the string for every possible todo entry @@ -93,7 +96,9 @@ with open(sys.argv[1]) as csv_file: evaluate_periph(col, outlist[array_index], item[0], item[1], altfn - 2, pin) # UART special case, run again for USART variant if item[0] == "UART": - evaluate_periph(col, outlist[array_index], "USART", item[1], altfn - 2, pin) + evaluate_periph( + col, outlist[array_index], "USART", item[1], altfn - 2, pin + ) array_index += 1 # TIM special case evaluate_tim(col, outlist[-1], altfn - 2, pin) @@ -102,7 +107,7 @@ with open(sys.argv[1]) as csv_file: # Print formatted output for i in range(len(todo)): - ins = (todo[i][0]).lower() + '_' + (todo[i][1]).lower() + '_' + ins = (todo[i][0]).lower() + "_" + (todo[i][1]).lower() + "_" # const mcu_i2c_sda_obj_t mcu_i2c_sda_list[4] = { print("const mcu_periph_obj_t mcu_" + ins + "list[" + str(len(outlist[i])) + "] = {") for row in outlist[i]: @@ -112,7 +117,17 @@ with open(sys.argv[1]) as csv_file: # Timer special case: print("const mcu_tim_pin_obj_t mcu_tim_pin_list[" + str(len(outlist[-1])) + "] = {") for row in outlist[-1]: - print(" TIM(" + row[0] + ", " + str(row[1]) + ", " + str(row[2]) + ", &pin_" + row[3] + "),") + print( + " TIM(" + + row[0] + + ", " + + str(row[1]) + + ", " + + str(row[2]) + + ", &pin_" + + row[3] + + ")," + ) print("};") else: @@ -126,14 +141,22 @@ with open(sys.argv[1]) as csv_file: altfn = 0 pin = row[1] if len(pin) < 4: - pin = pin[:2] + '0' + pin[2:] + pin = pin[:2] + "0" + pin[2:] outlist.append([pin, str(ord(row[1][1:2]) - 65), row[1][2:4]]) line_count += 1 for line in outlist: - print("const mcu_pin_obj_t pin_" + line[0] + " = PIN(" + line[1] + ", " + line[2] + ", NO_ADC);") + print( + "const mcu_pin_obj_t pin_" + + line[0] + + " = PIN(" + + line[1] + + ", " + + line[2] + + ", NO_ADC);" + ) for line in outlist: print("extern const mcu_pin_obj_t pin_" + line[0] + ";") - print(f'Processed {line_count} lines.') + print(f"Processed {line_count} lines.") diff --git a/ports/stm/tools/parse_pins_csv.py b/ports/stm/tools/parse_pins_csv.py index 68f6db586e..972c6b6a88 100644 --- a/ports/stm/tools/parse_pins_csv.py +++ b/ports/stm/tools/parse_pins_csv.py @@ -33,7 +33,7 @@ import sys # Open target file with open(sys.argv[1]) as csv_file: - csv_reader = csv.reader(csv_file, delimiter=',') + csv_reader = csv.reader(csv_file, delimiter=",") line_count = 0 print("STATIC const mp_rom_map_elem_t board_module_globals_table[] = {") @@ -42,8 +42,8 @@ with open(sys.argv[1]) as csv_file: label = row[0] pin = row[1] if len(pin) < 4: - pin = pin[:2] + '0' + pin[2:] + pin = pin[:2] + "0" + pin[2:] print("{ MP_ROM_QSTR(MP_QSTR_" + label + "), MP_ROM_PTR(&pin_" + pin + ") },") line_count += 1 - print(f'Processed {line_count} lines.') + print(f"Processed {line_count} lines.") diff --git a/ports/unix/alloc.c b/ports/unix/alloc.c index ca12d025b6..7fe7b4dba4 100644 --- a/ports/unix/alloc.c +++ b/ports/unix/alloc.c @@ -69,7 +69,7 @@ void mp_unix_free_exec(void *ptr, size_t size) { munmap(ptr, size); // unlink the mmap'd region from the list - for (mmap_region_t **rg = (mmap_region_t**)&MP_STATE_VM(mmap_region_head); *rg != NULL; *rg = (*rg)->next) { + for (mmap_region_t **rg = (mmap_region_t **)&MP_STATE_VM(mmap_region_head); *rg != NULL; *rg = (*rg)->next) { if ((*rg)->ptr == ptr) { mmap_region_t *next = (*rg)->next; m_del_obj(mmap_region_t, *rg); diff --git a/ports/unix/coverage.c b/ports/unix/coverage.c index 849820fffd..2d377bc8fe 100644 --- a/ports/unix/coverage.c +++ b/ports/unix/coverage.c @@ -105,7 +105,7 @@ STATIC const mp_stream_p_t fileio_stream_p = { STATIC const mp_obj_type_t mp_type_stest_fileio = { { &mp_type_type }, .protocol = &fileio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; // stream read returns non-blocking error @@ -133,12 +133,12 @@ STATIC const mp_stream_p_t textio_stream_p2 = { STATIC const mp_obj_type_t mp_type_stest_textio2 = { { &mp_type_type }, .protocol = &textio_stream_p2, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict2, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict2, }; // str/bytes objects without a valid hash -STATIC const mp_obj_str_t str_no_hash_obj = {{&mp_type_str}, 0, 10, (const byte*)"0123456789"}; -STATIC const mp_obj_str_t bytes_no_hash_obj = {{&mp_type_bytes}, 0, 10, (const byte*)"0123456789"}; +STATIC const mp_obj_str_t str_no_hash_obj = {{&mp_type_str}, 0, 10, (const byte *)"0123456789"}; +STATIC const mp_obj_str_t bytes_no_hash_obj = {{&mp_type_bytes}, 0, 10, (const byte *)"0123456789"}; // function to run extra tests for things that can't be checked by scripts STATIC mp_obj_t extra_coverage(void) { @@ -380,10 +380,10 @@ STATIC mp_obj_t extra_coverage(void) { // call mp_execute_bytecode with invalide bytecode (should raise NotImplementedError) mp_obj_fun_bc_t fun_bc; - fun_bc.bytecode = (const byte*)"\x01"; // just needed for n_state + fun_bc.bytecode = (const byte *)"\x01"; // just needed for n_state mp_code_state_t *code_state = m_new_obj_var(mp_code_state_t, mp_obj_t, 1); code_state->fun_bc = &fun_bc; - code_state->ip = (const byte*)"\x00"; // just needed for an invalid opcode + code_state->ip = (const byte *)"\x00"; // just needed for an invalid opcode code_state->sp = &code_state->state[0]; code_state->exc_sp = NULL; code_state->old_globals = NULL; diff --git a/ports/unix/file.c b/ports/unix/file.c index 222dca4621..892457ed56 100644 --- a/ports/unix/file.c +++ b/ports/unix/file.c @@ -104,7 +104,7 @@ STATIC mp_uint_t fdfile_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, i check_fd_is_open(o); switch (request) { case MP_STREAM_SEEK: { - struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg; + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; off_t off = lseek(o->fd, s->offset, s->whence); if (off == (off_t)-1) { *errcode = errno; @@ -175,7 +175,7 @@ STATIC mp_obj_t fdfile_open(const mp_obj_type_t *type, mp_arg_val_t *args) { case '+': mode_rw = O_RDWR; break; - #if MICROPY_PY_IO_FILEIO + #if MICROPY_PY_IO_FILEIO // If we don't have io.FileIO, then files are in text mode implicitly case 'b': type = &mp_type_fileio; @@ -183,7 +183,7 @@ STATIC mp_obj_t fdfile_open(const mp_obj_type_t *type, mp_arg_val_t *args) { case 't': type = &mp_type_textio; break; - #endif + #endif } } @@ -244,7 +244,7 @@ const mp_obj_type_t mp_type_fileio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &fileio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; #endif @@ -264,7 +264,7 @@ const mp_obj_type_t mp_type_textio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &textio_stream_p, - .locals_dict = (mp_obj_dict_t*)&rawfile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rawfile_locals_dict, }; // Factory function for I/O stream classes @@ -276,7 +276,7 @@ mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) } MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open); -const mp_obj_fdfile_t mp_sys_stdin_obj = { .base = {&mp_type_textio}, .fd = STDIN_FILENO }; +const mp_obj_fdfile_t mp_sys_stdin_obj = { .base = {&mp_type_textio}, .fd = STDIN_FILENO }; const mp_obj_fdfile_t mp_sys_stdout_obj = { .base = {&mp_type_textio}, .fd = STDOUT_FILENO }; const mp_obj_fdfile_t mp_sys_stderr_obj = { .base = {&mp_type_textio}, .fd = STDERR_FILENO }; diff --git a/ports/unix/gccollect.c b/ports/unix/gccollect.c index 7cd74ec134..45ad1e0430 100644 --- a/ports/unix/gccollect.c +++ b/ports/unix/gccollect.c @@ -49,20 +49,20 @@ STATIC void gc_helper_get_regs(regs_t arr) { register long r13 asm ("r13"); register long r14 asm ("r14"); register long r15 asm ("r15"); -#ifdef __clang__ + #ifdef __clang__ // TODO: // This is dirty workaround for Clang. It tries to get around // uncompliant (wrt to GCC) behavior of handling register variables. // Application of this patch here is random, and done only to unbreak // MacOS build. Better, cross-arch ways to deal with Clang issues should // be found. - asm("" : "=r"(rbx)); - asm("" : "=r"(rbp)); - asm("" : "=r"(r12)); - asm("" : "=r"(r13)); - asm("" : "=r"(r14)); - asm("" : "=r"(r15)); -#endif + asm ("" : "=r" (rbx)); + asm ("" : "=r" (rbp)); + asm ("" : "=r" (r12)); + asm ("" : "=r" (r13)); + asm ("" : "=r" (r14)); + asm ("" : "=r" (r15)); + #endif arr[0] = rbx; arr[1] = rbp; arr[2] = r12; @@ -80,18 +80,18 @@ STATIC void gc_helper_get_regs(regs_t arr) { register long esi asm ("esi"); register long edi asm ("edi"); register long ebp asm ("ebp"); -#ifdef __clang__ + #ifdef __clang__ // TODO: // This is dirty workaround for Clang. It tries to get around // uncompliant (wrt to GCC) behavior of handling register variables. // Application of this patch here is random, and done only to unbreak // MacOS build. Better, cross-arch ways to deal with Clang issues should // be found. - asm("" : "=r"(ebx)); - asm("" : "=r"(esi)); - asm("" : "=r"(edi)); - asm("" : "=r"(ebp)); -#endif + asm ("" : "=r" (ebx)); + asm ("" : "=r" (esi)); + asm ("" : "=r" (edi)); + asm ("" : "=r" (ebp)); + #endif arr[0] = ebx; arr[1] = esi; arr[2] = edi; @@ -155,12 +155,12 @@ void gc_collect_regs_and_stack(void) { regs_t regs; gc_helper_get_regs(regs); // GC stack (and regs because we captured them) - void **regs_ptr = (void**)(void*)®s; + void **regs_ptr = (void **)(void *)®s; gc_collect_root(regs_ptr, ((uintptr_t)MP_STATE_THREAD(stack_top) - (uintptr_t)®s) / sizeof(uintptr_t)); } void gc_collect(void) { - //gc_dump_info(); + // gc_dump_info(); gc_collect_start(); gc_collect_regs_and_stack(); @@ -172,8 +172,8 @@ void gc_collect(void) { #endif gc_collect_end(); - //printf("-----\n"); - //gc_dump_info(); + // printf("-----\n"); + // gc_dump_info(); } -#endif //MICROPY_ENABLE_GC +#endif // MICROPY_ENABLE_GC diff --git a/ports/unix/input.c b/ports/unix/input.c index b661ce3e24..6fbb8513ac 100644 --- a/ports/unix/input.c +++ b/ports/unix/input.c @@ -59,7 +59,7 @@ char *prompt(char *p) { #endif void prompt_read_history(void) { -#if MICROPY_USE_READLINE_HISTORY + #if MICROPY_USE_READLINE_HISTORY #if MICROPY_USE_READLINE == 1 readline_init0(); // will clear history pointers char *home = getenv("HOME"); @@ -91,11 +91,11 @@ void prompt_read_history(void) { vstr_clear(&vstr); } #endif -#endif + #endif } void prompt_write_history(void) { -#if MICROPY_USE_READLINE_HISTORY + #if MICROPY_USE_READLINE_HISTORY #if MICROPY_USE_READLINE == 1 char *home = getenv("HOME"); if (home != NULL) { @@ -117,5 +117,5 @@ void prompt_write_history(void) { } } #endif -#endif + #endif } diff --git a/ports/unix/main.c b/ports/unix/main.c index 5a3cbaf477..eb7f7521fa 100644 --- a/ports/unix/main.c +++ b/ports/unix/main.c @@ -59,7 +59,7 @@ STATIC uint emit_opt = MP_EMIT_OPT_NONE; #if MICROPY_ENABLE_GC // Heap size of GC heap (if enabled) // Make it larger on a 64 bit machine, because pointers are larger. -long heap_size = 1024*1024 * (sizeof(mp_uint_t) / 4); +long heap_size = 1024 * 1024 * (sizeof(mp_uint_t) / 4); #endif STATIC void stderr_print_strn(void *env, const char *str, size_t len) { @@ -114,7 +114,7 @@ STATIC int execute_from_lexer(int source_kind, const void *source, mp_parse_inpu const vstr_t *vstr = source; lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, false); } else if (source_kind == LEX_SRC_FILENAME) { - lex = mp_lexer_new_from_file((const char*)source); + lex = mp_lexer_new_from_file((const char *)source); } else { // LEX_SRC_STDIN lex = mp_lexer_new_from_fd(MP_QSTR__lt_stdin_gt_, 0, false); } @@ -303,25 +303,25 @@ STATIC int do_str(const char *str) { STATIC int usage(char **argv) { printf( -"usage: %s [] [-X ] [-c ] []\n" -"Options:\n" -"-v : verbose (trace various operations); can be multiple\n" -"-O[N] : apply bytecode optimizations of level N\n" -"\n" -"Implementation specific options (-X):\n", argv[0] -); + "usage: %s [] [-X ] [-c ] []\n" + "Options:\n" + "-v : verbose (trace various operations); can be multiple\n" + "-O[N] : apply bytecode optimizations of level N\n" + "\n" + "Implementation specific options (-X):\n", argv[0] + ); int impl_opts_cnt = 0; printf( -" compile-only -- parse and compile only\n" -" emit={bytecode,native,viper} -- set the default code emitter\n" -); + " compile-only -- parse and compile only\n" + " emit={bytecode,native,viper} -- set the default code emitter\n" + ); impl_opts_cnt++; -#if MICROPY_ENABLE_GC + #if MICROPY_ENABLE_GC printf( -" heapsize=[w][K|M] -- set the heap size for the GC (default %ld)\n" -, heap_size); + " heapsize=[w][K|M] -- set the heap size for the GC (default %ld)\n" + , heap_size); impl_opts_cnt++; -#endif + #endif if (impl_opts_cnt == 0) { printf(" (none)\n"); @@ -347,7 +347,7 @@ STATIC void pre_process_options(int argc, char **argv) { emit_opt = MP_EMIT_OPT_NATIVE_PYTHON; } else if (strcmp(argv[a + 1], "emit=viper") == 0) { emit_opt = MP_EMIT_OPT_VIPER; -#if MICROPY_ENABLE_GC + #if MICROPY_ENABLE_GC } else if (strncmp(argv[a + 1], "heapsize=", sizeof("heapsize=") - 1) == 0) { char *end; heap_size = strtol(argv[a + 1] + sizeof("heapsize=") - 1, &end, 0); @@ -380,9 +380,9 @@ STATIC void pre_process_options(int argc, char **argv) { if (heap_size < 700) { goto invalid_arg; } -#endif + #endif } else { -invalid_arg: + invalid_arg: printf("Invalid option\n"); exit(usage(argv)); } @@ -438,10 +438,10 @@ MP_NOINLINE int main_(int argc, char **argv) { pre_process_options(argc, argv); -#if MICROPY_ENABLE_GC + #if MICROPY_ENABLE_GC char *heap = malloc(heap_size); gc_init(heap, heap + heap_size); -#endif + #endif #if MICROPY_ENABLE_PYSTACK static mp_obj_t pystack[1024]; @@ -457,7 +457,7 @@ MP_NOINLINE int main_(int argc, char **argv) { mp_type_vfs_posix.make_new(&mp_type_vfs_posix, 0, 0, NULL), MP_OBJ_NEW_QSTR(MP_QSTR__slash_), }; - mp_vfs_mount(2, args, (mp_map_t*)&mp_const_empty_map); + mp_vfs_mount(2, args, (mp_map_t *)&mp_const_empty_map); MP_STATE_VM(vfs_cur) = MP_STATE_VM(vfs_mount_table); } #endif @@ -490,25 +490,25 @@ MP_NOINLINE int main_(int argc, char **argv) { // Frozen modules are in their own pseudo-dir, e.g., ".frozen". path_items[1] = MP_OBJ_NEW_QSTR(MP_FROZEN_FAKE_DIR_QSTR); { - char *p = path; - for (mp_uint_t i = builtin_path_count; i < path_num; i++) { - char *p1 = strchr(p, PATHLIST_SEP_CHAR); - if (p1 == NULL) { - p1 = p + strlen(p); + char *p = path; + for (mp_uint_t i = builtin_path_count; i < path_num; i++) { + char *p1 = strchr(p, PATHLIST_SEP_CHAR); + if (p1 == NULL) { + p1 = p + strlen(p); + } + if (p[0] == '~' && p[1] == '/' && home != NULL) { + // Expand standalone ~ to $HOME + int home_l = strlen(home); + vstr_t vstr; + vstr_init(&vstr, home_l + (p1 - p - 1) + 1); + vstr_add_strn(&vstr, home, home_l); + vstr_add_strn(&vstr, p + 1, p1 - p - 1); + path_items[i] = mp_obj_new_str_from_vstr(&mp_type_str, &vstr); + } else { + path_items[i] = mp_obj_new_str_via_qstr(p, p1 - p); + } + p = p1 + 1; } - if (p[0] == '~' && p[1] == '/' && home != NULL) { - // Expand standalone ~ to $HOME - int home_l = strlen(home); - vstr_t vstr; - vstr_init(&vstr, home_l + (p1 - p - 1) + 1); - vstr_add_strn(&vstr, home, home_l); - vstr_add_strn(&vstr, p + 1, p1 - p - 1); - path_items[i] = mp_obj_new_str_from_vstr(&mp_type_str, &vstr); - } else { - path_items[i] = mp_obj_new_str_via_qstr(p, p1 - p); - } - p = p1 + 1; - } } @@ -613,7 +613,8 @@ MP_NOINLINE int main_(int argc, char **argv) { MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf; } else { MP_STATE_VM(mp_optimise_value) = 0; - for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++); + for (char *p = argv[a] + 1; *p && *p == 'O'; p++, MP_STATE_VM(mp_optimise_value)++) {; + } } } else { return usage(argv); @@ -661,13 +662,13 @@ MP_NOINLINE int main_(int argc, char **argv) { mp_deinit(); -#if MICROPY_ENABLE_GC && !defined(NDEBUG) + #if MICROPY_ENABLE_GC && !defined(NDEBUG) // We don't really need to free memory since we are about to exit the // process, but doing so helps to find memory leaks. free(heap); -#endif + #endif - //printf("total bytes = %d\n", m_get_total_bytes_allocated()); + // printf("total bytes = %d\n", m_get_total_bytes_allocated()); return ret & 0xff; } diff --git a/ports/unix/modffi.c b/ports/unix/modffi.c index c750f2eb77..a64d4a7b23 100644 --- a/ports/unix/modffi.c +++ b/ports/unix/modffi.c @@ -93,39 +93,50 @@ typedef struct _mp_obj_fficallback_t { ffi_type *params[]; } mp_obj_fficallback_t; -//STATIC const mp_obj_type_t opaque_type; +// STATIC const mp_obj_type_t opaque_type; STATIC const mp_obj_type_t ffimod_type; STATIC const mp_obj_type_t ffifunc_type; STATIC const mp_obj_type_t fficallback_type; STATIC const mp_obj_type_t ffivar_type; -STATIC ffi_type *char2ffi_type(char c) -{ +STATIC ffi_type *char2ffi_type(char c) { switch (c) { - case 'b': return &ffi_type_schar; - case 'B': return &ffi_type_uchar; - case 'h': return &ffi_type_sshort; - case 'H': return &ffi_type_ushort; - case 'i': return &ffi_type_sint; - case 'I': return &ffi_type_uint; - case 'l': return &ffi_type_slong; - case 'L': return &ffi_type_ulong; + case 'b': + return &ffi_type_schar; + case 'B': + return &ffi_type_uchar; + case 'h': + return &ffi_type_sshort; + case 'H': + return &ffi_type_ushort; + case 'i': + return &ffi_type_sint; + case 'I': + return &ffi_type_uint; + case 'l': + return &ffi_type_slong; + case 'L': + return &ffi_type_ulong; #if MICROPY_PY_BUILTINS_FLOAT - case 'f': return &ffi_type_float; - case 'd': return &ffi_type_double; + case 'f': + return &ffi_type_float; + case 'd': + return &ffi_type_double; #endif case 'O': // mp_obj_t case 'C': // (*)() case 'P': // const void* case 'p': // void* - case 's': return &ffi_type_pointer; - case 'v': return &ffi_type_void; - default: return NULL; + case 's': + return &ffi_type_pointer; + case 'v': + return &ffi_type_void; + default: + return NULL; } } -STATIC ffi_type *get_ffi_type(mp_obj_t o_in) -{ +STATIC ffi_type *get_ffi_type(mp_obj_t o_in) { if (MP_OBJ_IS_STR(o_in)) { const char *s = mp_obj_str_get_str(o_in); ffi_type *t = char2ffi_type(*s); @@ -138,8 +149,7 @@ STATIC ffi_type *get_ffi_type(mp_obj_t o_in) mp_raise_TypeError(translate("Unknown type")); } -STATIC mp_obj_t return_ffi_value(ffi_arg val, char type) -{ +STATIC mp_obj_t return_ffi_value(ffi_arg val, char type) { switch (type) { case 's': { const char *s = (const char *)(intptr_t)val; @@ -152,11 +162,13 @@ STATIC mp_obj_t return_ffi_value(ffi_arg val, char type) return mp_const_none; #if MICROPY_PY_BUILTINS_FLOAT case 'f': { - union { ffi_arg ffi; float flt; } val_union = { .ffi = val }; - return mp_obj_new_float((mp_float_t) val_union.flt); + union { ffi_arg ffi; + float flt; + } val_union = { .ffi = val }; + return mp_obj_new_float((mp_float_t)val_union.flt); } case 'd': { - double *p = (double*)&val; + double *p = (double *)&val; return mp_obj_new_float(*p); } #endif @@ -187,7 +199,7 @@ STATIC mp_obj_t make_func(mp_obj_t rettype_in, void *func, mp_obj_t argtypes_in) const char *argtypes = mp_obj_str_get_str(argtypes_in); mp_int_t nparams = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(argtypes_in)); - mp_obj_ffifunc_t *o = m_new_obj_var(mp_obj_ffifunc_t, ffi_type*, nparams); + mp_obj_ffifunc_t *o = m_new_obj_var(mp_obj_ffifunc_t, ffi_type *, nparams); o->base.type = &ffifunc_type; o->func = func; @@ -224,20 +236,20 @@ STATIC mp_obj_t ffimod_func(size_t n_args, const mp_obj_t *args) { MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ffimod_func_obj, 4, 4, ffimod_func); STATIC mp_obj_t mod_ffi_func(mp_obj_t rettype, mp_obj_t addr_in, mp_obj_t argtypes) { - void *addr = (void*)MP_OBJ_TO_PTR(mp_obj_int_get_truncated(addr_in)); + void *addr = (void *)MP_OBJ_TO_PTR(mp_obj_int_get_truncated(addr_in)); return make_func(rettype, addr, argtypes); } MP_DEFINE_CONST_FUN_OBJ_3(mod_ffi_func_obj, mod_ffi_func); -STATIC void call_py_func(ffi_cif *cif, void *ret, void** args, void *func) { +STATIC void call_py_func(ffi_cif *cif, void *ret, void **args, void *func) { mp_obj_t pyargs[cif->nargs]; for (uint i = 0; i < cif->nargs; i++) { - pyargs[i] = mp_obj_new_int(*(mp_int_t*)args[i]); + pyargs[i] = mp_obj_new_int(*(mp_int_t *)args[i]); } mp_obj_t res = mp_call_function_n_kw(MP_OBJ_FROM_PTR(func), cif->nargs, 0, pyargs); if (res != mp_const_none) { - *(ffi_arg*)ret = mp_obj_int_get_truncated(res); + *(ffi_arg *)ret = mp_obj_int_get_truncated(res); } } @@ -245,7 +257,7 @@ STATIC mp_obj_t mod_ffi_callback(mp_obj_t rettype_in, mp_obj_t func_in, mp_obj_t const char *rettype = mp_obj_str_get_str(rettype_in); mp_int_t nparams = MP_OBJ_SMALL_INT_VALUE(mp_obj_len_maybe(paramtypes_in)); - mp_obj_fficallback_t *o = m_new_obj_var(mp_obj_fficallback_t, ffi_type*, nparams); + mp_obj_fficallback_t *o = m_new_obj_var(mp_obj_fficallback_t, ffi_type *, nparams); o->base.type = &fficallback_type; o->clo = ffi_closure_alloc(sizeof(ffi_closure), &o->func); @@ -337,7 +349,7 @@ STATIC const mp_obj_type_t ffimod_type = { .name = MP_QSTR_ffimod, .print = ffimod_print, .make_new = ffimod_make_new, - .locals_dict = (mp_obj_dict_t*)&ffimod_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ffimod_locals_dict, }; // FFI function @@ -362,10 +374,10 @@ STATIC mp_obj_t ffifunc_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const values[i] = (ffi_arg)(intptr_t)a; #if MICROPY_PY_BUILTINS_FLOAT } else if (*argtype == 'f') { - float *p = (float*)&values[i]; + float *p = (float *)&values[i]; *p = mp_obj_get_float(a); } else if (*argtype == 'd') { - double *p = (double*)&values[i]; + double *p = (double *)&values[i]; *p = mp_obj_get_float(a); #endif } else if (a == mp_const_none) { @@ -375,8 +387,8 @@ STATIC mp_obj_t ffifunc_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const } else if (MP_OBJ_IS_STR(a)) { const char *s = mp_obj_str_get_str(a); values[i] = (ffi_arg)(intptr_t)s; - } else if (((mp_obj_base_t*)MP_OBJ_TO_PTR(a))->type->buffer_p.get_buffer != NULL) { - mp_obj_base_t *o = (mp_obj_base_t*)MP_OBJ_TO_PTR(a); + } else if (((mp_obj_base_t *)MP_OBJ_TO_PTR(a))->type->buffer_p.get_buffer != NULL) { + mp_obj_base_t *o = (mp_obj_base_t *)MP_OBJ_TO_PTR(a); mp_buffer_info_t bufinfo; int ret = o->type->buffer_p.get_buffer(MP_OBJ_FROM_PTR(o), &bufinfo, MP_BUFFER_READ); // TODO: MP_BUFFER_READ? if (ret != 0) { @@ -440,7 +452,7 @@ STATIC void ffivar_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin (void)kind; mp_obj_ffivar_t *self = MP_OBJ_TO_PTR(self_in); // Variable value printed as cast to int - mp_printf(print, "", self->var, *(int*)self->var); + mp_printf(print, "", self->var, *(int *)self->var); } STATIC mp_obj_t ffivar_get(mp_obj_t self_in) { @@ -467,7 +479,7 @@ STATIC const mp_obj_type_t ffivar_type = { { &mp_type_type }, .name = MP_QSTR_ffivar, .print = ffivar_print, - .locals_dict = (mp_obj_dict_t*)&ffivar_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ffivar_locals_dict, }; // Generic opaque storage object (unused) @@ -486,7 +498,7 @@ STATIC mp_obj_t mod_ffi_open(size_t n_args, const mp_obj_t *args) { MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_ffi_open_obj, 1, 2, mod_ffi_open); STATIC mp_obj_t mod_ffi_as_bytearray(mp_obj_t ptr, mp_obj_t size) { - return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void*)(uintptr_t)mp_obj_int_get_truncated(ptr)); + return mp_obj_new_bytearray_by_ref(mp_obj_int_get_truncated(size), (void *)(uintptr_t)mp_obj_int_get_truncated(ptr)); } MP_DEFINE_CONST_FUN_OBJ_2(mod_ffi_as_bytearray_obj, mod_ffi_as_bytearray); @@ -502,5 +514,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_ffi_globals, mp_module_ffi_globals_table); const mp_obj_module_t mp_module_ffi = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_ffi_globals, + .globals = (mp_obj_dict_t *)&mp_module_ffi_globals, }; diff --git a/ports/unix/modjni.c b/ports/unix/modjni.c index 82d1ccd559..a0d0cb1de6 100644 --- a/ports/unix/modjni.c +++ b/ports/unix/modjni.c @@ -98,7 +98,7 @@ STATIC bool is_object_type(const char *jtypesig) { STATIC void check_exception(void) { jobject exc = JJ1(ExceptionOccurred); if (exc) { - //JJ1(ExceptionDescribe); + // JJ1(ExceptionDescribe); mp_obj_t py_e = new_jobject(exc); JJ1(ExceptionClear); if (JJ(IsInstanceOf, exc, IndexException_class)) { @@ -142,7 +142,7 @@ STATIC void jclass_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { dest[0] = new_jobject(obj); return; } - //JJ1(ExceptionDescribe); + // JJ1(ExceptionDescribe); JJ1(ExceptionClear); mp_obj_jmethod_t *o = m_new_obj(mp_obj_jmethod_t); @@ -179,7 +179,7 @@ STATIC const mp_obj_type_t jclass_type = { .print = jclass_print, .attr = jclass_attr, .call = jclass_call, - .locals_dict = (mp_obj_dict_t*)&jclass_locals_dict, + .locals_dict = (mp_obj_dict_t *)&jclass_locals_dict, }; STATIC mp_obj_t new_jclass(jclass jc) { @@ -220,7 +220,7 @@ STATIC void jobject_attr(mp_obj_t self_in, qstr attr_in, mp_obj_t *dest) { dest[0] = new_jobject(obj); return; } - //JJ1(ExceptionDescribe); + // JJ1(ExceptionDescribe); JJ1(ExceptionClear); mp_obj_jmethod_t *o = m_new_obj(mp_obj_jmethod_t); @@ -246,7 +246,7 @@ STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) mp_uint_t idx = mp_obj_get_int(index); char class_name[64]; get_jclass_name(self->obj, class_name); - //printf("class: %s\n", class_name); + // printf("class: %s\n", class_name); if (class_name[0] == '[') { if (class_name[1] == 'L' || class_name[1] == '[') { @@ -288,7 +288,7 @@ STATIC mp_obj_t jobject_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) } -return MP_OBJ_NULL; + return MP_OBJ_NULL; } STATIC mp_obj_t jobject_unary_op(mp_unary_op_t op, mp_obj_t self_in) { @@ -364,10 +364,10 @@ STATIC void jmethod_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki #define IMATCH(s, static) ((!strncmp(s, static, sizeof(static) - 1)) && (s += sizeof(static) - 1)) #define CHECK_TYPE(java_type_name) \ - if (strncmp(arg_type, java_type_name, sizeof(java_type_name) - 1) != 0) { \ - return false; \ - } \ - arg_type += sizeof(java_type_name) - 1; + if (strncmp(arg_type, java_type_name, sizeof(java_type_name) - 1) != 0) { \ + return false; \ + } \ + arg_type += sizeof(java_type_name) - 1; STATIC const char *strprev(const char *s, char c) { while (*s != c) { @@ -412,7 +412,7 @@ STATIC bool py2jvalue(const char **jtypesig, mp_obj_t arg, jvalue *out) { if (!MATCH(expected_type, "java.lang.Object")) { char class_name[64]; get_jclass_name(jo->obj, class_name); - //printf("Arg class: %s\n", class_name); + // printf("Arg class: %s\n", class_name); if (strcmp(class_name, expected_type) != 0) { return false; } @@ -425,7 +425,7 @@ STATIC bool py2jvalue(const char **jtypesig, mp_obj_t arg, jvalue *out) { return false; } } else if (arg == mp_const_none) { - //printf("TODO: Check java arg type!!\n"); + // printf("TODO: Check java arg type!!\n"); while (isalpha(*arg_type) || *arg_type == '.') { arg_type++; } @@ -470,7 +470,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool jobject name_o = JJ(CallObjectMethod, meth, Object_toString_mid); const char *decl = JJ(GetStringUTFChars, name_o, NULL); const char *arg_types = strchr(decl, '(') + 1; - //const char *arg_types_end = strchr(arg_types, ')'); + // const char *arg_types_end = strchr(arg_types, ')'); // printf("method[%d]=%p %s\n", i, meth, decl); const char *meth_name = NULL; @@ -481,7 +481,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool ret_type = strprev(ret_type, ' ') + 1; int name_len = strlen(name); - if (strncmp(name, meth_name, name_len/*arg_types - meth_name - 1*/) || meth_name[name_len] != '('/*(*/) { + if (strncmp(name, meth_name, name_len /*arg_types - meth_name - 1*/) || meth_name[name_len] != '(' /*(*/) { goto next_method; } } @@ -542,7 +542,7 @@ STATIC mp_obj_t call_method(jobject obj, const char *name, jarray methods, bool } } -next_method: + next_method: JJ(ReleaseStringUTFChars, name_o, decl); JJ(DeleteLocalRef, name_o); JJ(DeleteLocalRef, meth); @@ -602,9 +602,9 @@ STATIC void create_jvm() { if (!libjvm) { mp_raise_msg(&mp_type_OSError, "unable to load libjvm.so, use LD_LIBRARY_PATH"); } - int (*_JNI_CreateJavaVM)(void*, void**, void*) = dlsym(libjvm, "JNI_CreateJavaVM"); + int (*_JNI_CreateJavaVM)(void *, void **, void *) = dlsym(libjvm, "JNI_CreateJavaVM"); - int st = _JNI_CreateJavaVM(&jvm, (void**)&env, &args); + int st = _JNI_CreateJavaVM(&jvm, (void **)&env, &args); if (st < 0 || !env) { mp_raise_msg(&mp_type_OSError, "unable to create JVM"); } @@ -615,26 +615,26 @@ STATIC void create_jvm() { jclass Object_class = JJ(FindClass, "java/lang/Object"); Object_toString_mid = JJ(GetMethodID, Object_class, "toString", - "()Ljava/lang/String;"); + "()Ljava/lang/String;"); Class_getName_mid = (*env)->GetMethodID(env, Class_class, "getName", - "()Ljava/lang/String;"); + "()Ljava/lang/String;"); Class_getField_mid = (*env)->GetMethodID(env, Class_class, "getField", - "(Ljava/lang/String;)Ljava/lang/reflect/Field;"); + "(Ljava/lang/String;)Ljava/lang/reflect/Field;"); Class_getMethods_mid = (*env)->GetMethodID(env, Class_class, "getMethods", - "()[Ljava/lang/reflect/Method;"); + "()[Ljava/lang/reflect/Method;"); Class_getConstructors_mid = (*env)->GetMethodID(env, Class_class, "getConstructors", - "()[Ljava/lang/reflect/Constructor;"); + "()[Ljava/lang/reflect/Constructor;"); Method_getName_mid = (*env)->GetMethodID(env, method_class, "getName", - "()Ljava/lang/String;"); + "()Ljava/lang/String;"); List_class = JJ(FindClass, "java/util/List"); List_get_mid = JJ(GetMethodID, List_class, "get", - "(I)Ljava/lang/Object;"); + "(I)Ljava/lang/Object;"); List_set_mid = JJ(GetMethodID, List_class, "set", - "(ILjava/lang/Object;)Ljava/lang/Object;"); + "(ILjava/lang/Object;)Ljava/lang/Object;"); List_size_mid = JJ(GetMethodID, List_class, "size", - "()I"); + "()I"); IndexException_class = JJ(FindClass, "java/lang/IndexOutOfBoundsException"); } @@ -716,5 +716,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_jni_globals, mp_module_jni_globals_table); const mp_obj_module_t mp_module_jni = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_jni_globals, + .globals = (mp_obj_dict_t *)&mp_module_jni_globals, }; diff --git a/ports/unix/modmachine.c b/ports/unix/modmachine.c index 61697cfb6f..af3a9d88fe 100644 --- a/ports/unix/modmachine.c +++ b/ports/unix/modmachine.c @@ -95,7 +95,7 @@ STATIC MP_DEFINE_CONST_DICT(machine_module_globals, machine_module_globals_table const mp_obj_module_t mp_module_machine = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&machine_module_globals, + .globals = (mp_obj_dict_t *)&machine_module_globals, }; #endif // MICROPY_PY_MACHINE diff --git a/ports/unix/modos.c b/ports/unix/modos.c index 252b19a50c..57e00fa0c5 100644 --- a/ports/unix/modos.c +++ b/ports/unix/modos.c @@ -230,5 +230,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_os_globals, mp_module_os_globals_table); const mp_obj_module_t mp_module_os = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_os_globals, + .globals = (mp_obj_dict_t *)&mp_module_os_globals, }; diff --git a/ports/unix/modtermios.c b/ports/unix/modtermios.c index fe19aac83c..bd723085de 100644 --- a/ports/unix/modtermios.c +++ b/ports/unix/modtermios.c @@ -58,7 +58,7 @@ STATIC mp_obj_t mod_termios_tcgetattr(mp_obj_t fd_in) { // but no way unicode chars could be there, if c_cc is defined to be a // a "char". But it's type is actually cc_t, which can be anything. // TODO: For now, we still deal with it like that. - cc->items[i] = mp_obj_new_bytes((byte*)&term.c_cc[i], 1); + cc->items[i] = mp_obj_new_bytes((byte *)&term.c_cc[i], 1); } } return MP_OBJ_FROM_PTR(r); @@ -129,7 +129,7 @@ STATIC const mp_rom_map_elem_t mp_module_termios_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_tcsetattr), MP_ROM_PTR(&mod_termios_tcsetattr_obj) }, { MP_ROM_QSTR(MP_QSTR_setraw), MP_ROM_PTR(&mod_termios_setraw_obj) }, -#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(name) } +#define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(name) } C(TCSANOW), C(B9600), @@ -146,5 +146,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_termios_globals, mp_module_termios_globals const mp_obj_module_t mp_module_termios = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_termios_globals, + .globals = (mp_obj_dict_t *)&mp_module_termios_globals, }; diff --git a/ports/unix/modtime.c b/ports/unix/modtime.c index cc9b4a3371..94ae8d2f1e 100644 --- a/ports/unix/modtime.c +++ b/ports/unix/modtime.c @@ -60,38 +60,38 @@ static inline int msec_sleep_tv(struct timeval *tv) { #endif #if defined(MP_CLOCKS_PER_SEC) -#define CLOCK_DIV (mp_float_t) (MP_CLOCKS_PER_SEC / 1000.0F) +#define CLOCK_DIV (mp_float_t)(MP_CLOCKS_PER_SEC / 1000.0F) #else #error Unsupported clock() implementation #endif STATIC mp_obj_t mod_time_time(void) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT struct timeval tv; gettimeofday(&tv, NULL); mp_float_t val = tv.tv_sec + (mp_float_t)tv.tv_usec / 1000000; return mp_obj_new_float(val); -#else + #else return mp_obj_new_int((mp_int_t)time(NULL)); -#endif + #endif } STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_time_time_obj, mod_time_time); // Note: this is deprecated since CPy3.3, but pystone still uses it. STATIC mp_obj_t mod_time_clock(void) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT // float cannot represent full range of int32 precisely, so we pre-divide // int to reduce resolution, and then actually do float division hoping // to preserve integer part resolution. return mp_obj_new_float((mp_float_t)(clock() / 1000) / CLOCK_DIV); -#else + #else return mp_obj_new_int((mp_int_t)clock()); -#endif + #endif } STATIC MP_DEFINE_CONST_FUN_OBJ_0(mod_time_clock_obj, mod_time_clock); STATIC mp_obj_t mod_time_sleep(mp_obj_t arg) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT struct timeval tv; mp_float_t val = mp_obj_get_float(arg); double ipart; @@ -109,18 +109,18 @@ STATIC mp_obj_t mod_time_sleep(mp_obj_t arg) { break; } mp_handle_pending(); - //printf("select: EINTR: %ld:%ld\n", tv.tv_sec, tv.tv_usec); + // printf("select: EINTR: %ld:%ld\n", tv.tv_sec, tv.tv_usec); #else break; #endif } RAISE_ERRNO(res, errno); -#else + #else // TODO: Handle EINTR MP_THREAD_GIL_EXIT(); sleep(mp_obj_get_int(arg)); MP_THREAD_GIL_ENTER(); -#endif + #endif return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mod_time_sleep_obj, mod_time_sleep); @@ -179,7 +179,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_time_globals, mp_module_time_globals_table const mp_obj_module_t mp_module_time = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_time_globals, + .globals = (mp_obj_dict_t *)&mp_module_time_globals, }; #endif // MICROPY_PY_UTIME diff --git a/ports/unix/moduos_vfs.c b/ports/unix/moduos_vfs.c index b45d4485b5..bb2f370d9a 100644 --- a/ports/unix/moduos_vfs.c +++ b/ports/unix/moduos_vfs.c @@ -77,7 +77,7 @@ STATIC MP_DEFINE_CONST_DICT(uos_vfs_module_globals, uos_vfs_module_globals_table const mp_obj_module_t mp_module_uos_vfs = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&uos_vfs_module_globals, + .globals = (mp_obj_dict_t *)&uos_vfs_module_globals, }; #endif // MICROPY_VFS diff --git a/ports/unix/moduselect.c b/ports/unix/moduselect.c index dbda5e1107..4d0fa37c10 100644 --- a/ports/unix/moduselect.c +++ b/ports/unix/moduselect.c @@ -315,7 +315,7 @@ STATIC const mp_obj_type_t mp_type_poll = { .name = MP_QSTR_poll, .getiter = mp_identity_getiter, .iternext = poll_iternext, - .locals_dict = (void*)&poll_locals_dict, + .locals_dict = (void *)&poll_locals_dict, }; STATIC mp_obj_t select_poll(size_t n_args, const mp_obj_t *args) { @@ -348,7 +348,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_select_globals, mp_module_select_globals_t const mp_obj_module_t mp_module_uselect = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_select_globals, + .globals = (mp_obj_dict_t *)&mp_module_select_globals, }; #endif // MICROPY_PY_USELECT_POSIX diff --git a/ports/unix/modusocket.c b/ports/unix/modusocket.c index 90651a19ea..89480c0cc6 100644 --- a/ports/unix/modusocket.c +++ b/ports/unix/modusocket.c @@ -168,10 +168,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_listen_obj, socket_listen); STATIC mp_obj_t socket_accept(mp_obj_t self_in) { mp_obj_socket_t *self = MP_OBJ_TO_PTR(self_in); // sockaddr_storage isn't stack-friendly (129 bytes or so) - //struct sockaddr_storage addr; + // struct sockaddr_storage addr; byte addr[32]; socklen_t addr_len = sizeof(addr); - int fd = accept(self->fd, (struct sockaddr*)&addr, &addr_len); + int fd = accept(self->fd, (struct sockaddr *)&addr, &addr_len); RAISE_ERRNO(fd, errno); mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); @@ -217,7 +217,7 @@ STATIC mp_obj_t socket_recvfrom(size_t n_args, const mp_obj_t *args) { socklen_t addr_len = sizeof(addr); byte *buf = m_new(byte, sz); - int out_sz = recvfrom(self->fd, buf, sz, flags, (struct sockaddr*)&addr, &addr_len); + int out_sz = recvfrom(self->fd, buf, sz, flags, (struct sockaddr *)&addr, &addr_len); RAISE_ERRNO(out_sz, errno); mp_obj_t buf_o = mp_obj_new_str_of_type(&mp_type_bytes, buf, out_sz); @@ -225,7 +225,7 @@ STATIC mp_obj_t socket_recvfrom(size_t n_args, const mp_obj_t *args) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); t->items[0] = buf_o; - t->items[1] = mp_obj_from_sockaddr((struct sockaddr*)&addr, addr_len); + t->items[1] = mp_obj_from_sockaddr((struct sockaddr *)&addr, addr_len); return MP_OBJ_FROM_PTR(t); } @@ -265,7 +265,7 @@ STATIC mp_obj_t socket_sendto(size_t n_args, const mp_obj_t *args) { mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); mp_get_buffer_raise(dst_addr, &addr_bi, MP_BUFFER_READ); int out_sz = sendto(self->fd, bufinfo.buf, bufinfo.len, flags, - (struct sockaddr *)addr_bi.buf, addr_bi.len); + (struct sockaddr *)addr_bi.buf, addr_bi.len); RAISE_ERRNO(out_sz, errno); return MP_OBJ_NEW_SMALL_INT(out_sz); @@ -321,7 +321,7 @@ STATIC mp_obj_t socket_makefile(size_t n_args, const mp_obj_t *args) { mp_obj_t *new_args = alloca(n_args * sizeof(mp_obj_t)); memcpy(new_args + 1, args + 1, (n_args - 1) * sizeof(mp_obj_t)); new_args[0] = MP_OBJ_NEW_SMALL_INT(self->fd); - return mp_builtin_open(n_args, new_args, (mp_map_t*)&mp_const_empty_map); + return mp_builtin_open(n_args, new_args, (mp_map_t *)&mp_const_empty_map); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_makefile_obj, 1, 3, socket_makefile); @@ -388,7 +388,7 @@ const mp_obj_type_t mp_type_socket = { .getiter = NULL, .iternext = NULL, .protocol = &usocket_stream_p, - .locals_dict = (mp_obj_dict_t*)&usocket_locals_dict, + .locals_dict = (mp_obj_dict_t *)&usocket_locals_dict, }; #define BINADDR_MAX_LEN sizeof(struct in6_addr) @@ -442,10 +442,10 @@ STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { snprintf(buf, sizeof(buf), "%u", port); serv = buf; hints.ai_flags = AI_NUMERICSERV; -#ifdef __UCLIBC_MAJOR__ -#if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32)) + #ifdef __UCLIBC_MAJOR__ + #if __UCLIBC_MAJOR__ == 0 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ <= 32)) // "warning" requires -Wno-cpp which is a relatively new gcc option, so we choose not to use it. -//#warning Working around uClibc bug with numeric service name +// #warning Working around uClibc bug with numeric service name // Older versions og uClibc have bugs when numeric ports in service // arg require also hints.ai_socktype (or hints.ai_protocol) != 0 // This actually was fixed in 0.9.32.1, but uClibc doesn't allow to @@ -454,8 +454,8 @@ STATIC mp_obj_t mod_socket_getaddrinfo(size_t n_args, const mp_obj_t *args) { // Note that this is crude workaround, precluding UDP socket addresses // to be returned. TODO: set only if not set by Python args. hints.ai_socktype = SOCK_STREAM; -#endif -#endif + #endif + #endif } else { serv = mp_obj_str_get_str(args[1]); } @@ -500,30 +500,30 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mod_socket_getaddrinfo_obj, 2, 4, mod STATIC mp_obj_t mod_socket_sockaddr(mp_obj_t sockaddr_in) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(sockaddr_in, &bufinfo, MP_BUFFER_READ); - switch (((struct sockaddr*)bufinfo.buf)->sa_family) { + switch (((struct sockaddr *)bufinfo.buf)->sa_family) { case AF_INET: { - struct sockaddr_in *sa = (struct sockaddr_in*)bufinfo.buf; + struct sockaddr_in *sa = (struct sockaddr_in *)bufinfo.buf; mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET); - t->items[1] = mp_obj_new_bytes((byte*)&sa->sin_addr, sizeof(sa->sin_addr)); + t->items[1] = mp_obj_new_bytes((byte *)&sa->sin_addr, sizeof(sa->sin_addr)); t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin_port)); return MP_OBJ_FROM_PTR(t); } case AF_INET6: { - struct sockaddr_in6 *sa = (struct sockaddr_in6*)bufinfo.buf; + struct sockaddr_in6 *sa = (struct sockaddr_in6 *)bufinfo.buf; mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(AF_INET6); - t->items[1] = mp_obj_new_bytes((byte*)&sa->sin6_addr, sizeof(sa->sin6_addr)); + t->items[1] = mp_obj_new_bytes((byte *)&sa->sin6_addr, sizeof(sa->sin6_addr)); t->items[2] = MP_OBJ_NEW_SMALL_INT(ntohs(sa->sin6_port)); t->items[3] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_flowinfo)); t->items[4] = MP_OBJ_NEW_SMALL_INT(ntohl(sa->sin6_scope_id)); return MP_OBJ_FROM_PTR(t); } default: { - struct sockaddr *sa = (struct sockaddr*)bufinfo.buf; + struct sockaddr *sa = (struct sockaddr *)bufinfo.buf; mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(sa->sa_family); - t->items[1] = mp_obj_new_bytes((byte*)sa->sa_data, bufinfo.len - offsetof(struct sockaddr, sa_data)); + t->items[1] = mp_obj_new_bytes((byte *)sa->sa_data, bufinfo.len - offsetof(struct sockaddr, sa_data)); return MP_OBJ_FROM_PTR(t); } } @@ -539,7 +539,7 @@ STATIC const mp_rom_map_elem_t mp_module_socket_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_inet_ntop), MP_ROM_PTR(&mod_socket_inet_ntop_obj) }, { MP_ROM_QSTR(MP_QSTR_sockaddr), MP_ROM_PTR(&mod_socket_sockaddr_obj) }, -#define C(name) { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_INT(name) } +#define C(name) { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_INT(name) } C(AF_UNIX), C(AF_INET), C(AF_INET6), @@ -563,5 +563,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_socket_globals, mp_module_socket_globals_t const mp_obj_module_t mp_module_socket = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_socket_globals, + .globals = (mp_obj_dict_t *)&mp_module_socket_globals, }; diff --git a/ports/unix/mpconfigport.h b/ports/unix/mpconfigport.h index d6bbad9ce1..464c4ce119 100644 --- a/ports/unix/mpconfigport.h +++ b/ports/unix/mpconfigport.h @@ -36,7 +36,7 @@ #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. @@ -250,7 +250,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) diff --git a/ports/unix/mphalport.h b/ports/unix/mphalport.h index 4e459ffca5..d852b78c0c 100644 --- a/ports/unix/mphalport.h +++ b/ports/unix/mphalport.h @@ -51,10 +51,14 @@ 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_ms(mp_uint_t ms) { usleep((ms) * 1000); } -static inline void mp_hal_delay_us(mp_uint_t us) { usleep(us); } +static inline void mp_hal_delay_ms(mp_uint_t ms) { + usleep((ms) * 1000); +} +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/ports/unix/mpthreadport.c b/ports/unix/mpthreadport.c index 3641745bc6..864cf795e7 100644 --- a/ports/unix/mpthreadport.c +++ b/ports/unix/mpthreadport.c @@ -65,10 +65,10 @@ STATIC void mp_thread_gc(int signo, siginfo_t *info, void *context) { // We have access to the context (regs, stack) of the thread but it seems // that we don't need the extra information, enough is captured by the // gc_collect_regs_and_stack function above - //gc_collect_root((void**)context, sizeof(ucontext_t) / sizeof(uintptr_t)); + // gc_collect_root((void**)context, sizeof(ucontext_t) / sizeof(uintptr_t)); #if MICROPY_ENABLE_PYSTACK - void **ptrs = (void**)(void*)MP_STATE_THREAD(pystack_start); - gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void*)); + void **ptrs = (void **)(void *)MP_STATE_THREAD(pystack_start); + gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void *)); #endif thread_signal_done = 1; } @@ -119,7 +119,7 @@ void mp_thread_gc_others(void) { } mp_state_thread_t *mp_thread_get_state(void) { - return (mp_state_thread_t*)pthread_getspecific(tls_key); + return (mp_state_thread_t *)pthread_getspecific(tls_key); } void mp_thread_set_state(void *state) { @@ -137,7 +137,7 @@ void mp_thread_start(void) { pthread_mutex_unlock(&thread_mutex); } -void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size) { +void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) { // default stack size is 8k machine-words if (*stack_size == 0) { *stack_size = 8192 * BYTES_PER_WORD; diff --git a/ports/unix/unix_mphal.c b/ports/unix/unix_mphal.c index 77deb3152f..ab9c08f511 100644 --- a/ports/unix/unix_mphal.c +++ b/ports/unix/unix_mphal.c @@ -130,7 +130,7 @@ static int call_dupterm_read(size_t idx) { return -1; } nlr_pop(); - return *(byte*)bufinfo.buf; + return *(byte *)bufinfo.buf; } else { // Temporarily disable dupterm to avoid infinite recursion mp_obj_t save_term = MP_STATE_VM(dupterm_objs[idx]); @@ -146,12 +146,12 @@ static int call_dupterm_read(size_t idx) { int mp_hal_stdin_rx_chr(void) { unsigned char c; -#if MICROPY_PY_OS_DUPTERM + #if MICROPY_PY_OS_DUPTERM // TODO only support dupterm one slot at the moment if (MP_STATE_VM(dupterm_objs[0]) != MP_OBJ_NULL) { int c; do { - c = call_dupterm_read(0); + c = call_dupterm_read(0); } while (c == -2); if (c == -1) { goto main_term; @@ -161,18 +161,18 @@ int mp_hal_stdin_rx_chr(void) { } return c; } else { - main_term:; -#endif - int ret = read(0, &c, 1); - if (ret == 0) { - c = 4; // EOF, ctrl-D - } else if (c == '\n') { - c = '\r'; - } - return c; -#if MICROPY_PY_OS_DUPTERM + main_term:; + #endif + int ret = read(0, &c, 1); + if (ret == 0) { + c = 4; // EOF, ctrl-D + } else if (c == '\n') { + c = '\r'; } -#endif + return c; + #if MICROPY_PY_OS_DUPTERM +} + #endif } void mp_hal_stdout_tx_strn(const char *str, size_t len) { diff --git a/py/argcheck.c b/py/argcheck.c index af5c81bf37..7fba9dc274 100644 --- a/py/argcheck.c +++ b/py/argcheck.c @@ -48,38 +48,38 @@ void mp_arg_check_num_kw_array(size_t n_args, size_t n_kw, size_t n_args_min, si if (n_kw > 0 && !takes_kw) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #else - mp_raise_TypeError(translate("function does not take keyword arguments")); + mp_raise_TypeError(translate("function does not take keyword arguments")); #endif } if (n_args_min == n_args_max) { if (n_args != n_args_min) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #else - mp_raise_TypeError_varg( - translate("function takes %d positional arguments but %d were given"), - n_args_min, n_args); + mp_raise_TypeError_varg( + translate("function takes %d positional arguments but %d were given"), + n_args_min, n_args); #endif } } else { if (n_args < n_args_min) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #else - mp_raise_TypeError_varg( - translate("function missing %d required positional arguments"), - n_args_min - n_args); + mp_raise_TypeError_varg( + translate("function missing %d required positional arguments"), + n_args_min - n_args); #endif } else if (n_args > n_args_max) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #else - mp_raise_TypeError_varg( - translate("function expected at most %d arguments, got %d"), - n_args_max, n_args); + mp_raise_TypeError_varg( + translate("function expected at most %d arguments, got %d"), + n_args_max, n_args); #endif } } @@ -99,12 +99,12 @@ void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n mp_map_elem_t *kw = mp_map_lookup(kws, MP_OBJ_NEW_QSTR(allowed[i].qst), MP_MAP_LOOKUP); if (kw == NULL) { if (allowed[i].flags & MP_ARG_REQUIRED) { - #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); - #else - mp_raise_TypeError_varg( - translate("'%q' argument required"), allowed[i].qst); - #endif + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE + mp_arg_error_terse_mismatch(); + #else + mp_raise_TypeError_varg( + translate("'%q' argument required"), allowed[i].qst); + #endif } out_vals[i] = allowed[i].defval; continue; @@ -123,20 +123,20 @@ void mp_arg_parse_all(size_t n_pos, const mp_obj_t *pos, mp_map_t *kws, size_t n } } if (pos_found < n_pos) { - extra_positional: + extra_positional: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #else - // TODO better error message - mp_raise_TypeError(translate("extra positional arguments given")); + // TODO better error message + mp_raise_TypeError(translate("extra positional arguments given")); #endif } if (kws_found < kws->used) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #else - // TODO better error message - mp_raise_TypeError(translate("extra keyword arguments given")); + // TODO better error message + mp_raise_TypeError(translate("extra keyword arguments given")); #endif } } diff --git a/py/asmarm.c b/py/asmarm.c index 11e498b2c7..644548cfd4 100644 --- a/py/asmarm.c +++ b/py/asmarm.c @@ -40,16 +40,16 @@ void asm_arm_end_pass(asm_arm_t *as) { if (as->base.pass == MP_ASM_PASS_EMIT) { -#ifdef __arm__ + #ifdef __arm__ // flush I- and D-cache - asm volatile( - "0:" - "mrc p15, 0, r15, c7, c10, 3\n" - "bne 0b\n" - "mov r0, #0\n" - "mcr p15, 0, r0, c7, c7, 0\n" - : : : "r0", "cc"); -#endif + asm volatile ( + "0:" + "mrc p15, 0, r15, c7, c10, 3\n" + "bne 0b\n" + "mov r0, #0\n" + "mcr p15, 0, r0, c7, c7, 0\n" + : : : "r0", "cc"); + #endif } } @@ -57,7 +57,7 @@ void asm_arm_end_pass(asm_arm_t *as) { STATIC void emit(asm_arm_t *as, uint op) { uint8_t *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4); if (c != NULL) { - *(uint32_t*)c = op; + *(uint32_t *)c = op; } } @@ -205,7 +205,7 @@ void asm_arm_mov_reg_i32(asm_arm_t *as, uint rd, int imm) { // mvn is "move not", not "move negative" emit_al(as, asm_arm_op_mvn_imm(rd, ~imm)); } else { - //Insert immediate into code and jump over it + // Insert immediate into code and jump over it emit_al(as, 0x59f0000 | (rd << 12)); // ldr rd, [pc] emit_al(as, 0xa000000); // b pc emit(as, imm); @@ -359,7 +359,7 @@ void asm_arm_bl_ind(asm_arm_t *as, void *fun_ptr, uint fun_id, uint reg_temp) { // Set lr after fun_ptr emit_al(as, asm_arm_op_add_imm(ASM_ARM_REG_LR, ASM_ARM_REG_PC, 4)); // add lr, pc, #4 emit_al(as, asm_arm_op_mov_reg(ASM_ARM_REG_PC, reg_temp)); // mov pc, reg_temp - emit(as, (uint) fun_ptr); + emit(as, (uint)fun_ptr); } #endif // MICROPY_EMIT_ARM diff --git a/py/asmbase.c b/py/asmbase.c index 4d080f095e..5cf8a78c26 100644 --- a/py/asmbase.c +++ b/py/asmbase.c @@ -51,7 +51,7 @@ void mp_asm_base_start_pass(mp_asm_base_t *as, int pass) { memset(as->label_offsets, -1, as->max_num_labels * sizeof(size_t)); } else { // allocating executable RAM is platform specific - MP_PLAT_ALLOC_EXEC(as->code_offset, (void**)&as->code_base, &as->code_size); + MP_PLAT_ALLOC_EXEC(as->code_offset, (void **)&as->code_base, &as->code_size); assert(as->code_base != NULL); } as->pass = pass; @@ -84,12 +84,12 @@ void mp_asm_base_label_assign(mp_asm_base_t *as, size_t label) { } // align must be a multiple of 2 -void mp_asm_base_align(mp_asm_base_t* as, unsigned int align) { +void mp_asm_base_align(mp_asm_base_t *as, unsigned int align) { as->code_offset = (as->code_offset + align - 1) & (~(align - 1)); } // this function assumes a little endian machine -void mp_asm_base_data(mp_asm_base_t* as, unsigned int bytesize, uintptr_t val) { +void mp_asm_base_data(mp_asm_base_t *as, unsigned int bytesize, uintptr_t val) { uint8_t *c = mp_asm_base_get_cur_to_write_bytes(as, bytesize); if (c != NULL) { for (unsigned int i = 0; i < bytesize; i++) { diff --git a/py/asmbase.h b/py/asmbase.h index 3b2f59d159..9ee7fe061d 100644 --- a/py/asmbase.h +++ b/py/asmbase.h @@ -47,8 +47,8 @@ void mp_asm_base_deinit(mp_asm_base_t *as, bool free_code); void mp_asm_base_start_pass(mp_asm_base_t *as, int pass); uint8_t *mp_asm_base_get_cur_to_write_bytes(mp_asm_base_t *as, size_t num_bytes_to_write); void mp_asm_base_label_assign(mp_asm_base_t *as, size_t label); -void mp_asm_base_align(mp_asm_base_t* as, unsigned int align); -void mp_asm_base_data(mp_asm_base_t* as, unsigned int bytesize, uintptr_t val); +void mp_asm_base_align(mp_asm_base_t *as, unsigned int align); +void mp_asm_base_data(mp_asm_base_t *as, unsigned int bytesize, uintptr_t val); static inline size_t mp_asm_base_get_code_pos(mp_asm_base_t *as) { return as->code_offset; diff --git a/py/asmthumb.c b/py/asmthumb.c index 3cf47c5b15..33ec420046 100644 --- a/py/asmthumb.c +++ b/py/asmthumb.c @@ -328,7 +328,7 @@ void asm_thumb_b_label(asm_thumb_t *as, uint label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: asm_thumb_op32(as, OP_BW_HI(rel), OP_BW_LO(rel)); } } @@ -347,7 +347,7 @@ void asm_thumb_bcc_label(asm_thumb_t *as, int cond, uint label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: asm_thumb_op32(as, OP_BCC_W_HI(cond, rel), OP_BCC_W_LO(rel)); } } diff --git a/py/asmthumb.h b/py/asmthumb.h index 32219eb55a..6acf305a2d 100644 --- a/py/asmthumb.h +++ b/py/asmthumb.h @@ -94,8 +94,9 @@ void asm_thumb_exit(asm_thumb_t *as); void asm_thumb_op16(asm_thumb_t *as, uint op); void asm_thumb_op32(asm_thumb_t *as, uint op1, uint op2); -static inline void asm_thumb_it_cc(asm_thumb_t *as, uint cc, uint mask) - { asm_thumb_op16(as, ASM_THUMB_OP_IT | (cc << 4) | mask); } +static inline void asm_thumb_it_cc(asm_thumb_t *as, uint cc, uint mask) { + asm_thumb_op16(as, ASM_THUMB_OP_IT | (cc << 4) | mask); +} // FORMAT 1: move shifted register @@ -128,14 +129,18 @@ static inline void asm_thumb_format_2(asm_thumb_t *as, uint op, uint rlo_dest, u asm_thumb_op16(as, ASM_THUMB_FORMAT_2_ENCODE(op, rlo_dest, rlo_src, src_b)); } -static inline void asm_thumb_add_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) - { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); } -static inline void asm_thumb_add_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) - { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); } -static inline void asm_thumb_sub_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) - { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); } -static inline void asm_thumb_sub_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) - { asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); } +static inline void asm_thumb_add_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) { + asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); +} +static inline void asm_thumb_add_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) { + asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_ADD | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); +} +static inline void asm_thumb_sub_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, uint rlo_src_b) { + asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_REG_OPERAND, rlo_dest, rlo_src_a, rlo_src_b); +} +static inline void asm_thumb_sub_rlo_rlo_i3(asm_thumb_t *as, uint rlo_dest, uint rlo_src_a, int i3_src) { + asm_thumb_format_2(as, ASM_THUMB_FORMAT_2_SUB | ASM_THUMB_FORMAT_2_IMM_OPERAND, rlo_dest, rlo_src_a, i3_src); +} // FORMAT 3: move/compare/add/subtract immediate // These instructions all do zero extension of the i8 value @@ -152,10 +157,18 @@ static inline void asm_thumb_format_3(asm_thumb_t *as, uint op, uint rlo, int i8 asm_thumb_op16(as, ASM_THUMB_FORMAT_3_ENCODE(op, rlo, i8)); } -static inline void asm_thumb_mov_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_MOV, rlo, i8); } -static inline void asm_thumb_cmp_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_CMP, rlo, i8); } -static inline void asm_thumb_add_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_ADD, rlo, i8); } -static inline void asm_thumb_sub_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_SUB, rlo, i8); } +static inline void asm_thumb_mov_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { + asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_MOV, rlo, i8); +} +static inline void asm_thumb_cmp_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { + asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_CMP, rlo, i8); +} +static inline void asm_thumb_add_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { + asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_ADD, rlo, i8); +} +static inline void asm_thumb_sub_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { + asm_thumb_format_3(as, ASM_THUMB_FORMAT_3_SUB, rlo, i8); +} // FORMAT 4: ALU operations @@ -178,7 +191,9 @@ static inline void asm_thumb_sub_rlo_i8(asm_thumb_t *as, uint rlo, int i8) { asm void asm_thumb_format_4(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_src); -static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src) { asm_thumb_format_4(as, ASM_THUMB_FORMAT_4_CMP, rlo_dest, rlo_src); } +static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_src) { + asm_thumb_format_4(as, ASM_THUMB_FORMAT_4_CMP, rlo_dest, rlo_src); +} // FORMAT 9: load/store with immediate offset // For word transfers the offset must be aligned, and >>2 @@ -198,21 +213,28 @@ static inline void asm_thumb_cmp_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rl #define ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset) \ ((op) | (((offset) << 6) & 0x07c0) | ((rlo_base) << 3) | (rlo_dest)) -static inline void asm_thumb_format_9_10(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_base, uint offset) - { asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset)); } +static inline void asm_thumb_format_9_10(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_base, uint offset) { + asm_thumb_op16(as, ASM_THUMB_FORMAT_9_10_ENCODE(op, rlo_dest, rlo_base, offset)); +} -static inline void asm_thumb_str_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint word_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_src, rlo_base, word_offset); } -static inline void asm_thumb_strb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_src, rlo_base, byte_offset); } -static inline void asm_thumb_strh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_STRH, rlo_src, rlo_base, byte_offset); } -static inline void asm_thumb_ldr_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint word_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_dest, rlo_base, word_offset); } -static inline void asm_thumb_ldrb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER , rlo_dest, rlo_base, byte_offset); } -static inline void asm_thumb_ldrh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) - { asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_LDRH, rlo_dest, rlo_base, byte_offset); } +static inline void asm_thumb_str_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint word_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_src, rlo_base, word_offset); +} +static inline void asm_thumb_strb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_STR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_src, rlo_base, byte_offset); +} +static inline void asm_thumb_strh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint byte_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_STRH, rlo_src, rlo_base, byte_offset); +} +static inline void asm_thumb_ldr_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint word_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER, rlo_dest, rlo_base, word_offset); +} +static inline void asm_thumb_ldrb_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_BYTE_TRANSFER, rlo_dest, rlo_base, byte_offset); +} +static inline void asm_thumb_ldrh_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint byte_offset) { + asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_LDRH, rlo_dest, rlo_base, byte_offset); +} // TODO convert these to above format style diff --git a/py/asmx64.c b/py/asmx64.c index 8706b806e5..4e45f77a40 100644 --- a/py/asmx64.c +++ b/py/asmx64.c @@ -63,15 +63,15 @@ #define OPCODE_SUB_R64_FROM_RM64 (0x29) #define OPCODE_SUB_I32_FROM_RM64 (0x81) /* /5 */ #define OPCODE_SUB_I8_FROM_RM64 (0x83) /* /5 */ -//#define OPCODE_SHL_RM32_BY_I8 (0xc1) /* /4 */ -//#define OPCODE_SHR_RM32_BY_I8 (0xc1) /* /5 */ -//#define OPCODE_SAR_RM32_BY_I8 (0xc1) /* /7 */ +// #define OPCODE_SHL_RM32_BY_I8 (0xc1) /* /4 */ +// #define OPCODE_SHR_RM32_BY_I8 (0xc1) /* /5 */ +// #define OPCODE_SAR_RM32_BY_I8 (0xc1) /* /7 */ #define OPCODE_SHL_RM64_CL (0xd3) /* /4 */ #define OPCODE_SAR_RM64_CL (0xd3) /* /7 */ -//#define OPCODE_CMP_I32_WITH_RM32 (0x81) /* /7 */ -//#define OPCODE_CMP_I8_WITH_RM32 (0x83) /* /7 */ +// #define OPCODE_CMP_I32_WITH_RM32 (0x81) /* /7 */ +// #define OPCODE_CMP_I8_WITH_RM32 (0x83) /* /7 */ #define OPCODE_CMP_R64_WITH_RM64 (0x39) /* /r */ -//#define OPCODE_CMP_RM32_WITH_R32 (0x3b) +// #define OPCODE_CMP_RM32_WITH_R32 (0x3b) #define OPCODE_TEST_R8_WITH_RM8 (0x84) /* /r */ #define OPCODE_JMP_REL8 (0xeb) #define OPCODE_JMP_REL32 (0xe9) @@ -121,14 +121,14 @@ static inline byte *asm_x64_get_cur_to_write_bytes(asm_x64_t *as, int n) { } STATIC void asm_x64_write_byte_1(asm_x64_t *as, byte b1) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 1); + byte *c = asm_x64_get_cur_to_write_bytes(as, 1); if (c != NULL) { c[0] = b1; } } STATIC void asm_x64_write_byte_2(asm_x64_t *as, byte b1, byte b2) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 2); + byte *c = asm_x64_get_cur_to_write_bytes(as, 2); if (c != NULL) { c[0] = b1; c[1] = b2; @@ -136,7 +136,7 @@ STATIC void asm_x64_write_byte_2(asm_x64_t *as, byte b1, byte b2) { } STATIC void asm_x64_write_byte_3(asm_x64_t *as, byte b1, byte b2, byte b3) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 3); + byte *c = asm_x64_get_cur_to_write_bytes(as, 3); if (c != NULL) { c[0] = b1; c[1] = b2; @@ -145,7 +145,7 @@ STATIC void asm_x64_write_byte_3(asm_x64_t *as, byte b1, byte b2, byte b3) { } STATIC void asm_x64_write_word32(asm_x64_t *as, int w32) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 4); + byte *c = asm_x64_get_cur_to_write_bytes(as, 4); if (c != NULL) { c[0] = IMM32_L0(w32); c[1] = IMM32_L1(w32); @@ -155,7 +155,7 @@ STATIC void asm_x64_write_word32(asm_x64_t *as, int w32) { } STATIC void asm_x64_write_word64(asm_x64_t *as, int64_t w64) { - byte* c = asm_x64_get_cur_to_write_bytes(as, 8); + byte *c = asm_x64_get_cur_to_write_bytes(as, 8); if (c != NULL) { c[0] = IMM32_L0(w64); c[1] = IMM32_L1(w64); @@ -382,11 +382,11 @@ void asm_x64_xor_r64_r64(asm_x64_t *as, int dest_r64, int src_r64) { asm_x64_generic_r64_r64(as, dest_r64, src_r64, OPCODE_XOR_R64_TO_RM64); } -void asm_x64_shl_r64_cl(asm_x64_t* as, int dest_r64) { +void asm_x64_shl_r64_cl(asm_x64_t *as, int dest_r64) { asm_x64_generic_r64_r64(as, dest_r64, 4, OPCODE_SHL_RM64_CL); } -void asm_x64_sar_r64_cl(asm_x64_t* as, int dest_r64) { +void asm_x64_sar_r64_cl(asm_x64_t *as, int dest_r64) { asm_x64_generic_r64_r64(as, dest_r64, 7, OPCODE_SAR_RM64_CL); } @@ -496,7 +496,7 @@ void asm_x64_jmp_label(asm_x64_t *as, mp_uint_t label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: rel -= 5; asm_x64_write_byte_1(as, OPCODE_JMP_REL32); asm_x64_write_word32(as, rel); @@ -518,7 +518,7 @@ void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: rel -= 6; asm_x64_write_byte_2(as, OPCODE_JCC_REL32_A, OPCODE_JCC_REL32_B | jcc_type); asm_x64_write_word32(as, rel); @@ -612,12 +612,12 @@ void asm_x64_call_i1(asm_x64_t *as, void* func, int i1) { void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r64) { assert(temp_r64 < 8); -#ifdef __LP64__ + #ifdef __LP64__ asm_x64_mov_i64_to_r64_optimised(as, (int64_t)ptr, temp_r64); -#else + #else // If we get here, sizeof(int) == sizeof(void*). asm_x64_mov_i64_to_r64_optimised(as, (int64_t)(unsigned int)ptr, temp_r64); -#endif + #endif asm_x64_write_byte_2(as, OPCODE_CALL_RM32, MODRM_R64(2) | MODRM_RM_REG | MODRM_RM_R64(temp_r64)); // this reduces code size by 2 bytes per call, but doesn't seem to speed it up at all // doesn't work anymore because calls are 64 bits away diff --git a/py/asmx64.h b/py/asmx64.h index 113d925119..804e3b7098 100644 --- a/py/asmx64.h +++ b/py/asmx64.h @@ -79,11 +79,11 @@ static inline void asm_x64_end_pass(asm_x64_t *as) { (void)as; } -void asm_x64_nop(asm_x64_t* as); -void asm_x64_push_r64(asm_x64_t* as, int src_r64); -void asm_x64_pop_r64(asm_x64_t* as, int dest_r64); -void asm_x64_mov_r64_r64(asm_x64_t* as, int dest_r64, int src_r64); -void asm_x64_mov_i64_to_r64(asm_x64_t* as, int64_t src_i64, int dest_r64); +void asm_x64_nop(asm_x64_t *as); +void asm_x64_push_r64(asm_x64_t *as, int src_r64); +void asm_x64_pop_r64(asm_x64_t *as, int dest_r64); +void asm_x64_mov_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); +void asm_x64_mov_i64_to_r64(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_i64_to_r64_optimised(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_i64_to_r64_aligned(asm_x64_t *as, int64_t src_i64, int dest_r64); void asm_x64_mov_r8_to_mem8(asm_x64_t *as, int src_r64, int dest_r64, int dest_disp); @@ -97,22 +97,22 @@ void asm_x64_mov_mem64_to_r64(asm_x64_t *as, int src_r64, int src_disp, int dest void asm_x64_and_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_or_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); void asm_x64_xor_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); -void asm_x64_shl_r64_cl(asm_x64_t* as, int dest_r64); -void asm_x64_sar_r64_cl(asm_x64_t* as, int dest_r64); -void asm_x64_add_r64_r64(asm_x64_t* as, int dest_r64, int src_r64); -void asm_x64_sub_r64_r64(asm_x64_t* as, int dest_r64, int src_r64); -void asm_x64_mul_r64_r64(asm_x64_t* as, int dest_r64, int src_r64); -void asm_x64_cmp_r64_with_r64(asm_x64_t* as, int src_r64_a, int src_r64_b); -void asm_x64_test_r8_with_r8(asm_x64_t* as, int src_r64_a, int src_r64_b); -void asm_x64_setcc_r8(asm_x64_t* as, int jcc_type, int dest_r8); -void asm_x64_jmp_label(asm_x64_t* as, mp_uint_t label); -void asm_x64_jcc_label(asm_x64_t* as, int jcc_type, mp_uint_t label); -void asm_x64_entry(asm_x64_t* as, int num_locals); -void asm_x64_exit(asm_x64_t* as); -void asm_x64_mov_local_to_r64(asm_x64_t* as, int src_local_num, int dest_r64); -void asm_x64_mov_r64_to_local(asm_x64_t* as, int src_r64, int dest_local_num); -void asm_x64_mov_local_addr_to_r64(asm_x64_t* as, int local_num, int dest_r64); -void asm_x64_call_ind(asm_x64_t* as, void* ptr, int temp_r32); +void asm_x64_shl_r64_cl(asm_x64_t *as, int dest_r64); +void asm_x64_sar_r64_cl(asm_x64_t *as, int dest_r64); +void asm_x64_add_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); +void asm_x64_sub_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); +void asm_x64_mul_r64_r64(asm_x64_t *as, int dest_r64, int src_r64); +void asm_x64_cmp_r64_with_r64(asm_x64_t *as, int src_r64_a, int src_r64_b); +void asm_x64_test_r8_with_r8(asm_x64_t *as, int src_r64_a, int src_r64_b); +void asm_x64_setcc_r8(asm_x64_t *as, int jcc_type, int dest_r8); +void asm_x64_jmp_label(asm_x64_t *as, mp_uint_t label); +void asm_x64_jcc_label(asm_x64_t *as, int jcc_type, mp_uint_t label); +void asm_x64_entry(asm_x64_t *as, int num_locals); +void asm_x64_exit(asm_x64_t *as); +void asm_x64_mov_local_to_r64(asm_x64_t *as, int src_local_num, int dest_r64); +void asm_x64_mov_r64_to_local(asm_x64_t *as, int src_r64, int dest_local_num); +void asm_x64_mov_local_addr_to_r64(asm_x64_t *as, int local_num, int dest_r64); +void asm_x64_call_ind(asm_x64_t *as, void *ptr, int temp_r32); #if defined(GENERIC_ASM_API) && GENERIC_ASM_API diff --git a/py/asmx86.c b/py/asmx86.c index 8a08c68a03..05783354ed 100644 --- a/py/asmx86.c +++ b/py/asmx86.c @@ -41,13 +41,13 @@ #define OPCODE_NOP (0x90) #define OPCODE_PUSH_R32 (0x50) -//#define OPCODE_PUSH_I32 (0x68) -//#define OPCODE_PUSH_M32 (0xff) /* /6 */ +// #define OPCODE_PUSH_I32 (0x68) +// #define OPCODE_PUSH_M32 (0xff) /* /6 */ #define OPCODE_POP_R32 (0x58) #define OPCODE_RET (0xc3) -//#define OPCODE_MOV_I8_TO_R8 (0xb0) /* +rb */ +// #define OPCODE_MOV_I8_TO_R8 (0xb0) /* +rb */ #define OPCODE_MOV_I32_TO_R32 (0xb8) -//#define OPCODE_MOV_I32_TO_RM32 (0xc7) +// #define OPCODE_MOV_I32_TO_RM32 (0xc7) #define OPCODE_MOV_R8_TO_RM8 (0x88) /* /r */ #define OPCODE_MOV_R32_TO_RM32 (0x89) /* /r */ #define OPCODE_MOV_RM32_TO_R32 (0x8b) /* /r */ @@ -63,15 +63,15 @@ #define OPCODE_SUB_R32_FROM_RM32 (0x29) #define OPCODE_SUB_I32_FROM_RM32 (0x81) /* /5 */ #define OPCODE_SUB_I8_FROM_RM32 (0x83) /* /5 */ -//#define OPCODE_SHL_RM32_BY_I8 (0xc1) /* /4 */ -//#define OPCODE_SHR_RM32_BY_I8 (0xc1) /* /5 */ -//#define OPCODE_SAR_RM32_BY_I8 (0xc1) /* /7 */ +// #define OPCODE_SHL_RM32_BY_I8 (0xc1) /* /4 */ +// #define OPCODE_SHR_RM32_BY_I8 (0xc1) /* /5 */ +// #define OPCODE_SAR_RM32_BY_I8 (0xc1) /* /7 */ #define OPCODE_SHL_RM32_CL (0xd3) /* /4 */ #define OPCODE_SAR_RM32_CL (0xd3) /* /7 */ -//#define OPCODE_CMP_I32_WITH_RM32 (0x81) /* /7 */ -//#define OPCODE_CMP_I8_WITH_RM32 (0x83) /* /7 */ +// #define OPCODE_CMP_I32_WITH_RM32 (0x81) /* /7 */ +// #define OPCODE_CMP_I8_WITH_RM32 (0x83) /* /7 */ #define OPCODE_CMP_R32_WITH_RM32 (0x39) -//#define OPCODE_CMP_RM32_WITH_R32 (0x3b) +// #define OPCODE_CMP_RM32_WITH_R32 (0x3b) #define OPCODE_TEST_R8_WITH_RM8 (0x84) /* /r */ #define OPCODE_JMP_REL8 (0xeb) #define OPCODE_JMP_REL32 (0xe9) @@ -101,14 +101,14 @@ #define SIGNED_FIT8(x) (((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80) STATIC void asm_x86_write_byte_1(asm_x86_t *as, byte b1) { - byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 1); + byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 1); if (c != NULL) { c[0] = b1; } } STATIC void asm_x86_write_byte_2(asm_x86_t *as, byte b1, byte b2) { - byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 2); + byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 2); if (c != NULL) { c[0] = b1; c[1] = b2; @@ -116,7 +116,7 @@ STATIC void asm_x86_write_byte_2(asm_x86_t *as, byte b1, byte b2) { } STATIC void asm_x86_write_byte_3(asm_x86_t *as, byte b1, byte b2, byte b3) { - byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 3); + byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 3); if (c != NULL) { c[0] = b1; c[1] = b2; @@ -125,7 +125,7 @@ STATIC void asm_x86_write_byte_3(asm_x86_t *as, byte b1, byte b2, byte b3) { } STATIC void asm_x86_write_word32(asm_x86_t *as, int w32) { - byte* c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4); + byte *c = mp_asm_base_get_cur_to_write_bytes(&as->base, 4); if (c != NULL) { c[0] = IMM32_L0(w32); c[1] = IMM32_L1(w32); @@ -250,11 +250,11 @@ void asm_x86_xor_r32_r32(asm_x86_t *as, int dest_r32, int src_r32) { asm_x86_generic_r32_r32(as, dest_r32, src_r32, OPCODE_XOR_R32_TO_RM32); } -void asm_x86_shl_r32_cl(asm_x86_t* as, int dest_r32) { +void asm_x86_shl_r32_cl(asm_x86_t *as, int dest_r32) { asm_x86_generic_r32_r32(as, dest_r32, 4, OPCODE_SHL_RM32_CL); } -void asm_x86_sar_r32_cl(asm_x86_t* as, int dest_r32) { +void asm_x86_sar_r32_cl(asm_x86_t *as, int dest_r32) { asm_x86_generic_r32_r32(as, dest_r32, 7, OPCODE_SAR_RM32_CL); } @@ -358,7 +358,7 @@ void asm_x86_jmp_label(asm_x86_t *as, mp_uint_t label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: rel -= 5; asm_x86_write_byte_1(as, OPCODE_JMP_REL32); asm_x86_write_word32(as, rel); @@ -380,7 +380,7 @@ void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label) { } } else { // is a forwards jump, so need to assume it's large - large_jump: + large_jump: rel -= 6; asm_x86_write_byte_2(as, OPCODE_JCC_REL32_A, OPCODE_JCC_REL32_B | jcc_type); asm_x86_write_word32(as, rel); @@ -462,8 +462,7 @@ void asm_x86_push_local(asm_x86_t *as, int local_num) { asm_x86_push_disp(as, ASM_X86_REG_EBP, asm_x86_local_offset_from_ebp(as, local_num)); } -void asm_x86_push_local_addr(asm_x86_t *as, int local_num, int temp_r32) -{ +void asm_x86_push_local_addr(asm_x86_t *as, int local_num, int temp_r32) { asm_x86_mov_r32_r32(as, temp_r32, ASM_X86_REG_EBP); asm_x86_add_i32_to_r32(as, asm_x86_local_offset_from_ebp(as, local_num), temp_r32); asm_x86_push_r32(as, temp_r32); @@ -488,14 +487,14 @@ void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32) if (n_args > 0) { asm_x86_push_r32(as, ASM_X86_REG_ARG_1); } -#ifdef __LP64__ + #ifdef __LP64__ // We wouldn't run x86 code on an x64 machine. This is here to enable // testing of the x86 emitter only. asm_x86_mov_i32_to_r32(as, (int32_t)(int64_t)ptr, temp_r32); -#else + #else // If we get here, sizeof(int) == sizeof(void*). asm_x86_mov_i32_to_r32(as, (int32_t)ptr, temp_r32); -#endif + #endif asm_x86_write_byte_2(as, OPCODE_CALL_RM32, MODRM_R32(2) | MODRM_RM_REG | MODRM_RM_R32(temp_r32)); // this reduces code size by 2 bytes per call, but doesn't seem to speed it up at all /* diff --git a/py/asmx86.h b/py/asmx86.h index 05902350fc..1fa7ff7383 100644 --- a/py/asmx86.h +++ b/py/asmx86.h @@ -82,7 +82,7 @@ static inline void asm_x86_end_pass(asm_x86_t *as) { (void)as; } -void asm_x86_mov_r32_r32(asm_x86_t* as, int dest_r32, int src_r32); +void asm_x86_mov_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_mov_i32_to_r32(asm_x86_t *as, int32_t src_i32, int dest_r32); void asm_x86_mov_i32_to_r32_aligned(asm_x86_t *as, int32_t src_i32, int dest_r32); void asm_x86_mov_r8_to_mem8(asm_x86_t *as, int src_r32, int dest_r32, int dest_disp); @@ -94,23 +94,23 @@ void asm_x86_mov_mem32_to_r32(asm_x86_t *as, int src_r32, int src_disp, int dest void asm_x86_and_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_or_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); void asm_x86_xor_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); -void asm_x86_shl_r32_cl(asm_x86_t* as, int dest_r32); -void asm_x86_sar_r32_cl(asm_x86_t* as, int dest_r32); -void asm_x86_add_r32_r32(asm_x86_t* as, int dest_r32, int src_r32); -void asm_x86_sub_r32_r32(asm_x86_t* as, int dest_r32, int src_r32); -void asm_x86_mul_r32_r32(asm_x86_t* as, int dest_r32, int src_r32); -void asm_x86_cmp_r32_with_r32(asm_x86_t* as, int src_r32_a, int src_r32_b); -void asm_x86_test_r8_with_r8(asm_x86_t* as, int src_r32_a, int src_r32_b); -void asm_x86_setcc_r8(asm_x86_t* as, mp_uint_t jcc_type, int dest_r8); -void asm_x86_jmp_label(asm_x86_t* as, mp_uint_t label); -void asm_x86_jcc_label(asm_x86_t* as, mp_uint_t jcc_type, mp_uint_t label); -void asm_x86_entry(asm_x86_t* as, int num_locals); -void asm_x86_exit(asm_x86_t* as); +void asm_x86_shl_r32_cl(asm_x86_t *as, int dest_r32); +void asm_x86_sar_r32_cl(asm_x86_t *as, int dest_r32); +void asm_x86_add_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); +void asm_x86_sub_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); +void asm_x86_mul_r32_r32(asm_x86_t *as, int dest_r32, int src_r32); +void asm_x86_cmp_r32_with_r32(asm_x86_t *as, int src_r32_a, int src_r32_b); +void asm_x86_test_r8_with_r8(asm_x86_t *as, int src_r32_a, int src_r32_b); +void asm_x86_setcc_r8(asm_x86_t *as, mp_uint_t jcc_type, int dest_r8); +void asm_x86_jmp_label(asm_x86_t *as, mp_uint_t label); +void asm_x86_jcc_label(asm_x86_t *as, mp_uint_t jcc_type, mp_uint_t label); +void asm_x86_entry(asm_x86_t *as, int num_locals); +void asm_x86_exit(asm_x86_t *as); void asm_x86_mov_arg_to_r32(asm_x86_t *as, int src_arg_num, int dest_r32); -void asm_x86_mov_local_to_r32(asm_x86_t* as, int src_local_num, int dest_r32); -void asm_x86_mov_r32_to_local(asm_x86_t* as, int src_r32, int dest_local_num); -void asm_x86_mov_local_addr_to_r32(asm_x86_t* as, int local_num, int dest_r32); -void asm_x86_call_ind(asm_x86_t* as, void* ptr, mp_uint_t n_args, int temp_r32); +void asm_x86_mov_local_to_r32(asm_x86_t *as, int src_local_num, int dest_r32); +void asm_x86_mov_r32_to_local(asm_x86_t *as, int src_r32, int dest_local_num); +void asm_x86_mov_local_addr_to_r32(asm_x86_t *as, int local_num, int dest_r32); +void asm_x86_call_ind(asm_x86_t *as, void *ptr, mp_uint_t n_args, int temp_r32); #if defined(GENERIC_ASM_API) && GENERIC_ASM_API diff --git a/py/asmxtensa.c b/py/asmxtensa.c index 98b49ecb5e..5678eafd1d 100644 --- a/py/asmxtensa.c +++ b/py/asmxtensa.c @@ -65,7 +65,7 @@ void asm_xtensa_entry(asm_xtensa_t *as, int num_locals) { // jump over the constants asm_xtensa_op_j(as, as->num_const * WORD_SIZE + 4 - 4); mp_asm_base_get_cur_to_write_bytes(&as->base, 1); // padding/alignment byte - as->const_table = (uint32_t*)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4); + as->const_table = (uint32_t *)mp_asm_base_get_cur_to_write_bytes(&as->base, as->num_const * 4); // adjust the stack-pointer to store a0, a12, a13, a14 and locals, 16-byte aligned as->stack_adjust = (((4 + num_locals) * WORD_SIZE) + 15) & ~15; diff --git a/py/bc.c b/py/bc.c index 01131cb4c0..40a70fe515 100644 --- a/py/bc.c +++ b/py/bc.c @@ -73,21 +73,21 @@ const byte *mp_decode_uint_skip(const byte *ptr) { } STATIC NORETURN void fun_pos_args_mismatch(mp_obj_fun_bc_t *f, size_t expected, size_t given) { -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE // generic message, used also for other argument issues (void)f; (void)expected; (void)given; mp_arg_error_terse_mismatch(); -#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL + #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL (void)f; mp_raise_TypeError_varg( translate("function takes %d positional arguments but %d were given"), expected, given); -#elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED mp_raise_TypeError_varg( translate("%q() takes %d positional arguments but %d were given"), mp_obj_fun_get_name(MP_OBJ_FROM_PTR(f)), expected, given); -#endif + #endif } #if DEBUG_PRINT @@ -130,7 +130,7 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw size_t n_def_pos_args = *code_state->ip++; code_state->sp = &code_state->state[0] - 1; - code_state->exc_sp = (mp_exc_stack_t*)(code_state->state + n_state) - 1; + code_state->exc_sp = (mp_exc_stack_t *)(code_state->state + n_state) - 1; // zero out the local stack to begin with memset(code_state->state, 0, n_state * sizeof(*code_state->state)); @@ -187,16 +187,16 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw } // get pointer to arg_names array - const mp_obj_t *arg_names = (const mp_obj_t*)self->const_table; + const mp_obj_t *arg_names = (const mp_obj_t *)self->const_table; for (size_t i = 0; i < n_kw; i++) { // the keys in kwargs are expected to be qstr objects mp_obj_t wanted_arg_name = kwargs[2 * i]; - if(MP_UNLIKELY(!MP_OBJ_IS_QSTR(wanted_arg_name))) { + if (MP_UNLIKELY(!MP_OBJ_IS_QSTR(wanted_arg_name))) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("unexpected keyword argument")); + mp_raise_TypeError(translate("unexpected keyword argument")); #else - mp_raise_TypeError(translate("keywords must be strings")); + mp_raise_TypeError(translate("keywords must be strings")); #endif } for (size_t j = 0; j < n_pos_args + n_kwonly_args; j++) { @@ -212,14 +212,14 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw // Didn't find name match with positional args if ((scope_flags & MP_SCOPE_FLAG_VARKEYWORDS) == 0) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("unexpected keyword argument")); + mp_raise_TypeError(translate("unexpected keyword argument")); #else - mp_raise_TypeError_varg( - translate("unexpected keyword argument '%q'"), MP_OBJ_QSTR_VALUE(wanted_arg_name)); + mp_raise_TypeError_varg( + translate("unexpected keyword argument '%q'"), MP_OBJ_QSTR_VALUE(wanted_arg_name)); #endif } mp_obj_dict_store(dict, kwargs[2 * i], kwargs[2 * i + 1]); -continue2:; + continue2:; } DEBUG_printf("Args with kws flattened: "); @@ -251,7 +251,7 @@ continue2:; if (code_state->state[n_state - 1 - n_pos_args - i] == MP_OBJ_NULL) { mp_map_elem_t *elem = NULL; if ((scope_flags & MP_SCOPE_FLAG_DEFKWARGS) != 0) { - elem = mp_map_lookup(&((mp_obj_dict_t*)MP_OBJ_TO_PTR(self->extra_args[n_def_pos_args]))->map, arg_names[n_pos_args + i], MP_MAP_LOOKUP); + elem = mp_map_lookup(&((mp_obj_dict_t *)MP_OBJ_TO_PTR(self->extra_args[n_def_pos_args]))->map, arg_names[n_pos_args + i], MP_MAP_LOOKUP); } if (elem != NULL) { code_state->state[n_state - 1 - n_pos_args - i] = elem->value; @@ -408,7 +408,7 @@ uint mp_opcode_format(const byte *ip, size_t *opcode_size) { || *ip == MP_BC_LOAD_ATTR || *ip == MP_BC_STORE_ATTR #endif - ); + ); ip += 1; if (f == MP_OPCODE_VAR_UINT) { while ((*ip++ & 0x80) != 0) { diff --git a/py/bc.h b/py/bc.h index b71325f92b..6f62711c87 100644 --- a/py/bc.h +++ b/py/bc.h @@ -86,7 +86,7 @@ typedef struct _mp_code_state_t { // Variable-length mp_obj_t state[0]; // Variable-length, never accessed by name, only as (void*)(state + n_state) - //mp_exc_stack_t exc_state[0]; + // mp_exc_stack_t exc_state[0]; } mp_code_state_t; mp_uint_t mp_decode_uint(const byte **ptr); @@ -102,10 +102,10 @@ const byte *mp_bytecode_print_str(const byte *ip); #define mp_bytecode_print_inst(code, const_table) mp_bytecode_print2(code, 1, const_table) // Helper macros to access pointer with least significant bits holding flags -#define MP_TAGPTR_PTR(x) ((void*)((uintptr_t)(x) & ~((uintptr_t)3))) +#define MP_TAGPTR_PTR(x) ((void *)((uintptr_t)(x) & ~((uintptr_t)3))) #define MP_TAGPTR_TAG0(x) ((uintptr_t)(x) & 1) #define MP_TAGPTR_TAG1(x) ((uintptr_t)(x) & 2) -#define MP_TAGPTR_MAKE(ptr, tag) ((void*)((uintptr_t)(ptr) | (tag))) +#define MP_TAGPTR_MAKE(ptr, tag) ((void *)((uintptr_t)(ptr) | (tag))) #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE diff --git a/py/binary.c b/py/binary.c index b85edba625..846058525f 100644 --- a/py/binary.c +++ b/py/binary.c @@ -47,26 +47,43 @@ size_t mp_binary_get_size(char struct_type, char val_type, mp_uint_t *palign) { size_t size = 0; int align = 1; switch (struct_type) { - case '<': case '>': + case '<': + case '>': switch (val_type) { - case 'b': case 'B': case 'x': - size = 1; break; - case 'h': case 'H': - size = 2; break; - case 'i': case 'I': - size = 4; break; - case 'l': case 'L': - size = 4; break; - case 'q': case 'Q': - size = 8; break; -#if MICROPY_NONSTANDARD_TYPECODES - case 'P': case 'O': case 'S': - size = sizeof(void*); break; -#endif + case 'b': + case 'B': + case 'x': + size = 1; + break; + case 'h': + case 'H': + size = 2; + break; + case 'i': + case 'I': + size = 4; + break; + case 'l': + case 'L': + size = 4; + break; + case 'q': + case 'Q': + size = 8; + break; + #if MICROPY_NONSTANDARD_TYPECODES + case 'P': + case 'O': + case 'S': + size = sizeof(void *); + break; + #endif case 'f': - size = sizeof(float); break; + size = sizeof(float); + break; case 'd': - size = sizeof(double); break; + size = sizeof(double); + break; } break; case '@': { @@ -79,31 +96,47 @@ size_t mp_binary_get_size(char struct_type, char val_type, mp_uint_t *palign) { // particular (or any) ABI. switch (val_type) { case BYTEARRAY_TYPECODE: - case 'b': case 'B': case 'x': - align = size = 1; break; - case 'h': case 'H': + case 'b': + case 'B': + case 'x': + align = size = 1; + break; + case 'h': + case 'H': align = alignof(short); - size = sizeof(short); break; - case 'i': case 'I': + size = sizeof(short); + break; + case 'i': + case 'I': align = alignof(int); - size = sizeof(int); break; - case 'l': case 'L': + size = sizeof(int); + break; + case 'l': + case 'L': align = alignof(long); - size = sizeof(long); break; - case 'q': case 'Q': + size = sizeof(long); + break; + case 'q': + case 'Q': align = alignof(long long); - size = sizeof(long long); break; -#if MICROPY_NONSTANDARD_TYPECODES - case 'P': case 'O': case 'S': - align = alignof(void*); - size = sizeof(void*); break; -#endif + size = sizeof(long long); + break; + #if MICROPY_NONSTANDARD_TYPECODES + case 'P': + case 'O': + case 'S': + align = alignof(void *); + size = sizeof(void *); + break; + #endif case 'f': align = alignof(float); - size = sizeof(float); break; + size = sizeof(float); + break; case 'd': align = alignof(double); - size = sizeof(double); break; + size = sizeof(double); + break; } } } @@ -122,46 +155,46 @@ mp_obj_t mp_binary_get_val_array(char typecode, void *p, mp_uint_t index) { mp_int_t val = 0; switch (typecode) { case 'b': - val = ((signed char*)p)[index]; + val = ((signed char *)p)[index]; break; case BYTEARRAY_TYPECODE: case 'B': - val = ((unsigned char*)p)[index]; + val = ((unsigned char *)p)[index]; break; case 'h': - val = ((short*)p)[index]; + val = ((short *)p)[index]; break; case 'H': - val = ((unsigned short*)p)[index]; + val = ((unsigned short *)p)[index]; break; case 'i': - return mp_obj_new_int(((int*)p)[index]); + return mp_obj_new_int(((int *)p)[index]); case 'I': - return mp_obj_new_int_from_uint(((unsigned int*)p)[index]); + return mp_obj_new_int_from_uint(((unsigned int *)p)[index]); case 'l': - return mp_obj_new_int(((long*)p)[index]); + return mp_obj_new_int(((long *)p)[index]); case 'L': - return mp_obj_new_int_from_uint(((unsigned long*)p)[index]); + return mp_obj_new_int_from_uint(((unsigned long *)p)[index]); #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE case 'q': - return mp_obj_new_int_from_ll(((long long*)p)[index]); + return mp_obj_new_int_from_ll(((long long *)p)[index]); case 'Q': - return mp_obj_new_int_from_ull(((unsigned long long*)p)[index]); + return mp_obj_new_int_from_ull(((unsigned long long *)p)[index]); #endif -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'f': - return mp_obj_new_float(((float*)p)[index]); + return mp_obj_new_float(((float *)p)[index]); case 'd': - return mp_obj_new_float(((double*)p)[index]); -#endif -#if MICROPY_NONSTANDARD_TYPECODES + return mp_obj_new_float(((double *)p)[index]); + #endif + #if MICROPY_NONSTANDARD_TYPECODES // Extension to CPython: array of objects case 'O': - return ((mp_obj_t*)p)[index]; + return ((mp_obj_t *)p)[index]; // Extension to CPython: array of pointers case 'P': - return mp_obj_new_int((mp_int_t)(uintptr_t)((void**)p)[index]); -#endif + return mp_obj_new_int((mp_int_t)(uintptr_t)((void **)p)[index]); + #endif } return MP_OBJ_NEW_SMALL_INT(val); } @@ -199,7 +232,7 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr) { size_t size = mp_binary_get_size(struct_type, val_type, &align); if (struct_type == '@') { // Make pointer aligned - p = (byte*)MP_ALIGN(p, (size_t)align); + p = (byte *)MP_ALIGN(p, (size_t)align); #if MP_ENDIANNESS_LITTLE struct_type = '<'; #else @@ -212,19 +245,23 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte **ptr) { if (MICROPY_NONSTANDARD_TYPECODES && (val_type == 'O')) { return (mp_obj_t)(mp_uint_t)val; -#if MICROPY_NONSTANDARD_TYPECODES + #if MICROPY_NONSTANDARD_TYPECODES } else if (val_type == 'S') { - const char *s_val = (const char*)(uintptr_t)(mp_uint_t)val; + const char *s_val = (const char *)(uintptr_t)(mp_uint_t)val; return mp_obj_new_str(s_val, strlen(s_val)); -#endif -#if MICROPY_PY_BUILTINS_FLOAT + #endif + #if MICROPY_PY_BUILTINS_FLOAT } else if (val_type == 'f') { - union { uint32_t i; float f; } fpu = {val}; - return mp_obj_new_float((mp_float_t) fpu.f); + union { uint32_t i; + float f; + } fpu = {val}; + return mp_obj_new_float((mp_float_t)fpu.f); } else if (val_type == 'd') { - union { uint64_t i; double f; } fpu = {val}; + union { uint64_t i; + double f; + } fpu = {val}; return mp_obj_new_float(fpu.f); -#endif + #endif } else if (is_signed(val_type)) { if ((long long)MP_SMALL_INT_MIN <= val && val <= (long long)MP_SMALL_INT_MAX) { return mp_obj_new_int((mp_int_t)val); @@ -245,13 +282,13 @@ void mp_binary_set_int(mp_uint_t val_sz, bool big_endian, byte *dest, mp_uint_t memcpy(dest, &val, val_sz); } else if (MP_ENDIANNESS_BIG && big_endian) { // only copy the least-significant val_sz bytes - memcpy(dest, (byte*)&val + sizeof(mp_uint_t) - val_sz, val_sz); + memcpy(dest, (byte *)&val + sizeof(mp_uint_t) - val_sz, val_sz); } else { const byte *src; if (MP_ENDIANNESS_LITTLE) { - src = (const byte*)&val + val_sz; + src = (const byte *)&val + val_sz; } else { - src = (const byte*)&val + sizeof(mp_uint_t); + src = (const byte *)&val + sizeof(mp_uint_t); } while (val_sz--) { *dest++ = *--src; @@ -266,7 +303,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** size_t size = mp_binary_get_size(struct_type, val_type, &align); if (struct_type == '@') { // Make pointer aligned - p = (byte*)MP_ALIGN(p, (size_t)align); + p = (byte *)MP_ALIGN(p, (size_t)align); if (MP_ENDIANNESS_LITTLE) { struct_type = '<'; } else { @@ -277,20 +314,25 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** mp_uint_t val; switch (val_type) { -#if MICROPY_NONSTANDARD_TYPECODES + #if MICROPY_NONSTANDARD_TYPECODES case 'O': val = (mp_uint_t)val_in; break; -#endif -#if MICROPY_PY_BUILTINS_FLOAT + #endif + #if MICROPY_PY_BUILTINS_FLOAT case 'f': { - union { uint32_t i; float f; } fp_sp; + union { uint32_t i; + float f; + } fp_sp; fp_sp.f = mp_obj_get_float(val_in); val = fp_sp.i; break; } case 'd': { - union { uint64_t i64; uint32_t i32[2]; double f; } fp_dp; + union { uint64_t i64; + uint32_t i32[2]; + double f; + } fp_dp; fp_dp.f = mp_obj_get_float(val_in); if (BYTES_PER_WORD == 8) { val = fp_dp.i64; @@ -302,7 +344,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** } break; } -#endif + #endif default: { bool signed_type = is_signed(val_type); #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE @@ -338,20 +380,20 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte ** void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t val_in) { switch (typecode) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'f': - ((float*)p)[index] = mp_obj_get_float(val_in); + ((float *)p)[index] = mp_obj_get_float(val_in); break; case 'd': - ((double*)p)[index] = mp_obj_get_float(val_in); + ((double *)p)[index] = mp_obj_get_float(val_in); break; -#endif -#if MICROPY_NONSTANDARD_TYPECODES + #endif + #if MICROPY_NONSTANDARD_TYPECODES // Extension to CPython: array of objects case 'O': - ((mp_obj_t*)p)[index] = val_in; + ((mp_obj_t *)p)[index] = val_in; break; -#endif + #endif default: { size_t size = mp_binary_get_size('@', typecode, NULL); bool signed_type = is_signed(typecode); @@ -361,7 +403,7 @@ void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t v // It's a long int. mp_obj_int_buffer_overflow_check(val_in, size, signed_type); mp_obj_int_to_bytes_impl(val_in, MP_ENDIANNESS_BIG, - size, (uint8_t*)p + index * size); + size, (uint8_t *)p + index * size); return; } #endif @@ -376,51 +418,51 @@ void mp_binary_set_val_array(char typecode, void *p, mp_uint_t index, mp_obj_t v void mp_binary_set_val_array_from_int(char typecode, void *p, mp_uint_t index, mp_int_t val) { switch (typecode) { case 'b': - ((signed char*)p)[index] = val; + ((signed char *)p)[index] = val; break; case BYTEARRAY_TYPECODE: case 'B': - ((unsigned char*)p)[index] = val; + ((unsigned char *)p)[index] = val; break; case 'h': - ((short*)p)[index] = val; + ((short *)p)[index] = val; break; case 'H': - ((unsigned short*)p)[index] = val; + ((unsigned short *)p)[index] = val; break; case 'i': - ((int*)p)[index] = val; + ((int *)p)[index] = val; break; case 'I': - ((unsigned int*)p)[index] = val; + ((unsigned int *)p)[index] = val; break; case 'l': - ((long*)p)[index] = val; + ((long *)p)[index] = val; break; case 'L': - ((unsigned long*)p)[index] = val; + ((unsigned long *)p)[index] = val; break; #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE case 'q': - ((long long*)p)[index] = val; + ((long long *)p)[index] = val; break; case 'Q': - ((unsigned long long*)p)[index] = val; + ((unsigned long long *)p)[index] = val; break; #endif -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'f': - ((float*)p)[index] = val; + ((float *)p)[index] = val; break; case 'd': - ((double*)p)[index] = val; + ((double *)p)[index] = val; break; -#endif -#if MICROPY_NONSTANDARD_TYPECODES + #endif + #if MICROPY_NONSTANDARD_TYPECODES // Extension to CPython: array of pointers case 'P': - ((void**)p)[index] = (void*)(uintptr_t)val; + ((void **)p)[index] = (void *)(uintptr_t)val; break; -#endif + #endif } } diff --git a/py/builtinevex.c b/py/builtinevex.c index cff57c4131..5538ac783c 100644 --- a/py/builtinevex.c +++ b/py/builtinevex.c @@ -92,9 +92,15 @@ STATIC mp_obj_t mp_builtin_compile(size_t n_args, const mp_obj_t *args) { qstr mode = mp_obj_str_get_qstr(args[2]); mp_parse_input_kind_t parse_input_kind; switch (mode) { - case MP_QSTR_single: parse_input_kind = MP_PARSE_SINGLE_INPUT; break; - case MP_QSTR_exec: parse_input_kind = MP_PARSE_FILE_INPUT; break; - case MP_QSTR_eval: parse_input_kind = MP_PARSE_EVAL_INPUT; break; + case MP_QSTR_single: + parse_input_kind = MP_PARSE_SINGLE_INPUT; + break; + case MP_QSTR_exec: + parse_input_kind = MP_PARSE_FILE_INPUT; + break; + case MP_QSTR_eval: + parse_input_kind = MP_PARSE_EVAL_INPUT; + break; default: mp_raise_ValueError(translate("bad compile mode")); } diff --git a/py/builtinhelp.c b/py/builtinhelp.c index e1dcb60962..2e77e6dd93 100644 --- a/py/builtinhelp.c +++ b/py/builtinhelp.c @@ -35,18 +35,18 @@ #if MICROPY_PY_BUILTINS_HELP const char mp_help_default_text[] = -"Welcome to MicroPython!\n" -"\n" -"For online docs please visit http://docs.micropython.org/\n" -"\n" -"Control commands:\n" -" CTRL-A -- on a blank line, enter raw REPL mode\n" -" CTRL-B -- on a blank line, enter normal REPL mode\n" -" CTRL-C -- interrupt a running program\n" -" CTRL-D -- on a blank line, exit or do a soft reset\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 MicroPython!\n" + "\n" + "For online docs please visit http://docs.micropython.org/\n" + "\n" + "Control commands:\n" + " CTRL-A -- on a blank line, enter raw REPL mode\n" + " CTRL-B -- on a blank line, enter normal REPL mode\n" + " CTRL-C -- interrupt a running program\n" + " CTRL-D -- on a blank line, exit or do a soft reset\n" + " CTRL-E -- on a blank line, enter paste mode\n" + "\n" + "For further help on a specific object, type help(obj)\n" ; STATIC void mp_help_print_info_about_object(mp_obj_t name_o, mp_obj_t value) { @@ -105,7 +105,7 @@ STATIC void mp_help_print_modules(void) { #endif // sort the list so it's printed in alphabetical order - mp_obj_list_sort(1, &list, (mp_map_t*)&mp_const_empty_map); + mp_obj_list_sort(1, &list, (mp_map_t *)&mp_const_empty_map); // print the list of modules in a column-first order #define NUM_COLUMNS (4) @@ -134,7 +134,7 @@ STATIC void mp_help_print_modules(void) { } // let the user know there may be other modules available from the filesystem - const compressed_string_t* compressed = translate("Plus any modules on the filesystem\n"); + const compressed_string_t *compressed = translate("Plus any modules on the filesystem\n"); char decompressed[decompress_length(compressed)]; decompress(compressed, decompressed); mp_print_str(MP_PYTHON_PRINTER, decompressed); @@ -152,7 +152,7 @@ STATIC void mp_help_print_obj(const mp_obj_t obj) { mp_obj_type_t *type = mp_obj_get_type(obj); // try to print something sensible about the given object - const compressed_string_t* compressed = translate("object "); + const compressed_string_t *compressed = translate("object "); char decompressed_object[decompress_length(compressed)]; decompress(compressed, decompressed_object); @@ -188,7 +188,7 @@ STATIC void mp_help_print_obj(const mp_obj_t obj) { STATIC mp_obj_t mp_builtin_help(size_t n_args, const mp_obj_t *args) { if (n_args == 0) { // print a general help message. Translate only works on single strings on one line. - const compressed_string_t* compressed = + const compressed_string_t *compressed = translate("Welcome to Adafruit CircuitPython %s!\n\nPlease visit learn.adafruit.com/category/circuitpython for project guides.\n\nTo list built-in modules please do `help(\"modules\")`.\n"); char decompressed[decompress_length(compressed)]; decompress(compressed, decompressed); diff --git a/py/builtinimport.c b/py/builtinimport.c index c4768cc777..8462c146b1 100644 --- a/py/builtinimport.c +++ b/py/builtinimport.c @@ -63,8 +63,8 @@ bool mp_obj_is_package(mp_obj_t module) { STATIC mp_import_stat_t mp_import_stat_any(const char *path) { #if MICROPY_MODULE_FROZEN if (strncmp(MP_FROZEN_FAKE_DIR_SLASH, - path, - MP_FROZEN_FAKE_DIR_SLASH_LENGTH) == 0) { + path, + MP_FROZEN_FAKE_DIR_SLASH_LENGTH) == 0) { mp_import_stat_t st = mp_frozen_stat(path + MP_FROZEN_FAKE_DIR_SLASH_LENGTH); if (st != MP_IMPORT_STAT_NO_EXIST) { return st; @@ -104,40 +104,40 @@ STATIC mp_import_stat_t stat_dir_or_file(vstr_t *path) { } STATIC mp_import_stat_t find_file(const char *file_str, uint file_len, vstr_t *dest) { -#if MICROPY_PY_SYS + #if MICROPY_PY_SYS // extract the list of paths size_t path_num; mp_obj_t *path_items; mp_obj_list_get(mp_sys_path, &path_num, &path_items); if (path_num == 0) { -#endif - // mp_sys_path is empty, so just use the given file name - vstr_add_strn(dest, file_str, file_len); - return stat_dir_or_file(dest); -#if MICROPY_PY_SYS - } else { - // go through each path looking for a directory or file - for (size_t i = 0; i < path_num; i++) { - vstr_reset(dest); - size_t p_len; - const char *p = mp_obj_str_get_data(path_items[i], &p_len); - DEBUG_printf("Looking in path: %d =%s=\n", i, p); - if (p_len > 0) { - vstr_add_strn(dest, p, p_len); - vstr_add_char(dest, PATH_SEP_CHAR); - } - vstr_add_strn(dest, file_str, file_len); - mp_import_stat_t stat = stat_dir_or_file(dest); - if (stat != MP_IMPORT_STAT_NO_EXIST) { - return stat; - } + #endif + // mp_sys_path is empty, so just use the given file name + vstr_add_strn(dest, file_str, file_len); + return stat_dir_or_file(dest); + #if MICROPY_PY_SYS +} else { + // go through each path looking for a directory or file + for (size_t i = 0; i < path_num; i++) { + vstr_reset(dest); + size_t p_len; + const char *p = mp_obj_str_get_data(path_items[i], &p_len); + DEBUG_printf("Looking in path: %d =%s=\n", i, p); + if (p_len > 0) { + vstr_add_strn(dest, p, p_len); + vstr_add_char(dest, PATH_SEP_CHAR); + } + vstr_add_strn(dest, file_str, file_len); + mp_import_stat_t stat = stat_dir_or_file(dest); + if (stat != MP_IMPORT_STAT_NO_EXIST) { + return stat; } - - // could not find a directory or file - return MP_IMPORT_STAT_NO_EXIST; } -#endif + + // could not find a directory or file + return MP_IMPORT_STAT_NO_EXIST; +} + #endif } #if MICROPY_ENABLE_COMPILER @@ -198,8 +198,8 @@ STATIC void do_load(mp_obj_t module_obj, vstr_t *file) { #if MICROPY_MODULE_FROZEN || MICROPY_MODULE_FROZEN_MPY if (strncmp(MP_FROZEN_FAKE_DIR_SLASH, - file_str, - MP_FROZEN_FAKE_DIR_SLASH_LENGTH) == 0) { + file_str, + MP_FROZEN_FAKE_DIR_SLASH_LENGTH) == 0) { // If we support frozen modules (either as str or mpy) then try to find the // requested filename in the list of frozen module filenames. #if MICROPY_MODULE_FROZEN @@ -264,14 +264,14 @@ STATIC void chop_component(const char *start, const char **end) { } mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { -#if DEBUG_PRINT + #if DEBUG_PRINT DEBUG_printf("__import__:\n"); for (size_t i = 0; i < n_args; i++) { DEBUG_printf(" "); mp_obj_print(args[i], PRINT_REPR); DEBUG_printf("\n"); } -#endif + #endif mp_obj_t module_name = args[0]; mp_obj_t fromtuple = mp_const_none; @@ -310,12 +310,12 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { mp_map_elem_t *elem = mp_map_lookup(globals_map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP); bool is_pkg = (elem != NULL); -#if DEBUG_PRINT + #if DEBUG_PRINT DEBUG_printf("Current module/package: "); mp_obj_print(this_name_q, PRINT_REPR); DEBUG_printf(", is_package: %d", is_pkg); DEBUG_printf("\n"); -#endif + #endif size_t this_name_l; const char *this_name = mp_obj_str_get_data(this_name_q, &this_name_l); @@ -404,21 +404,21 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { qstr current_module_name = qstr_from_strn(mod_str + last, i - last); mp_map_elem_t *el = NULL; if (outer_module_obj == MP_OBJ_NULL) { - el = mp_map_lookup((mp_map_t*)&mp_builtin_module_map, - MP_OBJ_NEW_QSTR(current_module_name), - MP_MAP_LOOKUP); + el = mp_map_lookup((mp_map_t *)&mp_builtin_module_map, + MP_OBJ_NEW_QSTR(current_module_name), + MP_MAP_LOOKUP); #if MICROPY_MODULE_WEAK_LINKS // check if there is a weak link to this module if (el == NULL) { - el = mp_map_lookup((mp_map_t*)&mp_builtin_module_weak_links_map, - MP_OBJ_NEW_QSTR(current_module_name), - MP_MAP_LOOKUP); + el = mp_map_lookup((mp_map_t *)&mp_builtin_module_weak_links_map, + MP_OBJ_NEW_QSTR(current_module_name), + MP_MAP_LOOKUP); } #endif } else { - el = mp_map_lookup(&((mp_obj_module_t*) outer_module_obj)->globals->map, - MP_OBJ_NEW_QSTR(current_module_name), - MP_MAP_LOOKUP); + el = mp_map_lookup(&((mp_obj_module_t *)outer_module_obj)->globals->map, + MP_OBJ_NEW_QSTR(current_module_name), + MP_MAP_LOOKUP); } if (el != NULL && MP_OBJ_IS_TYPE(el->value, &mp_type_module)) { @@ -427,10 +427,10 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { } else { // couldn't find the file, so fail #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_ImportError(translate("module not found")); + mp_raise_ImportError(translate("module not found")); #else - mp_raise_msg_varg(&mp_type_ImportError, - translate("no module named '%q'"), mod_name); + mp_raise_msg_varg(&mp_type_ImportError, + translate("no module named '%q'"), mod_name); #endif } } else { @@ -471,7 +471,7 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { vstr_add_char(&path, PATH_SEP_CHAR); vstr_add_str(&path, "__init__.py"); if (stat_file_py_or_mpy(&path) != MP_IMPORT_STAT_FILE) { - //mp_warning("%s is imported as namespace package", vstr_str(&path)); + // mp_warning("%s is imported as namespace package", vstr_str(&path)); } else { do_load(module_obj, &path); } @@ -488,7 +488,7 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { // afterwards. gc_collect(); } - if (outer_module_obj != MP_OBJ_NULL && VERIFY_PTR(outer_module_obj) ) { + if (outer_module_obj != MP_OBJ_NULL && VERIFY_PTR(outer_module_obj)) { qstr s = qstr_from_strn(mod_str + last, i - last); mp_store_attr(outer_module_obj, s, module_obj); // The above store can cause a dictionary rehash and new allocation. So, @@ -529,7 +529,7 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { #if MICROPY_MODULE_WEAK_LINKS // Check if there is a weak link to this module - mp_map_elem_t *el = mp_map_lookup((mp_map_t*)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(module_name_qstr), MP_MAP_LOOKUP); + mp_map_elem_t *el = mp_map_lookup((mp_map_t *)&mp_builtin_module_weak_links_map, MP_OBJ_NEW_QSTR(module_name_qstr), MP_MAP_LOOKUP); if (el != NULL) { // Found weak-linked module mp_module_call_init(module_name_qstr, el->value); @@ -539,10 +539,10 @@ mp_obj_t mp_builtin___import__(size_t n_args, const mp_obj_t *args) { // Couldn't find the module, so fail #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_msg(&mp_type_ImportError, translate("module not found")); + mp_raise_msg(&mp_type_ImportError, translate("module not found")); #else - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, - translate("no module named '%q'"), module_name_qstr)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_ImportError, + translate("no module named '%q'"), module_name_qstr)); #endif } diff --git a/py/circuitpy_mpconfig.h b/py/circuitpy_mpconfig.h index f61c3959f0..eedda7ad73 100644 --- a/py/circuitpy_mpconfig.h +++ b/py/circuitpy_mpconfig.h @@ -148,7 +148,7 @@ #define BYTES_PER_WORD (4) -#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void*)((mp_uint_t)(p) | 1)) +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) // Track stack usage. Expose results via ustack module. #define MICROPY_MAX_STACK_USAGE (0) @@ -420,7 +420,7 @@ extern const struct _mp_obj_module_t terminalio_module; #else #define ERRNO_MODULE # -#endif + #endif #if CIRCUITPY_ESPIDF extern const struct _mp_obj_module_t espidf_module; @@ -523,7 +523,7 @@ extern const struct _mp_obj_module_t _eve_module; extern const struct _mp_obj_module_t memorymonitor_module; #define MEMORYMONITOR_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_memorymonitor), (mp_obj_t)&memorymonitor_module }, #define MEMORYMONITOR_ROOT_POINTERS mp_obj_t active_allocationsizes; \ - mp_obj_t active_allocationalarms; + mp_obj_t active_allocationalarms; #else #define MEMORYMONITOR_MODULE #define MEMORYMONITOR_ROOT_POINTERS @@ -550,7 +550,7 @@ extern const struct _mp_obj_module_t socket_module; #define SOCKET_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_socket), (mp_obj_t)&socket_module }, #define NETWORK_ROOT_POINTERS mp_obj_list_t mod_network_nic_list; #if MICROPY_PY_WIZNET5K - extern const struct _mp_obj_module_t wiznet_module; +extern const struct _mp_obj_module_t wiznet_module; #define WIZNET_MODULE { MP_OBJ_NEW_QSTR(MP_QSTR_wiznet), (mp_obj_t)&wiznet_module }, #endif #else @@ -853,9 +853,9 @@ extern const struct _mp_obj_module_t msgpack_module; COUNTIO_MODULE \ DIGITALIO_MODULE \ DISPLAYIO_MODULE \ - FONTIO_MODULE \ - TERMINALIO_MODULE \ - VECTORIO_MODULE \ + FONTIO_MODULE \ + TERMINALIO_MODULE \ + VECTORIO_MODULE \ ERRNO_MODULE \ ESPIDF_MODULE \ FRAMEBUFFERIO_MODULE \ @@ -873,8 +873,8 @@ extern const struct _mp_obj_module_t msgpack_module; MSGPACK_MODULE \ NEOPIXEL_WRITE_MODULE \ NETWORK_MODULE \ - SOCKET_MODULE \ - WIZNET_MODULE \ + SOCKET_MODULE \ + WIZNET_MODULE \ DUALBANK_MODULE \ PEW_MODULE \ PIXELBUF_MODULE \ @@ -938,8 +938,8 @@ struct _supervisor_allocation_node; BOARD_UART_ROOT_POINTER \ FLASH_ROOT_POINTERS \ MEMORYMONITOR_ROOT_POINTERS \ - NETWORK_ROOT_POINTERS \ - struct _supervisor_allocation_node* first_embedded_allocation; \ + NETWORK_ROOT_POINTERS \ + struct _supervisor_allocation_node *first_embedded_allocation; \ void supervisor_run_background_tasks_if_tick(void); #define RUN_BACKGROUND_TASKS (supervisor_run_background_tasks_if_tick()) diff --git a/py/compile.c b/py/compile.c index b4d81ed445..4a9fdc7db8 100644 --- a/py/compile.c +++ b/py/compile.c @@ -48,14 +48,14 @@ typedef enum { // define rules with a compile function #define DEF_RULE(rule, comp, kind, ...) PN_##rule, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC PN_const_object, // special node for a constant, generic Python object // define rules without a compile function #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) PN_##rule, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC } pn_kind_t; @@ -152,7 +152,7 @@ typedef struct _compiler_t { STATIC void compile_error_set_line(compiler_t *comp, mp_parse_node_t pn) { // if the line of the error is unknown then try to update it from the pn if (comp->compile_error_line == 0 && MP_PARSE_NODE_IS_STRUCT(pn)) { - comp->compile_error_line = ((mp_parse_node_struct_t*)pn)->source_line; + comp->compile_error_line = ((mp_parse_node_struct_t *)pn)->source_line; } } @@ -204,7 +204,7 @@ typedef void (*apply_list_fun_t)(compiler_t *comp, mp_parse_node_t pn); STATIC void apply_to_single_or_list(compiler_t *comp, mp_parse_node_t pn, pn_kind_t pn_list_kind, apply_list_fun_t f) { if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, pn_list_kind)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); for (int i = 0; i < num_nodes; i++) { f(comp, pns->nodes[i]); @@ -295,7 +295,7 @@ STATIC void c_if_cond(compiler_t *comp, mp_parse_node_t pn, bool jump_if, int la } return; } else if (MP_PARSE_NODE_IS_STRUCT(pn)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_or_test) { if (jump_if == false) { @@ -354,7 +354,7 @@ STATIC void c_assign_atom_expr(compiler_t *comp, mp_parse_node_struct_t *pns, as } if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_atom_expr_trailers) { int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1); if (assign_kind != ASSIGN_AUG_STORE) { @@ -363,7 +363,7 @@ STATIC void c_assign_atom_expr(compiler_t *comp, mp_parse_node_struct_t *pns, as } } assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1])); - pns1 = (mp_parse_node_struct_t*)pns1->nodes[n - 1]; + pns1 = (mp_parse_node_struct_t *)pns1->nodes[n - 1]; } if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) { if (assign_kind == ASSIGN_AUG_STORE) { @@ -423,14 +423,14 @@ STATIC void c_assign_tuple(compiler_t *comp, mp_parse_node_t node_head, uint num } if (num_head != 0) { if (0 == have_star_index) { - c_assign(comp, ((mp_parse_node_struct_t*)node_head)->nodes[0], ASSIGN_STORE); + c_assign(comp, ((mp_parse_node_struct_t *)node_head)->nodes[0], ASSIGN_STORE); } else { c_assign(comp, node_head, ASSIGN_STORE); } } for (uint i = 0; i < num_tail; i++) { if (num_head + i == have_star_index) { - c_assign(comp, ((mp_parse_node_struct_t*)nodes_tail[i])->nodes[0], ASSIGN_STORE); + c_assign(comp, ((mp_parse_node_struct_t *)nodes_tail[i])->nodes[0], ASSIGN_STORE); } else { c_assign(comp, nodes_tail[i], ASSIGN_STORE); } @@ -458,7 +458,7 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ } } else { // pn must be a struct - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; switch (MP_PARSE_NODE_STRUCT_KIND(pns)) { case PN_atom_expr_normal: // lhs is an index or attribute @@ -484,7 +484,7 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ if (assign_kind != ASSIGN_STORE) { goto cannot_assign; } - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; goto testlist_comp; } break; @@ -498,7 +498,7 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ // empty list, assignment allowed c_assign_tuple(comp, MP_PARSE_NODE_NULL, 0, NULL); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) { - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; goto testlist_comp; } else { // brackets around 1 item @@ -511,10 +511,10 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ } return; - testlist_comp: + testlist_comp: // lhs is a sequence if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) { // sequence of one item, with trailing comma assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0])); @@ -531,14 +531,14 @@ STATIC void c_assign(compiler_t *comp, mp_parse_node_t pn, assign_kind_t assign_ } } else { // sequence with 2 items - sequence_with_2_items: + sequence_with_2_items: c_assign_tuple(comp, MP_PARSE_NODE_NULL, 2, pns->nodes); } return; } return; - cannot_assign: +cannot_assign: compile_syntax_error(comp, pn, translate("can't assign to expression")); } @@ -590,7 +590,7 @@ STATIC void compile_funcdef_lambdef_param(compiler_t *comp, mp_parse_node_t pn) pn_kind = -1; } else { assert(MP_PARSE_NODE_IS_STRUCT(pn)); - pn_kind = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn); + pn_kind = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn); } if (pn_kind == PN_typedargslist_star || pn_kind == PN_varargslist_star) { @@ -620,16 +620,16 @@ STATIC void compile_funcdef_lambdef_param(compiler_t *comp, mp_parse_node_t pn) } else if (pn_kind == PN_typedargslist_name) { // this parameter has a colon and/or equal specifier - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; pn_id = pns->nodes[0]; - //pn_colon = pns->nodes[1]; // unused + // pn_colon = pns->nodes[1]; // unused pn_equal = pns->nodes[2]; } else { assert(pn_kind == PN_varargslist_name); // should be // this parameter has an equal specifier - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; pn_id = pns->nodes[0]; pn_equal = pns->nodes[1]; } @@ -719,7 +719,7 @@ STATIC qstr compile_funcdef_helper(compiler_t *comp, mp_parse_node_struct_t *pns } // get the scope for this function - scope_t *fscope = (scope_t*)pns->nodes[4]; + scope_t *fscope = (scope_t *)pns->nodes[4]; // compile the function definition compile_funcdef_lambdef(comp, fscope, pns->nodes[1], PN_typedargslist); @@ -741,7 +741,7 @@ STATIC qstr compile_classdef_helper(compiler_t *comp, mp_parse_node_struct_t *pn EMIT(load_build_class); // scope for this class - scope_t *cscope = (scope_t*)pns->nodes[3]; + scope_t *cscope = (scope_t *)pns->nodes[3]; // compile the class close_over_variables_etc(comp, cscope, 0, 0); @@ -775,7 +775,7 @@ STATIC bool compile_built_in_decorator(compiler_t *comp, int name_len, mp_parse_ qstr attr = MP_PARSE_NODE_LEAF_ARG(name_nodes[1]); if (attr == MP_QSTR_bytecode) { *emit_options = MP_EMIT_OPT_BYTECODE; - // @micropython.native decorator. + // @micropython.native decorator. } else if (attr == MP_QSTR_native) { // Different from MicroPython: native doesn't raise SyntaxError if native support isn't // compiled, it just passes through the function unmodified. @@ -784,16 +784,16 @@ STATIC bool compile_built_in_decorator(compiler_t *comp, int name_len, mp_parse_ #else return true; #endif - #if MICROPY_EMIT_NATIVE - // @micropython.viper decorator. + #if MICROPY_EMIT_NATIVE + // @micropython.viper decorator. } else if (attr == MP_QSTR_viper) { *emit_options = MP_EMIT_OPT_VIPER; - #endif - #if MICROPY_EMIT_INLINE_ASM - // @micropython.asm_thumb decorator. + #endif + #if MICROPY_EMIT_INLINE_ASM + // @micropython.asm_thumb decorator. } else if (attr == ASM_DECORATOR_QSTR) { *emit_options = MP_EMIT_OPT_ASM; - #endif + #endif } else { compile_syntax_error(comp, name_nodes[1], translate("invalid micropython decorator")); } @@ -813,7 +813,7 @@ STATIC void compile_decorated(compiler_t *comp, mp_parse_node_struct_t *pns) { int num_built_in_decorators = 0; for (int i = 0; i < n; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(nodes[i], PN_decorator)); // should be - mp_parse_node_struct_t *pns_decorator = (mp_parse_node_struct_t*)nodes[i]; + mp_parse_node_struct_t *pns_decorator = (mp_parse_node_struct_t *)nodes[i]; // nodes[0] contains the decorator function, which is a dotted name mp_parse_node_t *name_nodes; @@ -843,16 +843,16 @@ STATIC void compile_decorated(compiler_t *comp, mp_parse_node_struct_t *pns) { } // compile the body (funcdef, async funcdef or classdef) and get its name - mp_parse_node_struct_t *pns_body = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_body = (mp_parse_node_struct_t *)pns->nodes[1]; qstr body_name = 0; if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_funcdef) { body_name = compile_funcdef_helper(comp, pns_body, emit_options); #if MICROPY_PY_ASYNC_AWAIT } else if (MP_PARSE_NODE_STRUCT_KIND(pns_body) == PN_async_funcdef) { assert(MP_PARSE_NODE_IS_STRUCT(pns_body->nodes[0])); - mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns_body->nodes[0]; + mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns_body->nodes[0]; body_name = compile_funcdef_helper(comp, pns0, emit_options); - scope_t *fscope = (scope_t*)pns0->nodes[4]; + scope_t *fscope = (scope_t *)pns0->nodes[4]; fscope->scope_flags |= MP_SCOPE_FLAG_GENERATOR | MP_SCOPE_FLAG_ASYNC; #endif } else { @@ -879,19 +879,19 @@ STATIC void c_del_stmt(compiler_t *comp, mp_parse_node_t pn) { if (MP_PARSE_NODE_IS_ID(pn)) { compile_delete_id(comp, MP_PARSE_NODE_LEAF_ARG(pn)); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_expr_normal)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; compile_node(comp, pns->nodes[0]); // base of the atom_expr_normal node if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_atom_expr_trailers) { int n = MP_PARSE_NODE_STRUCT_NUM_NODES(pns1); for (int i = 0; i < n - 1; i++) { compile_node(comp, pns1->nodes[i]); } assert(MP_PARSE_NODE_IS_STRUCT(pns1->nodes[n - 1])); - pns1 = (mp_parse_node_struct_t*)pns1->nodes[n - 1]; + pns1 = (mp_parse_node_struct_t *)pns1->nodes[n - 1]; } if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_trailer_bracket) { compile_node(comp, pns1->nodes[0]); @@ -907,16 +907,16 @@ STATIC void c_del_stmt(compiler_t *comp, mp_parse_node_t pn) { } } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_paren)) { - pn = ((mp_parse_node_struct_t*)pn)->nodes[0]; + pn = ((mp_parse_node_struct_t *)pn)->nodes[0]; if (MP_PARSE_NODE_IS_NULL(pn)) { goto cannot_delete; } else { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_testlist_comp)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; // TODO perhaps factorise testlist_comp code with other uses of PN_testlist_comp if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_testlist_comp_3b) { // sequence of one item, with trailing comma assert(MP_PARSE_NODE_IS_NULL(pns1->nodes[0])); @@ -936,7 +936,7 @@ STATIC void c_del_stmt(compiler_t *comp, mp_parse_node_t pn) { } } else { // sequence with 2 items - sequence_with_2_items: + sequence_with_2_items: c_del_stmt(comp, pns->nodes[0]); c_del_stmt(comp, pns->nodes[1]); } @@ -982,10 +982,10 @@ STATIC void compile_return_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { // no argument to 'return', so return None EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); } else if (MICROPY_COMP_RETURN_IF_EXPR - && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) { + && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_test_if_expr)) { // special case when returning an if-expression; to match CPython optimisation - mp_parse_node_struct_t *pns_test_if_expr = (mp_parse_node_struct_t*)pns->nodes[0]; - mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t*)pns_test_if_expr->nodes[1]; + mp_parse_node_struct_t *pns_test_if_expr = (mp_parse_node_struct_t *)pns->nodes[0]; + mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t *)pns_test_if_expr->nodes[1]; uint l_fail = comp_next_label(comp); c_if_cond(comp, pns_test_if_else->nodes[0], false, l_fail); // condition @@ -1010,7 +1010,7 @@ STATIC void compile_raise_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { EMIT_ARG(raise_varargs, 0); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_raise_stmt_arg)) { // raise x from y - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; compile_node(comp, pns->nodes[0]); compile_node(comp, pns->nodes[1]); EMIT_ARG(raise_varargs, 2); @@ -1027,7 +1027,7 @@ STATIC void compile_raise_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { STATIC void do_import_name(compiler_t *comp, mp_parse_node_t pn, qstr *q_base) { bool is_as = false; if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_dotted_as_name)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; // a name of the form x as y; unwrap it *q_base = MP_PARSE_NODE_LEAF_ARG(pns->nodes[1]); pn = pns->nodes[0]; @@ -1046,7 +1046,7 @@ STATIC void do_import_name(compiler_t *comp, mp_parse_node_t pn, qstr *q_base) { EMIT_ARG(import, q_full, MP_EMIT_IMPORT_NAME); } else { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_dotted_name)); // should be - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; { // a name of the form a.b.c if (!is_as) { @@ -1105,7 +1105,7 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { pn_import_source = MP_PARSE_NODE_NULL; } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn_import_source, PN_import_from_2b)) { // This covers relative imports starting with dot(s) like "from .foo import" - mp_parse_node_struct_t *pns_2b = (mp_parse_node_struct_t*)pn_import_source; + mp_parse_node_struct_t *pns_2b = (mp_parse_node_struct_t *)pn_import_source; pn_rel = pns_2b->nodes[0]; pn_import_source = pns_2b->nodes[1]; assert(!MP_PARSE_NODE_IS_NULL(pn_import_source)); // should not be @@ -1149,7 +1149,7 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { int n = mp_parse_node_extract_list(&pns->nodes[1], PN_import_as_names, &pn_nodes); for (int i = 0; i < n; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_nodes[i], PN_import_as_name)); - mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pn_nodes[i]; + mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pn_nodes[i]; qstr id2 = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[0]); // should be id EMIT_ARG(load_const_str, id2); } @@ -1160,7 +1160,7 @@ STATIC void compile_import_from(compiler_t *comp, mp_parse_node_struct_t *pns) { do_import_name(comp, pn_import_source, &dummy_q); for (int i = 0; i < n; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_nodes[i], PN_import_as_name)); - mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pn_nodes[i]; + mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pn_nodes[i]; qstr id2 = MP_PARSE_NODE_LEAF_ARG(pns3->nodes[0]); // should be id EMIT_ARG(import, id2, MP_EMIT_IMPORT_FROM); if (MP_PARSE_NODE_IS_NULL(pns3->nodes[1])) { @@ -1273,7 +1273,7 @@ STATIC void compile_if_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { int n_elif = mp_parse_node_extract_list(&pns->nodes[2], PN_if_stmt_elif_list, &pn_elif); for (int i = 0; i < n_elif; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_elif[i], PN_if_stmt_elif)); // should be - mp_parse_node_struct_t *pns_elif = (mp_parse_node_struct_t*)pn_elif[i]; + mp_parse_node_struct_t *pns_elif = (mp_parse_node_struct_t *)pn_elif[i]; // optimisation: don't emit anything when "if False" if (!mp_parse_node_is_const_false(pns_elif->nodes[0])) { @@ -1442,11 +1442,11 @@ STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { // this is actually slower, but uses no heap memory // for viper it will be much, much faster if (/*comp->scope_cur->emit_options == MP_EMIT_OPT_VIPER &&*/ MP_PARSE_NODE_IS_ID(pns->nodes[0]) && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_atom_expr_normal)) { - mp_parse_node_struct_t *pns_it = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_it = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_IS_ID(pns_it->nodes[0]) && MP_PARSE_NODE_LEAF_ARG(pns_it->nodes[0]) == MP_QSTR_range - && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pns_it->nodes[1]) == PN_trailer_paren) { - mp_parse_node_t pn_range_args = ((mp_parse_node_struct_t*)pns_it->nodes[1])->nodes[0]; + && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pns_it->nodes[1]) == PN_trailer_paren) { + mp_parse_node_t pn_range_args = ((mp_parse_node_struct_t *)pns_it->nodes[1])->nodes[0]; mp_parse_node_t *args; int n_args = mp_parse_node_extract_list(&pn_range_args, PN_arglist, &args); mp_parse_node_t pn_range_start; @@ -1475,13 +1475,13 @@ STATIC void compile_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { } // arguments must be able to be compiled as standard expressions if (optimize && MP_PARSE_NODE_IS_STRUCT(pn_range_start)) { - int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_range_start); + int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_range_start); if (k == PN_arglist_star || k == PN_arglist_dbl_star || k == PN_argument) { optimize = false; } } if (optimize && MP_PARSE_NODE_IS_STRUCT(pn_range_end)) { - int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_range_end); + int k = MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_range_end); if (k == PN_arglist_star || k == PN_arglist_dbl_star || k == PN_argument) { optimize = false; } @@ -1540,7 +1540,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ for (int i = 0; i < n_except; i++) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pn_excepts[i], PN_try_stmt_except)); // should be - mp_parse_node_struct_t *pns_except = (mp_parse_node_struct_t*)pn_excepts[i]; + mp_parse_node_struct_t *pns_except = (mp_parse_node_struct_t *)pn_excepts[i]; qstr qstr_exception_local = 0; uint end_finally_label = comp_next_label(comp); @@ -1556,7 +1556,7 @@ STATIC void compile_try_except(compiler_t *comp, mp_parse_node_t pn_body, int n_ // this exception handler requires a match to a certain type of exception mp_parse_node_t pns_exception_expr = pns_except->nodes[0]; if (MP_PARSE_NODE_IS_STRUCT(pns_exception_expr)) { - mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pns_exception_expr; + mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pns_exception_expr; if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_try_stmt_as_name) { // handler binds the exception to a local pns_exception_expr = pns3->nodes[0]; @@ -1637,7 +1637,7 @@ STATIC void compile_try_finally(compiler_t *comp, mp_parse_node_t pn_body, int n STATIC void compile_try_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should be { - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_try_stmt_finally) { // just try-finally compile_try_finally(comp, pns->nodes[0], 0, NULL, MP_PARSE_NODE_NULL, pns2->nodes[0]); @@ -1650,7 +1650,7 @@ STATIC void compile_try_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { compile_try_except(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1]); } else { // have finally - compile_try_finally(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1], ((mp_parse_node_struct_t*)pns2->nodes[2])->nodes[0]); + compile_try_finally(comp, pns->nodes[0], n_except, pn_excepts, pns2->nodes[1], ((mp_parse_node_struct_t *)pns2->nodes[2])->nodes[0]); } } else { // just try-except @@ -1674,7 +1674,7 @@ STATIC void compile_with_stmt_helper(compiler_t *comp, int n, mp_parse_node_t *n } if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) { // this pre-bit is of the form "a as b" - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)nodes[0]; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0]; compile_node(comp, pns->nodes[0]); EMIT_ARG(setup_block, l_end, MP_EMIT_SETUP_BLOCK_WITH); c_assign(comp, pns->nodes[1], ASSIGN_STORE); @@ -1713,7 +1713,7 @@ STATIC void compile_yield_from(compiler_t *comp) { #if MICROPY_PY_ASYNC_AWAIT STATIC bool compile_require_async_context(compiler_t *comp, mp_parse_node_struct_t *pns) { int scope_flags = comp->scope_cur->scope_flags; - if(scope_flags & MP_SCOPE_FLAG_ASYNC) { + if (scope_flags & MP_SCOPE_FLAG_ASYNC) { return true; } compile_syntax_error(comp, (mp_parse_node_t)pns, @@ -1730,7 +1730,7 @@ STATIC void compile_await_object_method(compiler_t *comp, qstr method) { STATIC void compile_async_for_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { // comp->break_label |= MP_EMIT_BREAK_FROM_FOR; - if(!compile_require_async_context(comp, pns)) { + if (!compile_require_async_context(comp, pns)) { return; } @@ -1800,7 +1800,7 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes[0], PN_with_item)) { // this pre-bit is of the form "a as b" - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)nodes[0]; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)nodes[0]; compile_node(comp, pns->nodes[0]); context = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); compile_store_id(comp, context); @@ -1872,7 +1872,7 @@ STATIC void compile_async_with_stmt_helper(compiler_t *comp, int n, mp_parse_nod } STATIC void compile_async_with_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { - if(!compile_require_async_context(comp, pns)) { + if (!compile_require_async_context(comp, pns)) { return; } // get the nodes for the pre-bit of the with (the a as b, c as d, ... bit) @@ -1886,11 +1886,11 @@ STATIC void compile_async_with_stmt(compiler_t *comp, mp_parse_node_struct_t *pn STATIC void compile_async_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[0])); - mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns->nodes[0]; + mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns->nodes[0]; if (MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_funcdef) { // async def compile_funcdef(comp, pns0); - scope_t *fscope = (scope_t*)pns0->nodes[4]; + scope_t *fscope = (scope_t *)pns0->nodes[4]; fscope->scope_flags |= MP_SCOPE_FLAG_GENERATOR | MP_SCOPE_FLAG_ASYNC; } else if (MP_PARSE_NODE_STRUCT_KIND(pns0) == PN_for_stmt) { // async for @@ -1923,7 +1923,7 @@ STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { } } } else if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; int kind = MP_PARSE_NODE_STRUCT_KIND(pns1); if (kind == PN_expr_stmt_augassign) { c_assign(comp, pns->nodes[0], ASSIGN_AUG_LOAD); // lhs load for aug assign @@ -1931,18 +1931,43 @@ STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { assert(MP_PARSE_NODE_IS_TOKEN(pns1->nodes[0])); mp_binary_op_t op; switch (MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0])) { - case MP_TOKEN_DEL_PIPE_EQUAL: op = MP_BINARY_OP_INPLACE_OR; break; - case MP_TOKEN_DEL_CARET_EQUAL: op = MP_BINARY_OP_INPLACE_XOR; break; - case MP_TOKEN_DEL_AMPERSAND_EQUAL: op = MP_BINARY_OP_INPLACE_AND; break; - case MP_TOKEN_DEL_DBL_LESS_EQUAL: op = MP_BINARY_OP_INPLACE_LSHIFT; break; - case MP_TOKEN_DEL_DBL_MORE_EQUAL: op = MP_BINARY_OP_INPLACE_RSHIFT; break; - case MP_TOKEN_DEL_PLUS_EQUAL: op = MP_BINARY_OP_INPLACE_ADD; break; - case MP_TOKEN_DEL_MINUS_EQUAL: op = MP_BINARY_OP_INPLACE_SUBTRACT; break; - case MP_TOKEN_DEL_STAR_EQUAL: op = MP_BINARY_OP_INPLACE_MULTIPLY; break; - case MP_TOKEN_DEL_DBL_SLASH_EQUAL: op = MP_BINARY_OP_INPLACE_FLOOR_DIVIDE; break; - case MP_TOKEN_DEL_SLASH_EQUAL: op = MP_BINARY_OP_INPLACE_TRUE_DIVIDE; break; - case MP_TOKEN_DEL_PERCENT_EQUAL: op = MP_BINARY_OP_INPLACE_MODULO; break; - case MP_TOKEN_DEL_DBL_STAR_EQUAL: default: op = MP_BINARY_OP_INPLACE_POWER; break; + case MP_TOKEN_DEL_PIPE_EQUAL: + op = MP_BINARY_OP_INPLACE_OR; + break; + case MP_TOKEN_DEL_CARET_EQUAL: + op = MP_BINARY_OP_INPLACE_XOR; + break; + case MP_TOKEN_DEL_AMPERSAND_EQUAL: + op = MP_BINARY_OP_INPLACE_AND; + break; + case MP_TOKEN_DEL_DBL_LESS_EQUAL: + op = MP_BINARY_OP_INPLACE_LSHIFT; + break; + case MP_TOKEN_DEL_DBL_MORE_EQUAL: + op = MP_BINARY_OP_INPLACE_RSHIFT; + break; + case MP_TOKEN_DEL_PLUS_EQUAL: + op = MP_BINARY_OP_INPLACE_ADD; + break; + case MP_TOKEN_DEL_MINUS_EQUAL: + op = MP_BINARY_OP_INPLACE_SUBTRACT; + break; + case MP_TOKEN_DEL_STAR_EQUAL: + op = MP_BINARY_OP_INPLACE_MULTIPLY; + break; + case MP_TOKEN_DEL_DBL_SLASH_EQUAL: + op = MP_BINARY_OP_INPLACE_FLOOR_DIVIDE; + break; + case MP_TOKEN_DEL_SLASH_EQUAL: + op = MP_BINARY_OP_INPLACE_TRUE_DIVIDE; + break; + case MP_TOKEN_DEL_PERCENT_EQUAL: + op = MP_BINARY_OP_INPLACE_MODULO; + break; + case MP_TOKEN_DEL_DBL_STAR_EQUAL: + default: + op = MP_BINARY_OP_INPLACE_POWER; + break; } EMIT_ARG(binary_op, op); c_assign(comp, pns->nodes[0], ASSIGN_AUG_STORE); // lhs store for aug assign @@ -1965,8 +1990,8 @@ STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { #if MICROPY_COMP_DOUBLE_TUPLE_ASSIGN if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_testlist_star_expr) && MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_star_expr)) { - mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t*)pns->nodes[0]; - pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns0 = (mp_parse_node_struct_t *)pns->nodes[0]; + pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; uint32_t n_pns0 = MP_PARSE_NODE_STRUCT_NUM_NODES(pns0); // Can only optimise a tuple-to-tuple assignment when all of the following hold: // - equal number of items in LHS and RHS tuples @@ -2016,7 +2041,7 @@ STATIC void compile_expr_stmt(compiler_t *comp, mp_parse_node_struct_t *pns) { STATIC void compile_test_if_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_test_if_else)); - mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_test_if_else = (mp_parse_node_struct_t *)pns->nodes[1]; uint l_fail = comp_next_label(comp); uint l_end = comp_next_label(comp); @@ -2038,7 +2063,7 @@ STATIC void compile_lambdef(compiler_t *comp, mp_parse_node_struct_t *pns) { } // get the scope for this lambda - scope_t *this_scope = (scope_t*)pns->nodes[2]; + scope_t *this_scope = (scope_t *)pns->nodes[2]; // compile the lambda definition compile_funcdef_lambdef(comp, this_scope, pns->nodes[0], PN_varargslist); @@ -2079,18 +2104,33 @@ STATIC void compile_comparison(compiler_t *comp, mp_parse_node_struct_t *pns) { if (MP_PARSE_NODE_IS_TOKEN(pns->nodes[i])) { mp_binary_op_t op; switch (MP_PARSE_NODE_LEAF_ARG(pns->nodes[i])) { - case MP_TOKEN_OP_LESS: op = MP_BINARY_OP_LESS; break; - case MP_TOKEN_OP_MORE: op = MP_BINARY_OP_MORE; break; - case MP_TOKEN_OP_DBL_EQUAL: op = MP_BINARY_OP_EQUAL; break; - case MP_TOKEN_OP_LESS_EQUAL: op = MP_BINARY_OP_LESS_EQUAL; break; - case MP_TOKEN_OP_MORE_EQUAL: op = MP_BINARY_OP_MORE_EQUAL; break; - case MP_TOKEN_OP_NOT_EQUAL: op = MP_BINARY_OP_NOT_EQUAL; break; - case MP_TOKEN_KW_IN: default: op = MP_BINARY_OP_IN; break; + case MP_TOKEN_OP_LESS: + op = MP_BINARY_OP_LESS; + break; + case MP_TOKEN_OP_MORE: + op = MP_BINARY_OP_MORE; + break; + case MP_TOKEN_OP_DBL_EQUAL: + op = MP_BINARY_OP_EQUAL; + break; + case MP_TOKEN_OP_LESS_EQUAL: + op = MP_BINARY_OP_LESS_EQUAL; + break; + case MP_TOKEN_OP_MORE_EQUAL: + op = MP_BINARY_OP_MORE_EQUAL; + break; + case MP_TOKEN_OP_NOT_EQUAL: + op = MP_BINARY_OP_NOT_EQUAL; + break; + case MP_TOKEN_KW_IN: + default: + op = MP_BINARY_OP_IN; + break; } EMIT_ARG(binary_op, op); } else { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[i])); // should be - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[i]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[i]; int kind = MP_PARSE_NODE_STRUCT_KIND(pns2); if (kind == PN_comp_op_not_in) { EMIT_ARG(binary_op, MP_BINARY_OP_NOT_IN); @@ -2142,13 +2182,27 @@ STATIC void compile_term(compiler_t *comp, mp_parse_node_struct_t *pns) { mp_binary_op_t op; mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(pns->nodes[i]); switch (tok) { - case MP_TOKEN_OP_PLUS: op = MP_BINARY_OP_ADD; break; - case MP_TOKEN_OP_MINUS: op = MP_BINARY_OP_SUBTRACT; break; - case MP_TOKEN_OP_STAR: op = MP_BINARY_OP_MULTIPLY; break; - case MP_TOKEN_OP_DBL_SLASH: op = MP_BINARY_OP_FLOOR_DIVIDE; break; - case MP_TOKEN_OP_SLASH: op = MP_BINARY_OP_TRUE_DIVIDE; break; - case MP_TOKEN_OP_PERCENT: op = MP_BINARY_OP_MODULO; break; - case MP_TOKEN_OP_DBL_LESS: op = MP_BINARY_OP_LSHIFT; break; + case MP_TOKEN_OP_PLUS: + op = MP_BINARY_OP_ADD; + break; + case MP_TOKEN_OP_MINUS: + op = MP_BINARY_OP_SUBTRACT; + break; + case MP_TOKEN_OP_STAR: + op = MP_BINARY_OP_MULTIPLY; + break; + case MP_TOKEN_OP_DBL_SLASH: + op = MP_BINARY_OP_FLOOR_DIVIDE; + break; + case MP_TOKEN_OP_SLASH: + op = MP_BINARY_OP_TRUE_DIVIDE; + break; + case MP_TOKEN_OP_PERCENT: + op = MP_BINARY_OP_MODULO; + break; + case MP_TOKEN_OP_DBL_LESS: + op = MP_BINARY_OP_LSHIFT; + break; default: assert(tok == MP_TOKEN_OP_DBL_MORE); op = MP_BINARY_OP_RSHIFT; @@ -2163,8 +2217,12 @@ STATIC void compile_factor_2(compiler_t *comp, mp_parse_node_struct_t *pns) { mp_unary_op_t op; mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); switch (tok) { - case MP_TOKEN_OP_PLUS: op = MP_UNARY_OP_POSITIVE; break; - case MP_TOKEN_OP_MINUS: op = MP_UNARY_OP_NEGATIVE; break; + case MP_TOKEN_OP_PLUS: + op = MP_UNARY_OP_POSITIVE; + break; + case MP_TOKEN_OP_MINUS: + op = MP_UNARY_OP_NEGATIVE; + break; default: assert(tok == MP_TOKEN_OP_TILDE); op = MP_UNARY_OP_INVERT; @@ -2184,10 +2242,10 @@ STATIC void compile_atom_expr_normal(compiler_t *comp, mp_parse_node_struct_t *p // get the array of trailers (known to be an array of PARSE_NODE_STRUCT) size_t num_trail = 1; - mp_parse_node_struct_t **pns_trail = (mp_parse_node_struct_t**)&pns->nodes[1]; + mp_parse_node_struct_t **pns_trail = (mp_parse_node_struct_t **)&pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns_trail[0]) == PN_atom_expr_trailers) { num_trail = MP_PARSE_NODE_STRUCT_NUM_NODES(pns_trail[0]); - pns_trail = (mp_parse_node_struct_t**)&pns_trail[0]->nodes[0]; + pns_trail = (mp_parse_node_struct_t **)&pns_trail[0]->nodes[0]; } // the current index into the array of trailers @@ -2277,7 +2335,7 @@ STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_ar mp_parse_node_struct_t *star_args_node = NULL, *dblstar_args_node = NULL; for (int i = 0; i < n_args; i++) { if (MP_PARSE_NODE_IS_STRUCT(args[i])) { - mp_parse_node_struct_t *pns_arg = (mp_parse_node_struct_t*)args[i]; + mp_parse_node_struct_t *pns_arg = (mp_parse_node_struct_t *)args[i]; if (MP_PARSE_NODE_STRUCT_KIND(pns_arg) == PN_arglist_star) { if (star_flags & MP_EMIT_STAR_FLAG_SINGLE) { compile_syntax_error(comp, (mp_parse_node_t)pns_arg, translate("can't have multiple *x")); @@ -2309,7 +2367,7 @@ STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_ar goto normal_argument; } } else { - normal_argument: + normal_argument: if (star_flags) { compile_syntax_error(comp, args[i], translate("non-keyword arg after */**")); return; @@ -2350,7 +2408,7 @@ STATIC void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_ar STATIC void compile_comprehension(compiler_t *comp, mp_parse_node_struct_t *pns, scope_kind_t kind) { assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 2); assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_comp_for)); - mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t *)pns->nodes[1]; if (comp->pass == MP_PASS_SCOPE) { // create a new scope for this comprehension @@ -2360,7 +2418,7 @@ STATIC void compile_comprehension(compiler_t *comp, mp_parse_node_struct_t *pns, } // get the scope for this comprehension - scope_t *this_scope = (scope_t*)pns_comp_for->nodes[3]; + scope_t *this_scope = (scope_t *)pns_comp_for->nodes[3]; // compile the comprehension close_over_variables_etc(comp, this_scope, 0, 0); @@ -2378,10 +2436,10 @@ STATIC void compile_atom_paren(compiler_t *comp, mp_parse_node_struct_t *pns) { c_tuple(comp, MP_PARSE_NODE_NULL, NULL); } else { assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)); - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; assert(!MP_PARSE_NODE_IS_NULL(pns->nodes[1])); if (MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])) { - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_testlist_comp_3b) { // tuple of one item, with trailing comma assert(MP_PARSE_NODE_IS_NULL(pns2->nodes[0])); @@ -2398,7 +2456,7 @@ STATIC void compile_atom_paren(compiler_t *comp, mp_parse_node_struct_t *pns) { } } else { // tuple with 2 items - tuple_with_2_items: + tuple_with_2_items: c_tuple(comp, MP_PARSE_NODE_NULL, pns); } } @@ -2409,9 +2467,9 @@ STATIC void compile_atom_bracket(compiler_t *comp, mp_parse_node_struct_t *pns) // empty list EMIT_ARG(build, 0, MP_EMIT_BUILD_LIST); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) { - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)pns->nodes[0]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)pns->nodes[0]; if (MP_PARSE_NODE_IS_STRUCT(pns2->nodes[1])) { - mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t*)pns2->nodes[1]; + mp_parse_node_struct_t *pns3 = (mp_parse_node_struct_t *)pns2->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns3) == PN_testlist_comp_3b) { // list of one item, with trailing comma assert(MP_PARSE_NODE_IS_NULL(pns3->nodes[0])); @@ -2431,7 +2489,7 @@ STATIC void compile_atom_bracket(compiler_t *comp, mp_parse_node_struct_t *pns) } } else { // list with 2 items - list_with_2_items: + list_with_2_items: compile_node(comp, pns2->nodes[0]); compile_node(comp, pns2->nodes[1]); EMIT_ARG(build, 2, MP_EMIT_BUILD_LIST); @@ -2449,7 +2507,7 @@ STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) { // empty dict EMIT_ARG(build, 0, MP_EMIT_BUILD_MAP); } else if (MP_PARSE_NODE_IS_STRUCT(pn)) { - pns = (mp_parse_node_struct_t*)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker_item) { // dict with one element EMIT_ARG(build, 1, MP_EMIT_BUILD_MAP); @@ -2457,7 +2515,7 @@ STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) { EMIT(store_map); } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker) { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should succeed - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_dictorsetmaker_list) { // dict/set with multiple elements @@ -2487,9 +2545,9 @@ STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) { if (is_dict) { if (!is_key_value) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - compile_syntax_error(comp, (mp_parse_node_t)pns, translate("invalid syntax")); + compile_syntax_error(comp, (mp_parse_node_t)pns, translate("invalid syntax")); #else - compile_syntax_error(comp, (mp_parse_node_t)pns, translate("expecting key:value for dict")); + compile_syntax_error(comp, (mp_parse_node_t)pns, translate("expecting key:value for dict")); #endif return; } @@ -2497,9 +2555,9 @@ STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) { } else { if (is_key_value) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - compile_syntax_error(comp, (mp_parse_node_t)pns, translate("invalid syntax")); + compile_syntax_error(comp, (mp_parse_node_t)pns, translate("invalid syntax")); #else - compile_syntax_error(comp, (mp_parse_node_t)pns, translate("expecting just a value for set")); + compile_syntax_error(comp, (mp_parse_node_t)pns, translate("expecting just a value for set")); #endif return; } @@ -2529,7 +2587,7 @@ STATIC void compile_atom_brace(compiler_t *comp, mp_parse_node_struct_t *pns) { } } else { // set with one element - set_with_one_element: + set_with_one_element: #if MICROPY_PY_BUILTINS_SET compile_node(comp, pn); EMIT_ARG(build, 1, MP_EMIT_BUILD_SET); @@ -2559,7 +2617,7 @@ STATIC void compile_subscript(compiler_t *comp, mp_parse_node_struct_t *pns) { if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_2) { compile_node(comp, pns->nodes[0]); // start of slice assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should always be - pns = (mp_parse_node_struct_t*)pns->nodes[1]; + pns = (mp_parse_node_struct_t *)pns->nodes[1]; } else { // pns is a PN_subscript_3, load None for start of slice EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); @@ -2572,7 +2630,7 @@ STATIC void compile_subscript(compiler_t *comp, mp_parse_node_struct_t *pns) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(build, 2, MP_EMIT_BUILD_SLICE); } else if (MP_PARSE_NODE_IS_STRUCT(pn)) { - pns = (mp_parse_node_struct_t*)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3c) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); pn = pns->nodes[0]; @@ -2587,7 +2645,7 @@ STATIC void compile_subscript(compiler_t *comp, mp_parse_node_struct_t *pns) { } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_subscript_3d) { compile_node(comp, pns->nodes[0]); assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should always be - pns = (mp_parse_node_struct_t*)pns->nodes[1]; + pns = (mp_parse_node_struct_t *)pns->nodes[1]; assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_sliceop); // should always be if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) { // [?:x:] @@ -2631,13 +2689,13 @@ STATIC void compile_yield_expr(compiler_t *comp, mp_parse_node_struct_t *pns) { EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT_ARG(yield, MP_EMIT_YIELD_VALUE); } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_yield_arg_from)) { - pns = (mp_parse_node_struct_t*)pns->nodes[0]; -#if MICROPY_PY_ASYNC_AWAIT - if(comp->scope_cur->scope_flags & MP_SCOPE_FLAG_ASYNC) { + pns = (mp_parse_node_struct_t *)pns->nodes[0]; + #if MICROPY_PY_ASYNC_AWAIT + if (comp->scope_cur->scope_flags & MP_SCOPE_FLAG_ASYNC) { compile_syntax_error(comp, (mp_parse_node_t)pns, translate("'yield from' inside async function")); return; } -#endif + #endif compile_node(comp, pns->nodes[0]); compile_yield_from(comp); } else { @@ -2678,13 +2736,13 @@ STATIC void compile_const_object(compiler_t *comp, mp_parse_node_struct_t *pns) EMIT_ARG(load_const_obj, get_const_object(pns)); } -typedef void (*compile_function_t)(compiler_t*, mp_parse_node_struct_t*); +typedef void (*compile_function_t)(compiler_t *, mp_parse_node_struct_t *); STATIC const compile_function_t compile_function[] = { // only define rules with a compile function #define c(f) compile_##f #define DEF_RULE(rule, comp, kind, ...) comp, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef c #undef DEF_RULE #undef DEF_RULE_NC @@ -2716,8 +2774,12 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { } else if (MP_PARSE_NODE_IS_LEAF(pn)) { uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn); switch (MP_PARSE_NODE_LEAF_KIND(pn)) { - case MP_PARSE_NODE_ID: compile_load_id(comp, arg); break; - case MP_PARSE_NODE_STRING: EMIT_ARG(load_const_str, arg); break; + case MP_PARSE_NODE_ID: + compile_load_id(comp, arg); + break; + case MP_PARSE_NODE_STRING: + EMIT_ARG(load_const_str, arg); + break; case MP_PARSE_NODE_BYTES: // only create and load the actual bytes object on the last pass if (comp->pass != MP_PASS_EMIT) { @@ -2728,18 +2790,19 @@ STATIC void compile_node(compiler_t *comp, mp_parse_node_t pn) { EMIT_ARG(load_const_obj, mp_obj_new_bytes(data, len)); } break; - case MP_PARSE_NODE_TOKEN: default: + case MP_PARSE_NODE_TOKEN: + default: if (arg == MP_TOKEN_NEWLINE) { // this can occur when file_input lets through a NEWLINE (eg if file starts with a newline) // or when single_input lets through a NEWLINE (user enters a blank line) // do nothing } else { - EMIT_ARG(load_const_tok, arg); + EMIT_ARG(load_const_tok, arg); } break; } } else { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; EMIT_ARG(set_source_line, pns->source_line); assert(MP_PARSE_NODE_STRUCT_KIND(pns) <= PN_const_object); compile_function_t f = compile_function[MP_PARSE_NODE_STRUCT_KIND(pns)]; @@ -2767,7 +2830,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn } } else { assert(MP_PARSE_NODE_IS_STRUCT(pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == pn_name) { param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); if (comp->have_star) { @@ -2788,7 +2851,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn if (MP_PARSE_NODE_IS_NULL(pns->nodes[0])) { // bare star // TODO see http://www.python.org/dev/peps/pep-3102/ - //assert(comp->scope_cur->num_dict_params == 0); + // assert(comp->scope_cur->num_dict_params == 0); } else if (MP_PARSE_NODE_IS_ID(pns->nodes[0])) { // named star comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS; @@ -2797,7 +2860,7 @@ STATIC void compile_scope_func_lambda_param(compiler_t *comp, mp_parse_node_t pn assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)); // should be // named star with possible annotation comp->scope_cur->scope_flags |= MP_SCOPE_FLAG_VARARGS; - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; param_name = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); } } else { @@ -2835,14 +2898,14 @@ STATIC void compile_scope_func_annotations(compiler_t *comp, mp_parse_node_t pn) return; } - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_name) { // named parameter with possible annotation // fallthrough } else if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_typedargslist_star) { if (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_tfpdef)) { // named star with possible annotation - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; // fallthrough } else { // no annotation @@ -2879,7 +2942,7 @@ STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pn c_assign(comp, pns_comp_for->nodes[0], ASSIGN_STORE); mp_parse_node_t pn_iter = pns_comp_for->nodes[2]; - tail_recursion: +tail_recursion: if (MP_PARSE_NODE_IS_NULL(pn_iter)) { // no more nested if/for; compile inner expression compile_node(comp, pn_inner_expr); @@ -2889,16 +2952,16 @@ STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pn } else { EMIT_ARG(store_comp, comp->scope_cur->kind, 4 * for_depth + 5); } - } else if (MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_iter) == PN_comp_if) { + } else if (MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_iter) == PN_comp_if) { // if condition - mp_parse_node_struct_t *pns_comp_if = (mp_parse_node_struct_t*)pn_iter; + mp_parse_node_struct_t *pns_comp_if = (mp_parse_node_struct_t *)pn_iter; c_if_cond(comp, pns_comp_if->nodes[0], false, l_top); pn_iter = pns_comp_if->nodes[1]; goto tail_recursion; } else { - assert(MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)pn_iter) == PN_comp_for); // should be + assert(MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)pn_iter) == PN_comp_for); // should be // for loop - mp_parse_node_struct_t *pns_comp_for2 = (mp_parse_node_struct_t*)pn_iter; + mp_parse_node_struct_t *pns_comp_for2 = (mp_parse_node_struct_t *)pn_iter; compile_node(comp, pns_comp_for2->nodes[1]); EMIT_ARG(get_iter, true); compile_scope_comp_iter(comp, pns_comp_for2, pn_inner_expr, for_depth + 1); @@ -2910,7 +2973,7 @@ STATIC void compile_scope_comp_iter(compiler_t *comp, mp_parse_node_struct_t *pn } STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) { -#if MICROPY_ENABLE_DOC_STRING + #if MICROPY_ENABLE_DOC_STRING // see http://www.python.org/dev/peps/pep-0257/ // look for the first statement @@ -2918,7 +2981,7 @@ STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) { // a statement; fall through } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_file_input_2)) { // file input; find the first non-newline node - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; int num_nodes = MP_PARSE_NODE_STRUCT_NUM_NODES(pns); for (int i = 0; i < num_nodes; i++) { pn = pns->nodes[i]; @@ -2930,28 +2993,28 @@ STATIC void check_for_doc_string(compiler_t *comp, mp_parse_node_t pn) { // if we didn't find a non-newline then it's okay to fall through; pn will be a newline and so doc-string test below will fail gracefully } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_suite_block_stmts)) { // a list of statements; get the first one - pn = ((mp_parse_node_struct_t*)pn)->nodes[0]; + pn = ((mp_parse_node_struct_t *)pn)->nodes[0]; } else { return; } // check the first statement for a doc string if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_expr_stmt)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; if ((MP_PARSE_NODE_IS_LEAF(pns->nodes[0]) - && MP_PARSE_NODE_LEAF_KIND(pns->nodes[0]) == MP_PARSE_NODE_STRING) + && MP_PARSE_NODE_LEAF_KIND(pns->nodes[0]) == MP_PARSE_NODE_STRING) || (MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_const_object) - && MP_OBJ_IS_STR(get_const_object((mp_parse_node_struct_t*)pns->nodes[0])))) { - // compile the doc string - compile_node(comp, pns->nodes[0]); - // store the doc string - compile_store_id(comp, MP_QSTR___doc__); + && MP_OBJ_IS_STR(get_const_object((mp_parse_node_struct_t *)pns->nodes[0])))) { + // compile the doc string + compile_node(comp, pns->nodes[0]); + // store the doc string + compile_store_id(comp, MP_QSTR___doc__); } } -#else + #else (void)comp; (void)pn; -#endif + #endif } STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { @@ -2970,7 +3033,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { // compile if (MP_PARSE_NODE_IS_STRUCT_KIND(scope->pn, PN_eval_input)) { assert(scope->kind == SCOPE_MODULE); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; compile_node(comp, pns->nodes[0]); // compile the expression EMIT(return_value); } else if (scope->kind == SCOPE_MODULE) { @@ -2982,7 +3045,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { EMIT(return_value); } else if (scope->kind == SCOPE_FUNCTION) { assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_funcdef); // work out number of parameters, keywords and default parameters, and add them to the id_info array @@ -3021,7 +3084,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { } } else if (scope->kind == SCOPE_LAMBDA) { assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 3); // work out number of parameters, keywords and default parameters, and add them to the id_info array @@ -3043,10 +3106,10 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { // a bit of a hack at the moment assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 2); assert(MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[1], PN_comp_for)); - mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns_comp_for = (mp_parse_node_struct_t *)pns->nodes[1]; // We need a unique name for the comprehension argument (the iterator). // CPython uses .0, but we should be able to use anything that won't @@ -3093,7 +3156,7 @@ STATIC void compile_scope(compiler_t *comp, scope_t *scope, pass_kind_t pass) { } else { assert(scope->kind == SCOPE_CLASS); assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_classdef); if (comp->pass == MP_PASS_SCOPE) { @@ -3145,10 +3208,10 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind // get the function definition parse node assert(MP_PARSE_NODE_IS_STRUCT(scope->pn)); - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)scope->pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)scope->pn; assert(MP_PARSE_NODE_STRUCT_KIND(pns) == PN_funcdef); - //qstr f_id = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); // function name + // qstr f_id = MP_PARSE_NODE_LEAF_ARG(pns->nodes[0]); // function name // parameters are in pns->nodes[1] if (comp->pass == MP_PASS_CODE_SIZE) { @@ -3168,11 +3231,21 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind if (MP_PARSE_NODE_IS_ID(pn_annotation)) { qstr ret_type = MP_PARSE_NODE_LEAF_ARG(pn_annotation); switch (ret_type) { - case MP_QSTR_object: type_sig = MP_NATIVE_TYPE_OBJ; break; - case MP_QSTR_bool: type_sig = MP_NATIVE_TYPE_BOOL; break; - case MP_QSTR_int: type_sig = MP_NATIVE_TYPE_INT; break; - case MP_QSTR_uint: type_sig = MP_NATIVE_TYPE_UINT; break; - default: compile_syntax_error(comp, pn_annotation, translate("unknown type")); return; + case MP_QSTR_object: + type_sig = MP_NATIVE_TYPE_OBJ; + break; + case MP_QSTR_bool: + type_sig = MP_NATIVE_TYPE_BOOL; + break; + case MP_QSTR_int: + type_sig = MP_NATIVE_TYPE_INT; + break; + case MP_QSTR_uint: + type_sig = MP_NATIVE_TYPE_UINT; + break; + default: + compile_syntax_error(comp, pn_annotation, translate("unknown type")); + return; } } else { compile_syntax_error(comp, pn_annotation, translate("return annotation must be an identifier")); @@ -3185,7 +3258,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind for (int i = 0; i < num; i++) { assert(MP_PARSE_NODE_IS_STRUCT(nodes[i])); - mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t*)nodes[i]; + mp_parse_node_struct_t *pns2 = (mp_parse_node_struct_t *)nodes[i]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) == PN_pass_stmt) { // no instructions continue; @@ -3201,7 +3274,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind if (!MP_PARSE_NODE_IS_NULL(pns2->nodes[1])) { goto not_an_instruction; } - pns2 = (mp_parse_node_struct_t*)pns2->nodes[0]; + pns2 = (mp_parse_node_struct_t *)pns2->nodes[0]; if (MP_PARSE_NODE_STRUCT_KIND(pns2) != PN_atom_expr_normal) { goto not_an_instruction; } @@ -3215,7 +3288,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind // parse node looks like an instruction // get instruction name and args qstr op = MP_PARSE_NODE_LEAF_ARG(pns2->nodes[0]); - pns2 = (mp_parse_node_struct_t*)pns2->nodes[1]; // PN_trailer_paren + pns2 = (mp_parse_node_struct_t *)pns2->nodes[1]; // PN_trailer_paren mp_parse_node_t *pn_arg; int n_args = mp_parse_node_extract_list(&pns2->nodes[0], PN_arglist, &pn_arg); @@ -3238,7 +3311,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind return; } if (pass > MP_PASS_SCOPE) { - mp_asm_base_align((mp_asm_base_t*)comp->emit_inline_asm, + mp_asm_base_align((mp_asm_base_t *)comp->emit_inline_asm, MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[0])); } } else if (op == MP_QSTR_data) { @@ -3253,7 +3326,7 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind compile_syntax_error(comp, nodes[i], translate("'data' requires integer arguments")); return; } - mp_asm_base_data((mp_asm_base_t*)comp->emit_inline_asm, + mp_asm_base_data((mp_asm_base_t *)comp->emit_inline_asm, bytesize, MP_PARSE_NODE_LEAF_SMALL_INT(pn_arg[j])); } } @@ -3273,9 +3346,9 @@ STATIC void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind EMIT_INLINE_ASM_ARG(end_pass, type_sig); if (comp->pass == MP_PASS_EMIT) { - void *f = mp_asm_base_get_code((mp_asm_base_t*)comp->emit_inline_asm); + void *f = mp_asm_base_get_code((mp_asm_base_t *)comp->emit_inline_asm); mp_emit_glue_assign_native(comp->scope_cur->raw_code, MP_CODE_NATIVE_ASM, - f, mp_asm_base_get_code_size((mp_asm_base_t*)comp->emit_inline_asm), + f, mp_asm_base_get_code_size((mp_asm_base_t *)comp->emit_inline_asm), NULL, comp->scope_cur->num_pos_args, 0, type_sig); } } @@ -3297,7 +3370,9 @@ STATIC void scope_compute_things(scope_t *scope) { if (id->flags & ID_FLAG_IS_STAR_PARAM) { if (id_param != NULL) { // swap star param with last param - id_info_t temp = *id_param; *id_param = *id; *id = temp; + id_info_t temp = *id_param; + *id_param = *id; + *id = temp; } break; } else if (id_param == NULL && id->flags == ID_FLAG_IS_PARAM) { @@ -3418,9 +3493,9 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f emit_bc_set_max_num_labels(emit_bc, max_num_labels); // compile pass 2 and 3 -#if MICROPY_EMIT_NATIVE + #if MICROPY_EMIT_NATIVE emit_t *emit_native = NULL; -#endif + #endif for (scope_t *s = comp->scope_head; s != NULL && comp->compile_error == MP_OBJ_NULL; s = s->next) { if (false) { // dummy @@ -3451,7 +3526,7 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f switch (s->emit_options) { -#if MICROPY_EMIT_NATIVE + #if MICROPY_EMIT_NATIVE case MP_EMIT_OPT_NATIVE_PYTHON: case MP_EMIT_OPT_VIPER: if (emit_native == NULL) { @@ -3461,7 +3536,7 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f comp->emit = emit_native; EMIT_ARG(set_native_type, MP_EMIT_NATIVE_TYPE_ENABLE, s->emit_options == MP_EMIT_OPT_VIPER, 0); break; -#endif // MICROPY_EMIT_NATIVE + #endif // MICROPY_EMIT_NATIVE default: comp->emit = emit_bc; @@ -3498,11 +3573,11 @@ mp_raw_code_t *mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_f // free the emitters emit_bc_free(emit_bc); -#if MICROPY_EMIT_NATIVE + #if MICROPY_EMIT_NATIVE if (emit_native != NULL) { NATIVE_EMITTER(free)(emit_native); } -#endif + #endif #if MICROPY_EMIT_INLINE_ASM if (comp->emit_inline_asm != NULL) { ASM_EMITTER(free)(comp->emit_inline_asm); diff --git a/py/emit.h b/py/emit.h index 30543d2a3c..b142e0641b 100644 --- a/py/emit.h +++ b/py/emit.h @@ -184,7 +184,7 @@ emit_t *emit_native_thumb_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); emit_t *emit_native_arm_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); emit_t *emit_native_xtensa_new(mp_obj_t *error_slot, mp_uint_t max_num_labels); -void emit_bc_set_max_num_labels(emit_t* emit, mp_uint_t max_num_labels); +void emit_bc_set_max_num_labels(emit_t *emit, mp_uint_t max_num_labels); void emit_bc_free(emit_t *emit); void emit_native_x64_free(emit_t *emit); diff --git a/py/emitbc.c b/py/emitbc.c index f45dcb9167..37960cb6b4 100644 --- a/py/emitbc.c +++ b/py/emitbc.c @@ -107,7 +107,7 @@ STATIC void emit_write_uint(emit_t *emit, emit_allocator_t allocator, mp_uint_t // all functions must go through this one to emit code info STATIC byte *emit_get_cur_to_write_code_info(emit_t *emit, int num_bytes_to_write) { - //printf("emit %d\n", num_bytes_to_write); + // printf("emit %d\n", num_bytes_to_write); if (emit->pass < MP_PASS_EMIT) { emit->code_info_offset += num_bytes_to_write; return emit->dummy_data; @@ -119,11 +119,11 @@ STATIC byte *emit_get_cur_to_write_code_info(emit_t *emit, int num_bytes_to_writ } } -STATIC void emit_write_code_info_byte(emit_t* emit, byte val) { +STATIC void emit_write_code_info_byte(emit_t *emit, byte val) { *emit_get_cur_to_write_code_info(emit, 1) = val; } -STATIC void emit_write_code_info_uint(emit_t* emit, mp_uint_t val) { +STATIC void emit_write_code_info_uint(emit_t *emit, mp_uint_t val) { emit_write_uint(emit, emit_get_cur_to_write_code_info, val); } @@ -141,7 +141,7 @@ STATIC void emit_write_code_info_qstr(emit_t *emit, qstr qst) { #if MICROPY_ENABLE_SOURCE_LINE STATIC void emit_write_code_info_bytes_lines(emit_t *emit, mp_uint_t bytes_to_skip, mp_uint_t lines_to_skip) { assert(bytes_to_skip > 0 || lines_to_skip > 0); - //printf(" %d %d\n", bytes_to_skip, lines_to_skip); + // printf(" %d %d\n", bytes_to_skip, lines_to_skip); while (bytes_to_skip > 0 || lines_to_skip > 0) { mp_uint_t b, l; if (lines_to_skip <= 6 || bytes_to_skip > 0xf) { @@ -170,7 +170,7 @@ STATIC void emit_write_code_info_bytes_lines(emit_t *emit, mp_uint_t bytes_to_sk // all functions must go through this one to emit byte code STATIC byte *emit_get_cur_to_write_bytecode(emit_t *emit, int num_bytes_to_write) { - //printf("emit %d\n", num_bytes_to_write); + // printf("emit %d\n", num_bytes_to_write); if (emit->pass < MP_PASS_EMIT) { emit->bytecode_offset += num_bytes_to_write; return emit->dummy_data; @@ -187,7 +187,7 @@ STATIC void emit_write_bytecode_byte(emit_t *emit, byte b1) { c[0] = b1; } -STATIC void emit_write_bytecode_byte_byte(emit_t* emit, byte b1, byte b2) { +STATIC void emit_write_bytecode_byte_byte(emit_t *emit, byte b1, byte b2) { byte *c = emit_get_cur_to_write_bytecode(emit, 2); c[0] = b1; c[1] = b2; @@ -234,7 +234,7 @@ STATIC void emit_write_bytecode_byte_const(emit_t *emit, byte b, mp_uint_t n, mp } #endif -STATIC void emit_write_bytecode_byte_qstr(emit_t* emit, byte b, qstr qst) { +STATIC void emit_write_bytecode_byte_qstr(emit_t *emit, byte b, qstr qst) { #if MICROPY_PERSISTENT_CODE assert((qst >> 16) == 0); byte *c = emit_get_cur_to_write_bytecode(emit, 3); @@ -255,7 +255,7 @@ STATIC void emit_write_bytecode_byte_obj(emit_t *emit, byte b, mp_obj_t obj) { // aligns the pointer so it is friendly to GC emit_write_bytecode_byte(emit, b); emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(mp_obj_t)); - mp_obj_t *c = (mp_obj_t*)emit_get_cur_to_write_bytecode(emit, sizeof(mp_obj_t)); + mp_obj_t *c = (mp_obj_t *)emit_get_cur_to_write_bytecode(emit, sizeof(mp_obj_t)); // Verify thar c is already uint-aligned assert(c == MP_ALIGN(c, sizeof(mp_obj_t))); *c = obj; @@ -270,10 +270,10 @@ STATIC void emit_write_bytecode_byte_raw_code(emit_t *emit, byte b, mp_raw_code_ #else // aligns the pointer so it is friendly to GC emit_write_bytecode_byte(emit, b); - emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(void*)); - void **c = (void**)emit_get_cur_to_write_bytecode(emit, sizeof(void*)); + emit->bytecode_offset = (size_t)MP_ALIGN(emit->bytecode_offset, sizeof(void *)); + void **c = (void **)emit_get_cur_to_write_bytecode(emit, sizeof(void *)); // Verify thar c is already uint-aligned - assert(c == MP_ALIGN(c, sizeof(void*))); + assert(c == MP_ALIGN(c, sizeof(void *))); *c = rc; #endif } @@ -347,7 +347,7 @@ void mp_emit_bc_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope) { // for it and hope that is enough! TODO assert this or something. if (pass == MP_PASS_EMIT) { emit_write_code_info_uint(emit, emit->code_info_size - emit->code_info_offset); - } else { + } else { emit_get_cur_to_write_code_info(emit, 2); } @@ -469,8 +469,8 @@ static inline void emit_bc_pre(emit_t *emit, mp_int_t stack_size_delta) { } void mp_emit_bc_set_source_line(emit_t *emit, mp_uint_t source_line) { - //printf("source: line %d -> %d offset %d -> %d\n", emit->last_source_line, source_line, emit->last_source_line_offset, emit->bytecode_offset); -#if MICROPY_ENABLE_SOURCE_LINE + // printf("source: line %d -> %d offset %d -> %d\n", emit->last_source_line, source_line, emit->last_source_line_offset, emit->bytecode_offset); + #if MICROPY_ENABLE_SOURCE_LINE if (MP_STATE_VM(mp_optimise_value) >= 3) { // If we compile with -O3, don't store line numbers. return; @@ -482,10 +482,10 @@ void mp_emit_bc_set_source_line(emit_t *emit, mp_uint_t source_line) { emit->last_source_line_offset = emit->bytecode_offset; emit->last_source_line = source_line; } -#else + #else (void)emit; (void)source_line; -#endif + #endif } void mp_emit_bc_label_assign(emit_t *emit, mp_uint_t l) { @@ -522,9 +522,15 @@ void mp_emit_bc_import(emit_t *emit, qstr qst, int kind) { void mp_emit_bc_load_const_tok(emit_t *emit, mp_token_kind_t tok) { emit_bc_pre(emit, 1); switch (tok) { - case MP_TOKEN_KW_FALSE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_FALSE); break; - case MP_TOKEN_KW_NONE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_NONE); break; - case MP_TOKEN_KW_TRUE: emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_TRUE); break; + case MP_TOKEN_KW_FALSE: + emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_FALSE); + break; + case MP_TOKEN_KW_NONE: + emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_NONE); + break; + case MP_TOKEN_KW_TRUE: + emit_write_bytecode_byte(emit, MP_BC_LOAD_CONST_TRUE); + break; default: assert(tok == MP_TOKEN_ELLIPSIS); emit_write_bytecode_byte_obj(emit, MP_BC_LOAD_CONST_OBJ, MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj)); @@ -724,8 +730,8 @@ void mp_emit_bc_setup_block(emit_t *emit, mp_uint_t label, int kind) { MP_STATIC_ASSERT(MP_BC_SETUP_WITH + MP_EMIT_SETUP_BLOCK_EXCEPT == MP_BC_SETUP_EXCEPT); MP_STATIC_ASSERT(MP_BC_SETUP_WITH + MP_EMIT_SETUP_BLOCK_FINALLY == MP_BC_SETUP_FINALLY); if (kind == MP_EMIT_SETUP_BLOCK_WITH) { - // The SETUP_WITH opcode pops ctx_mgr from the top of the stack - // and then pushes 3 entries: __exit__, ctx_mgr, as_value. + // The SETUP_WITH opcode pops ctx_mgr from the top of the stack + // and then pushes 3 entries: __exit__, ctx_mgr, as_value. emit_bc_pre(emit, 2); } else { emit_bc_pre(emit, 0); @@ -993,4 +999,4 @@ const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_delete_id_ops = { }; #endif -#endif //MICROPY_ENABLE_COMPILER +#endif // MICROPY_ENABLE_COMPILER diff --git a/py/emitglue.c b/py/emitglue.c index 7635a73d6a..d0286803e7 100644 --- a/py/emitglue.c +++ b/py/emitglue.c @@ -75,14 +75,14 @@ void mp_emit_glue_assign_bytecode(mp_raw_code_t *rc, const byte *code, rc->data.u_byte.n_raw_code = n_raw_code; #endif -#ifdef DEBUG_PRINT + #ifdef DEBUG_PRINT DEBUG_printf("assign byte code: code=%p len=" UINT_FMT " flags=%x\n", code, len, (uint)scope_flags); -#endif -#if MICROPY_DEBUG_PRINTERS + #endif + #if MICROPY_DEBUG_PRINTERS if (mp_verbose_flag >= 2) { mp_bytecode_print(rc, code, len, const_table); } -#endif + #endif } #if MICROPY_EMIT_NATIVE || MICROPY_EMIT_INLINE_ASM @@ -95,24 +95,24 @@ void mp_emit_glue_assign_native(mp_raw_code_t *rc, mp_raw_code_kind_t kind, void rc->data.u_native.const_table = const_table; rc->data.u_native.type_sig = type_sig; -#ifdef DEBUG_PRINT + #ifdef DEBUG_PRINT DEBUG_printf("assign native: kind=%d fun=%p len=" UINT_FMT " n_pos_args=" UINT_FMT " flags=%x\n", kind, fun_data, fun_len, n_pos_args, (uint)scope_flags); for (mp_uint_t i = 0; i < fun_len; i++) { if (i > 0 && i % 16 == 0) { DEBUG_printf("\n"); } - DEBUG_printf(" %02x", ((byte*)fun_data)[i]); + DEBUG_printf(" %02x", ((byte *)fun_data)[i]); } DEBUG_printf("\n"); -#ifdef WRITE_CODE + #ifdef WRITE_CODE FILE *fp_write_code = fopen("out-code", "wb"); fwrite(fun_data, fun_len, 1, fp_write_code); fclose(fp_write_code); -#endif -#else + #endif + #else (void)fun_len; -#endif + #endif } #endif diff --git a/py/emitinlinethumb.c b/py/emitinlinethumb.c index 47ed14321e..1faeccbd27 100644 --- a/py/emitinlinethumb.c +++ b/py/emitinlinethumb.c @@ -39,14 +39,14 @@ typedef enum { // define rules with a compile function #define DEF_RULE(rule, comp, kind, ...) PN_##rule, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC PN_const_object, // special node for a constant, generic Python object // define rules without a compile function #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) PN_##rule, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC } pn_kind_t; @@ -131,7 +131,9 @@ STATIC bool emit_inline_thumb_label(emit_inline_asm_t *emit, mp_uint_t label_num return true; } -typedef struct _reg_name_t { byte reg; byte name[3]; } reg_name_t; +typedef struct _reg_name_t { byte reg; + byte name[3]; +} reg_name_t; STATIC const reg_name_t reg_name_table[] = { {0, "r0\0"}, {1, "r1\0"}, @@ -157,7 +159,9 @@ STATIC const reg_name_t reg_name_table[] = { }; #define MAX_SPECIAL_REGISTER_NAME_LENGTH 7 -typedef struct _special_reg_name_t { byte reg; char name[MAX_SPECIAL_REGISTER_NAME_LENGTH + 1]; } special_reg_name_t; +typedef struct _special_reg_name_t { byte reg; + char name[MAX_SPECIAL_REGISTER_NAME_LENGTH + 1]; +} special_reg_name_t; STATIC const special_reg_name_t special_reg_name_table[] = { {5, "IPSR"}, {17, "BASEPRI"}, @@ -226,8 +230,8 @@ STATIC mp_uint_t get_arg_vfpreg(emit_inline_asm_t *emit, const char *op, mp_pars } if (regno > 31) { emit_inline_thumb_error_exc(emit, - mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, - translate("'%s' expects at most r%d"), op, 31)); + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + translate("'%s' expects at most r%d"), op, 31)); return 0; } else { return regno; @@ -235,7 +239,7 @@ STATIC mp_uint_t get_arg_vfpreg(emit_inline_asm_t *emit, const char *op, mp_pars } malformed: emit_inline_thumb_error_exc(emit, - mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, translate("'%s' expects an FPU register"), op)); return 0; } @@ -248,7 +252,7 @@ STATIC mp_uint_t get_arg_reglist(emit_inline_asm_t *emit, const char *op, mp_par goto bad_arg; } - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; assert(MP_PARSE_NODE_STRUCT_NUM_NODES(pns) == 1); // should always be pn = pns->nodes[0]; @@ -258,10 +262,10 @@ STATIC mp_uint_t get_arg_reglist(emit_inline_asm_t *emit, const char *op, mp_par // set with one element reglist |= 1 << get_arg_reg(emit, op, pn, 15); } else if (MP_PARSE_NODE_IS_STRUCT(pn)) { - pns = (mp_parse_node_struct_t*)pn; + pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == PN_dictorsetmaker) { assert(MP_PARSE_NODE_IS_STRUCT(pns->nodes[1])); // should succeed - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pns->nodes[1]; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pns->nodes[1]; if (MP_PARSE_NODE_STRUCT_KIND(pns1) == PN_dictorsetmaker_list) { // set with multiple elements @@ -311,11 +315,11 @@ STATIC bool get_arg_addr(emit_inline_asm_t *emit, const char *op, mp_parse_node_ if (!MP_PARSE_NODE_IS_STRUCT_KIND(pn, PN_atom_bracket)) { goto bad_arg; } - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; if (!MP_PARSE_NODE_IS_STRUCT_KIND(pns->nodes[0], PN_testlist_comp)) { goto bad_arg; } - pns = (mp_parse_node_struct_t*)pns->nodes[0]; + pns = (mp_parse_node_struct_t *)pns->nodes[0]; if (MP_PARSE_NODE_STRUCT_NUM_NODES(pns) != 2) { goto bad_arg; } @@ -347,7 +351,9 @@ STATIC int get_arg_label(emit_inline_asm_t *emit, const char *op, mp_parse_node_ return 0; } -typedef struct _cc_name_t { byte cc; byte name[2]; } cc_name_t; +typedef struct _cc_name_t { byte cc; + byte name[2]; +} cc_name_t; STATIC const cc_name_t cc_name_table[] = { { ASM_THUMB_CC_EQ, "eq" }, { ASM_THUMB_CC_NE, "ne" }, @@ -365,7 +371,9 @@ STATIC const cc_name_t cc_name_table[] = { { ASM_THUMB_CC_LE, "le" }, }; -typedef struct _format_4_op_t { byte op; char name[3]; } format_4_op_t; +typedef struct _format_4_op_t { byte op; + char name[3]; +} format_4_op_t; #define X(x) (((x) >> 4) & 0xff) // only need 1 byte to distinguish these ops STATIC const format_4_op_t format_4_op_table[] = { { X(ASM_THUMB_FORMAT_4_EOR), "eor" }, @@ -387,7 +395,9 @@ STATIC const format_4_op_t format_4_op_table[] = { #undef X // name is actually a qstr, which should fit in 16 bits -typedef struct _format_9_10_op_t { uint16_t op; uint16_t name; } format_9_10_op_t; +typedef struct _format_9_10_op_t { uint16_t op; + uint16_t name; +} format_9_10_op_t; #define X(x) (x) STATIC const format_9_10_op_t format_9_10_op_table[] = { { X(ASM_THUMB_FORMAT_9_LDR | ASM_THUMB_FORMAT_9_WORD_TRANSFER), MP_QSTR_ldr }, @@ -401,7 +411,9 @@ STATIC const format_9_10_op_t format_9_10_op_table[] = { #if MICROPY_EMIT_INLINE_THUMB_FLOAT // actual opcodes are: 0xee00 | op.hi_nibble, 0x0a00 | op.lo_nibble -typedef struct _format_vfp_op_t { byte op; char name[3]; } format_vfp_op_t; +typedef struct _format_vfp_op_t { byte op; + char name[3]; +} format_vfp_op_t; STATIC const format_vfp_op_t format_vfp_op_table[] = { { 0x30, "add" }, { 0x34, "sub" }, @@ -425,7 +437,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a // "subs", RLO, RLO, I3, asm_thumb_subs_reg_reg_i3 size_t op_len; - const char *op_str = (const char*)qstr_data(op, &op_len); + const char *op_str = (const char *)qstr_data(op, &op_len); #if MICROPY_EMIT_INLINE_THUMB_FLOAT if (op_str[0] == 'v') { @@ -434,7 +446,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a mp_uint_t op_code = 0x0ac0, op_code_hi; if (op == MP_QSTR_vcmp) { op_code_hi = 0xeeb4; - op_vfp_twoargs:; + op_vfp_twoargs:; mp_uint_t vd = get_arg_vfpreg(emit, op_str, pn_args[0]); mp_uint_t vm = get_arg_vfpreg(emit, op_str, pn_args[1]); asm_thumb_op32(&emit->as, @@ -485,7 +497,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a 0x0a10 | (r_arm << 12) | ((vm & 1) << 7)); } else if (op == MP_QSTR_vldr) { op_code_hi = 0xed90; - op_vldr_vstr:; + op_vldr_vstr:; mp_uint_t vd = get_arg_vfpreg(emit, op_str, pn_args[0]); mp_parse_node_t pn_base, pn_offset; if (get_arg_addr(emit, op_str, pn_args[1], &pn_base, &pn_offset)) { @@ -547,8 +559,8 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a mp_uint_t r = get_arg_reg(emit, op_str, pn_args[0], 15); asm_thumb_op16(&emit->as, 0x4700 | (r << 3)); } else if (op_str[0] == 'b' && (op_len == 3 - || (op_len == 5 && op_str[3] == '_' - && (op_str[4] == 'n' || (ARMV7M && op_str[4] == 'w'))))) { + || (op_len == 5 && op_str[3] == '_' + && (op_str[4] == 'n' || (ARMV7M && op_str[4] == 'w'))))) { mp_uint_t cc = -1; for (mp_uint_t i = 0; i < MP_ARRAY_SIZE(cc_name_table); i++) { if (op_str[1] == cc_name_table[i].name[0] && op_str[2] == cc_name_table[i].name[1]) { @@ -637,7 +649,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a op_code_hi = 0xfab0; op_code = 0xf080; mp_uint_t rd, rm; - op_clz_rbit: + op_clz_rbit: rd = get_arg_reg(emit, op_str, pn_args[0], 15); rm = get_arg_reg(emit, op_str, pn_args[1], 15); asm_thumb_op32(&emit->as, op_code_hi | rm, op_code | (rd << 8) | rm); @@ -645,7 +657,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a op_code_hi = 0xfa90; op_code = 0xf0a0; goto op_clz_rbit; - } else if (ARMV7M && op == MP_QSTR_mrs){ + } else if (ARMV7M && op == MP_QSTR_mrs) { mp_uint_t reg_dest = get_arg_reg(emit, op_str, pn_args[0], 12); mp_uint_t reg_src = get_arg_special_reg(emit, op_str, pn_args[1]); asm_thumb_op32(&emit->as, 0xf3ef, 0x8000 | (reg_dest << 8) | reg_src); @@ -653,7 +665,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a if (op == MP_QSTR_and_) { op_code = ASM_THUMB_FORMAT_4_AND; mp_uint_t reg_dest, reg_src; - op_format_4: + op_format_4: reg_dest = get_arg_reg(emit, op_str, pn_args[0], 7); reg_src = get_arg_reg(emit, op_str, pn_args[1], 7); asm_thumb_format_4(&emit->as, op_code, reg_dest, reg_src); @@ -674,7 +686,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a if (op == MP_QSTR_mov) { op_code = ASM_THUMB_FORMAT_3_MOV; mp_uint_t rlo_dest, i8_src; - op_format_3: + op_format_3: rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7); i8_src = get_arg_i(emit, op_str, pn_args[1], 0xff); asm_thumb_format_3(&emit->as, op_code, rlo_dest, i8_src); @@ -690,7 +702,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a } else if (ARMV7M && op == MP_QSTR_movw) { op_code = ASM_THUMB_OP_MOVW; mp_uint_t reg_dest; - op_movw_movt: + op_movw_movt: reg_dest = get_arg_reg(emit, op_str, pn_args[0], 15); int i_src = get_arg_i(emit, op_str, pn_args[1], 0xffff); asm_thumb_mov_reg_i16(&emit->as, op_code, reg_dest, i_src); @@ -743,7 +755,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a if (op == MP_QSTR_lsl) { op_code = ASM_THUMB_FORMAT_1_LSL; mp_uint_t rlo_dest, rlo_src, i5; - op_format_1: + op_format_1: rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7); rlo_src = get_arg_reg(emit, op_str, pn_args[1], 7); i5 = get_arg_i(emit, op_str, pn_args[2], 0x1f); @@ -757,7 +769,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a } else if (op == MP_QSTR_add) { op_code = ASM_THUMB_FORMAT_2_ADD; mp_uint_t rlo_dest, rlo_src; - op_format_2: + op_format_2: rlo_dest = get_arg_reg(emit, op_str, pn_args[0], 7); rlo_src = get_arg_reg(emit, op_str, pn_args[1], 7); int src_b; @@ -772,7 +784,7 @@ STATIC void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a } else if (ARMV7M && op == MP_QSTR_sdiv) { op_code = 0xfb90; // sdiv high part mp_uint_t rd, rn, rm; - op_sdiv_udiv: + op_sdiv_udiv: rd = get_arg_reg(emit, op_str, pn_args[0], 15); rn = get_arg_reg(emit, op_str, pn_args[1], 15); rm = get_arg_reg(emit, op_str, pn_args[2], 15); diff --git a/py/emitinlinextensa.c b/py/emitinlinextensa.c index ae84aae2e3..8094c0befa 100644 --- a/py/emitinlinextensa.c +++ b/py/emitinlinextensa.c @@ -115,7 +115,9 @@ STATIC bool emit_inline_xtensa_label(emit_inline_asm_t *emit, mp_uint_t label_nu return true; } -typedef struct _reg_name_t { byte reg; byte name[3]; } reg_name_t; +typedef struct _reg_name_t { byte reg; + byte name[3]; +} reg_name_t; STATIC const reg_name_t reg_name_table[] = { {0, "a0\0"}, {1, "a1\0"}, @@ -242,7 +244,7 @@ STATIC const opcode_table_3arg_t opcode_table_3arg[] = { STATIC void emit_inline_xtensa_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_args, mp_parse_node_t *pn_args) { size_t op_len; - const char *op_str = (const char*)qstr_data(op, &op_len); + const char *op_str = (const char *)qstr_data(op, &op_len); if (n_args == 0) { if (op == MP_QSTR_ret_n) { diff --git a/py/emitnative.c b/py/emitnative.c index 51919e389b..57b75030a4 100644 --- a/py/emitnative.c +++ b/py/emitnative.c @@ -86,7 +86,7 @@ #define EMIT_NATIVE_VIPER_TYPE_ERROR(emit, ...) do { \ *emit->error_slot = mp_obj_new_exception_msg_varg(&mp_type_ViperTypeError, __VA_ARGS__); \ - } while (0) +} while (0) typedef enum { STACK_VALUE, @@ -114,15 +114,25 @@ typedef enum { STATIC qstr vtype_to_qstr(vtype_kind_t vtype) { switch (vtype) { - case VTYPE_PYOBJ: return MP_QSTR_object; - case VTYPE_BOOL: return MP_QSTR_bool; - case VTYPE_INT: return MP_QSTR_int; - case VTYPE_UINT: return MP_QSTR_uint; - case VTYPE_PTR: return MP_QSTR_ptr; - case VTYPE_PTR8: return MP_QSTR_ptr8; - case VTYPE_PTR16: return MP_QSTR_ptr16; - case VTYPE_PTR32: return MP_QSTR_ptr32; - case VTYPE_PTR_NONE: default: return MP_QSTR_None; + case VTYPE_PYOBJ: + return MP_QSTR_object; + case VTYPE_BOOL: + return MP_QSTR_bool; + case VTYPE_INT: + return MP_QSTR_int; + case VTYPE_UINT: + return MP_QSTR_uint; + case VTYPE_PTR: + return MP_QSTR_ptr; + case VTYPE_PTR8: + return MP_QSTR_ptr8; + case VTYPE_PTR16: + return MP_QSTR_ptr16; + case VTYPE_PTR32: + return MP_QSTR_ptr32; + case VTYPE_PTR_NONE: + default: + return MP_QSTR_None; } } @@ -163,7 +173,7 @@ struct _emit_t { ASM_T *as; }; -emit_t *EXPORT_FUN(new)(mp_obj_t *error_slot, mp_uint_t max_num_labels) { +emit_t *EXPORT_FUN(new)(mp_obj_t * error_slot, mp_uint_t max_num_labels) { emit_t *emit = m_new0(emit_t, 1); emit->error_slot = error_slot; emit->as = m_new0(ASM_T, 1); @@ -171,7 +181,7 @@ emit_t *EXPORT_FUN(new)(mp_obj_t *error_slot, mp_uint_t max_num_labels) { return emit; } -void EXPORT_FUN(free)(emit_t *emit) { +void EXPORT_FUN(free)(emit_t * emit) { mp_asm_base_deinit(&emit->as->base, false); m_del_obj(ASM_T, emit->as); m_del(vtype_kind_t, emit->local_vtype, emit->local_vtype_alloc); @@ -188,15 +198,33 @@ STATIC void emit_native_set_native_type(emit_t *emit, mp_uint_t op, mp_uint_t ar default: { vtype_kind_t type; switch (arg2) { - case MP_QSTR_object: type = VTYPE_PYOBJ; break; - case MP_QSTR_bool: type = VTYPE_BOOL; break; - case MP_QSTR_int: type = VTYPE_INT; break; - case MP_QSTR_uint: type = VTYPE_UINT; break; - case MP_QSTR_ptr: type = VTYPE_PTR; break; - case MP_QSTR_ptr8: type = VTYPE_PTR8; break; - case MP_QSTR_ptr16: type = VTYPE_PTR16; break; - case MP_QSTR_ptr32: type = VTYPE_PTR32; break; - default: EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("unknown type '%q'"), arg2); return; + case MP_QSTR_object: + type = VTYPE_PYOBJ; + break; + case MP_QSTR_bool: + type = VTYPE_BOOL; + break; + case MP_QSTR_int: + type = VTYPE_INT; + break; + case MP_QSTR_uint: + type = VTYPE_UINT; + break; + case MP_QSTR_ptr: + type = VTYPE_PTR; + break; + case MP_QSTR_ptr8: + type = VTYPE_PTR8; + break; + case MP_QSTR_ptr16: + type = VTYPE_PTR16; + break; + case MP_QSTR_ptr32: + type = VTYPE_PTR32; + break; + default: + EMIT_NATIVE_VIPER_TYPE_ERROR(emit, translate("unknown type '%q'"), arg2); + return; } if (op == MP_EMIT_NATIVE_TYPE_RETURN) { emit->return_vtype = type; @@ -463,7 +491,7 @@ STATIC void emit_native_end_pass(emit_t *emit) { #pragma GCC diagnostic ignored "-Wcast-align" mp_emit_glue_assign_native(emit->scope->raw_code, emit->do_viper_types ? MP_CODE_NATIVE_VIPER : MP_CODE_NATIVE_PY, - f, f_len, (mp_uint_t*)((byte*)f + emit->const_table_offset), + f, f_len, (mp_uint_t *)((byte *)f + emit->const_table_offset), emit->scope->num_pos_args, emit->scope->scope_flags, type_sig); #pragma GCC diagnostic pop } @@ -479,14 +507,14 @@ STATIC void adjust_stack(emit_t *emit, mp_int_t stack_size_delta) { if (emit->pass > MP_PASS_SCOPE && emit->stack_size > emit->scope->stack_size) { emit->scope->stack_size = emit->stack_size; } -#ifdef DEBUG_PRINT + #ifdef DEBUG_PRINT DEBUG_printf(" adjust_stack; stack_size=%d+%d; stack now:", emit->stack_size - stack_size_delta, stack_size_delta); for (int i = 0; i < emit->stack_size; i++) { stack_info_t *si = &emit->stack_info[i]; DEBUG_printf(" (v=%d k=%d %d)", si->vtype, si->kind, si->data.u_reg); } DEBUG_printf("\n"); -#endif + #endif } STATIC void emit_native_adjust_stack_size(emit_t *emit, mp_int_t delta) { @@ -875,22 +903,40 @@ STATIC void emit_native_load_const_tok(emit_t *emit, mp_token_kind_t tok) { mp_uint_t val; if (emit->do_viper_types) { switch (tok) { - case MP_TOKEN_KW_NONE: vtype = VTYPE_PTR_NONE; val = 0; break; - case MP_TOKEN_KW_FALSE: vtype = VTYPE_BOOL; val = 0; break; - case MP_TOKEN_KW_TRUE: vtype = VTYPE_BOOL; val = 1; break; + case MP_TOKEN_KW_NONE: + vtype = VTYPE_PTR_NONE; + val = 0; + break; + case MP_TOKEN_KW_FALSE: + vtype = VTYPE_BOOL; + val = 0; + break; + case MP_TOKEN_KW_TRUE: + vtype = VTYPE_BOOL; + val = 1; + break; default: assert(tok == MP_TOKEN_ELLIPSIS); - vtype = VTYPE_PYOBJ; val = (mp_uint_t)&mp_const_ellipsis_obj; break; + vtype = VTYPE_PYOBJ; + val = (mp_uint_t)&mp_const_ellipsis_obj; + break; } } else { vtype = VTYPE_PYOBJ; switch (tok) { - case MP_TOKEN_KW_NONE: val = (mp_uint_t)mp_const_none; break; - case MP_TOKEN_KW_FALSE: val = (mp_uint_t)mp_const_false; break; - case MP_TOKEN_KW_TRUE: val = (mp_uint_t)mp_const_true; break; + case MP_TOKEN_KW_NONE: + val = (mp_uint_t)mp_const_none; + break; + case MP_TOKEN_KW_FALSE: + val = (mp_uint_t)mp_const_false; + break; + case MP_TOKEN_KW_TRUE: + val = (mp_uint_t)mp_const_true; + break; default: assert(tok == MP_TOKEN_ELLIPSIS); - val = (mp_uint_t)&mp_const_ellipsis_obj; break; + val = (mp_uint_t)&mp_const_ellipsis_obj; + break; } } emit_post_push_imm(emit, vtype, val); @@ -1939,7 +1985,7 @@ STATIC void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { asm_xtensa_setcc_reg_reg_reg(emit->as, cc & ~0x80, REG_RET, reg_rhs, REG_ARG_2); } #else - #error not implemented + #error not implemented #endif emit_post_push_reg(emit, VTYPE_BOOL, REG_RET); } else { diff --git a/py/enum.c b/py/enum.c index 02a85a168c..8dc83a9fba 100644 --- a/py/enum.c +++ b/py/enum.c @@ -29,7 +29,7 @@ mp_obj_t cp_enum_find(const mp_obj_type_t *type, int value) { const mp_obj_dict_t *dict = type->locals_dict; - for (size_t i=0; imap.used; i++) { + for (size_t i = 0; i < dict->map.used; i++) { const cp_enum_obj_t *v = dict->map.table[i].value; if (v->value == value) { return (mp_obj_t)v; @@ -42,11 +42,11 @@ int cp_enum_value(const mp_obj_type_t *type, mp_obj_t *obj) { if (!MP_OBJ_IS_TYPE(obj, type)) { mp_raise_TypeError_varg(translate("Expected a %q"), type->name); } - return ((cp_enum_obj_t*)MP_OBJ_TO_PTR(obj))->value; + return ((cp_enum_obj_t *)MP_OBJ_TO_PTR(obj))->value; } void cp_enum_obj_print_helper(uint16_t module, const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - (void) kind; + (void)kind; cp_enum_obj_t *self = self_in; mp_printf(print, "%q.%q.%q", module, self->base.type->name, self->name); } diff --git a/py/enum.h b/py/enum.h index 708678eb69..286bac098f 100644 --- a/py/enum.h +++ b/py/enum.h @@ -35,27 +35,27 @@ typedef struct { } cp_enum_obj_t; #define MAKE_ENUM_VALUE(type, prefix, name, value) \ - const cp_enum_obj_t prefix ## _ ## name ## _obj = { \ - { &type }, value, MP_QSTR_ ## name, \ + const cp_enum_obj_t prefix##_##name##_obj = { \ + { &type }, value, MP_QSTR_##name, \ } #define MAKE_ENUM_MAP(name) \ - const mp_rom_map_elem_t name ## _locals_table[] = + const mp_rom_map_elem_t name##_locals_table[] = #define MAKE_ENUM_MAP_ENTRY(prefix, name) \ - { MP_ROM_QSTR(MP_QSTR_ ## name), MP_ROM_PTR(&prefix ## _ ## name ## _obj) } + { MP_ROM_QSTR(MP_QSTR_##name), MP_ROM_PTR(&prefix##_##name##_obj) } #define MAKE_PRINTER(module, typename) \ - STATIC void typename ## _ ## print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { \ - cp_enum_obj_print_helper(MP_QSTR_ ## module, print, self_in, kind); \ + STATIC void typename##_##print(const mp_print_t * print, mp_obj_t self_in, mp_print_kind_t kind) { \ + cp_enum_obj_print_helper(MP_QSTR_##module, print, self_in, kind); \ } #define MAKE_ENUM_TYPE(module, type, typename) \ - const mp_obj_type_t typename ## _type = { \ + const mp_obj_type_t typename##_type = { \ { &mp_type_type }, \ - .name = MP_QSTR_ ## type, \ - .print = typename ## _print, \ - .locals_dict = (mp_obj_t)&typename ## _locals_dict, \ + .name = MP_QSTR_##type, \ + .print = typename##_print, \ + .locals_dict = (mp_obj_t)&typename##_locals_dict, \ } diff --git a/py/formatfloat.c b/py/formatfloat.c index 166a98a2e6..f8d06d2d71 100644 --- a/py/formatfloat.c +++ b/py/formatfloat.c @@ -68,11 +68,20 @@ union floatbits { float f; uint32_t u; }; -static inline int fp_signbit(float x) { union floatbits fb = {x}; return fb.u & FLT_SIGN_MASK; } +static inline int fp_signbit(float x) { + union floatbits fb = {x}; + return fb.u & FLT_SIGN_MASK; +} #define fp_isnan(x) isnan(x) #define fp_isinf(x) isinf(x) -static inline int fp_iszero(float x) { union floatbits fb = {x}; return fb.u == 0; } -static inline int fp_isless1(float x) { union floatbits fb = {x}; return fb.u < 0x3f800000; } +static inline int fp_iszero(float x) { + union floatbits fb = {x}; + return fb.u == 0; +} +static inline int fp_isless1(float x) { + union floatbits fb = {x}; + return fb.u < 0x3f800000; +} #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE @@ -282,7 +291,7 @@ int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, ch if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) { prec = buf_remaining - FPMIN_BUF_SIZE; } - if (fmt == 'g'){ + if (fmt == 'g') { // Truncate precision to prevent buffer overflow if (prec + (FPMIN_BUF_SIZE - 1) > buf_remaining) { prec = buf_remaining - (FPMIN_BUF_SIZE - 1); diff --git a/py/frozenmod.c b/py/frozenmod.c index 0e040a44fd..6f8191d311 100644 --- a/py/frozenmod.c +++ b/py/frozenmod.c @@ -157,7 +157,7 @@ int mp_find_frozen_module(const char *str, size_t len, void **data) { #if MICROPY_MODULE_FROZEN_MPY const mp_raw_code_t *rc = mp_find_frozen_mpy(str, len); if (rc != NULL) { - *data = (void*)rc; + *data = (void *)rc; return MP_FROZEN_MPY; } #endif diff --git a/py/frozenmod.h b/py/frozenmod.h index 3ba1b590d7..668b7ac17e 100644 --- a/py/frozenmod.h +++ b/py/frozenmod.h @@ -36,10 +36,10 @@ enum { // Frozen modules are in a pseudo-directory, so sys.path can control how they're found. #define MP_FROZEN_FAKE_DIR ".frozen" -#define MP_FROZEN_FAKE_DIR_LENGTH (sizeof(MP_FROZEN_FAKE_DIR)-1) +#define MP_FROZEN_FAKE_DIR_LENGTH (sizeof(MP_FROZEN_FAKE_DIR) - 1) #define MP_FROZEN_FAKE_DIR_SLASH (MP_FROZEN_FAKE_DIR "/") -#define MP_FROZEN_FAKE_DIR_SLASH_LENGTH (sizeof(MP_FROZEN_FAKE_DIR_SLASH)-1) +#define MP_FROZEN_FAKE_DIR_SLASH_LENGTH (sizeof(MP_FROZEN_FAKE_DIR_SLASH) - 1) // This should match MP_FROZEN_FAKE_DIR. #define MP_FROZEN_FAKE_DIR_QSTR MP_QSTR__dot_frozen diff --git a/py/gc.c b/py/gc.c old mode 100755 new mode 100644 index 2aa2668dc4..cb7e454193 --- a/py/gc.c +++ b/py/gc.c @@ -78,7 +78,7 @@ #define ATB_HEAD_TO_MARK(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] |= (AT_MARK << BLOCK_SHIFT(block)); } while (0) #define ATB_MARK_TO_HEAD(block) do { MP_STATE_MEM(gc_alloc_table_start)[(block) / BLOCKS_PER_ATB] &= (~(AT_TAIL << BLOCK_SHIFT(block))); } while (0) -#define BLOCK_FROM_PTR(ptr) (((byte*)(ptr) - MP_STATE_MEM(gc_pool_start)) / BYTES_PER_BLOCK) +#define BLOCK_FROM_PTR(ptr) (((byte *)(ptr) - MP_STATE_MEM(gc_pool_start)) / BYTES_PER_BLOCK) #define PTR_FROM_BLOCK(block) (((block) * BYTES_PER_BLOCK + (uintptr_t)MP_STATE_MEM(gc_pool_start))) #define ATB_FROM_BLOCK(bl) ((bl) / BLOCKS_PER_ATB) @@ -115,43 +115,43 @@ void __attribute__ ((noinline)) gc_log_change(uint32_t start_block, uint32_t len // TODO waste less memory; currently requires that all entries in alloc_table have a corresponding block in pool void gc_init(void *start, void *end) { // align end pointer on block boundary - end = (void*)((uintptr_t)end & (~(BYTES_PER_BLOCK - 1))); - DEBUG_printf("Initializing GC heap: %p..%p = " UINT_FMT " bytes\n", start, end, (byte*)end - (byte*)start); + end = (void *)((uintptr_t)end & (~(BYTES_PER_BLOCK - 1))); + DEBUG_printf("Initializing GC heap: %p..%p = " UINT_FMT " bytes\n", start, end, (byte *)end - (byte *)start); // calculate parameters for GC (T=total, A=alloc table, F=finaliser table, P=pool; all in bytes): // T = A + F + P // F = A * BLOCKS_PER_ATB / BLOCKS_PER_FTB // P = A * BLOCKS_PER_ATB * BYTES_PER_BLOCK // => T = A * (1 + BLOCKS_PER_ATB / BLOCKS_PER_FTB + BLOCKS_PER_ATB * BYTES_PER_BLOCK) - size_t total_byte_len = (byte*)end - (byte*)start; -#if MICROPY_ENABLE_FINALISER + size_t total_byte_len = (byte *)end - (byte *)start; + #if MICROPY_ENABLE_FINALISER MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len * BITS_PER_BYTE / (BITS_PER_BYTE + BITS_PER_BYTE * BLOCKS_PER_ATB / BLOCKS_PER_FTB + BITS_PER_BYTE * BLOCKS_PER_ATB * BYTES_PER_BLOCK); -#else + #else MP_STATE_MEM(gc_alloc_table_byte_len) = total_byte_len / (1 + BITS_PER_BYTE / 2 * BYTES_PER_BLOCK); -#endif + #endif - MP_STATE_MEM(gc_alloc_table_start) = (byte*)start; + MP_STATE_MEM(gc_alloc_table_start) = (byte *)start; -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER size_t gc_finaliser_table_byte_len = (MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB + BLOCKS_PER_FTB - 1) / BLOCKS_PER_FTB; MP_STATE_MEM(gc_finaliser_table_start) = MP_STATE_MEM(gc_alloc_table_start) + MP_STATE_MEM(gc_alloc_table_byte_len); -#endif + #endif size_t gc_pool_block_len = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; - MP_STATE_MEM(gc_pool_start) = (byte*)end - gc_pool_block_len * BYTES_PER_BLOCK; + MP_STATE_MEM(gc_pool_start) = (byte *)end - gc_pool_block_len * BYTES_PER_BLOCK; MP_STATE_MEM(gc_pool_end) = end; -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER assert(MP_STATE_MEM(gc_pool_start) >= MP_STATE_MEM(gc_finaliser_table_start) + gc_finaliser_table_byte_len); -#endif + #endif // clear ATBs memset(MP_STATE_MEM(gc_alloc_table_start), 0, MP_STATE_MEM(gc_alloc_table_byte_len)); -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER // clear FTBs memset(MP_STATE_MEM(gc_finaliser_table_start), 0, gc_finaliser_table_byte_len); -#endif + #endif // Set first free ATB index to the start of the heap. for (size_t i = 0; i < MICROPY_ATB_INDICES; i++) { @@ -163,7 +163,7 @@ void gc_init(void *start, void *end) { // Set the lowest long lived ptr to the end of the heap to start. This will be lowered as long // lived objects are allocated. - MP_STATE_MEM(gc_lowest_long_lived_ptr) = (void*) PTR_FROM_BLOCK(MP_STATE_MEM(gc_alloc_table_byte_len * BLOCKS_PER_ATB)); + MP_STATE_MEM(gc_lowest_long_lived_ptr) = (void *)PTR_FROM_BLOCK(MP_STATE_MEM(gc_alloc_table_byte_len * BLOCKS_PER_ATB)); // unlock the GC MP_STATE_MEM(gc_lock_depth) = 0; @@ -185,9 +185,9 @@ void gc_init(void *start, void *end) { DEBUG_printf("GC layout:\n"); DEBUG_printf(" alloc table at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_alloc_table_start), MP_STATE_MEM(gc_alloc_table_byte_len), MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB); -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER DEBUG_printf(" finaliser table at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_finaliser_table_start), gc_finaliser_table_byte_len, gc_finaliser_table_byte_len * BLOCKS_PER_FTB); -#endif + #endif DEBUG_printf(" pool at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", MP_STATE_MEM(gc_pool_start), gc_pool_block_len * BYTES_PER_BLOCK, gc_pool_block_len); } @@ -237,8 +237,8 @@ STATIC void gc_mark_subtree(size_t block) { } while (ATB_GET_KIND(block + n_blocks) == AT_TAIL); // check this block's children - void **ptrs = (void**)PTR_FROM_BLOCK(block); - for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void*); i > 0; i--, ptrs++) { + void **ptrs = (void **)PTR_FROM_BLOCK(block); + for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void *); i > 0; i--, ptrs++) { void *ptr = *ptrs; if (VERIFY_PTR(ptr)) { // Mark and push this pointer @@ -289,9 +289,9 @@ STATIC void gc_sweep(void) { for (size_t block = 0; block < MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; block++) { switch (ATB_GET_KIND(block)) { case AT_HEAD: -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER if (FTB_GET(block)) { - mp_obj_base_t *obj = (mp_obj_base_t*)PTR_FROM_BLOCK(block); + mp_obj_base_t *obj = (mp_obj_base_t *)PTR_FROM_BLOCK(block); if (obj->type != NULL) { // if the object has a type then see if it has a __del__ method mp_obj_t dest[2]; @@ -310,11 +310,11 @@ STATIC void gc_sweep(void) { // clear finaliser flag FTB_CLEAR(block); } -#endif + #endif free_tail = 1; ATB_ANY_TO_FREE(block); #if CLEAR_ON_SWEEP - memset((void*)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK); + memset((void *)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK); #endif DEBUG_printf("gc_sweep(%x)\n", PTR_FROM_BLOCK(block)); @@ -330,7 +330,7 @@ STATIC void gc_sweep(void) { if (free_tail) { ATB_ANY_TO_FREE(block); #if CLEAR_ON_SWEEP - memset((void*)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK); + memset((void *)PTR_FROM_BLOCK(block), 0, BYTES_PER_BLOCK); #endif } break; @@ -344,7 +344,7 @@ STATIC void gc_sweep(void) { } // Mark can handle NULL pointers because it verifies the pointer is within the heap bounds. -STATIC void gc_mark(void* ptr) { +STATIC void gc_mark(void *ptr) { if (VERIFY_PTR(ptr)) { size_t block = BLOCK_FROM_PTR(ptr); if (ATB_GET_KIND(block) == AT_HEAD) { @@ -367,17 +367,17 @@ void gc_collect_start(void) { // Trace root pointers. This relies on the root pointers being organised // correctly in the mp_state_ctx structure. We scan nlr_top, dict_locals, // dict_globals, then the root pointer section of mp_state_vm. - void **ptrs = (void**)(void*)&mp_state_ctx; + void **ptrs = (void **)(void *)&mp_state_ctx; size_t root_start = offsetof(mp_state_ctx_t, thread.dict_locals); size_t root_end = offsetof(mp_state_ctx_t, vm.qstr_last_chunk); - gc_collect_root(ptrs + root_start / sizeof(void*), (root_end - root_start) / sizeof(void*)); + gc_collect_root(ptrs + root_start / sizeof(void *), (root_end - root_start) / sizeof(void *)); gc_mark(MP_STATE_MEM(permanent_pointers)); #if MICROPY_ENABLE_PYSTACK // Trace root pointers from the Python stack. - ptrs = (void**)(void*)MP_STATE_THREAD(pystack_start); - gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void*)); + ptrs = (void **)(void *)MP_STATE_THREAD(pystack_start); + gc_collect_root(ptrs, (MP_STATE_THREAD(pystack_cur) - MP_STATE_THREAD(pystack_start)) / sizeof(void *)); #endif } @@ -549,7 +549,7 @@ void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived) { if (!collected) { size_t block = i * BLOCKS_PER_ATB + j; if ((direction == 1 && block >= crossover_block) || - (direction == -1 && block < crossover_block)) { + (direction == -1 && block < crossover_block)) { keep_looking = false; } } @@ -612,7 +612,7 @@ void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived) { // get pointer to first block // we must create this pointer before unlocking the GC so a collection can find it - void *ret_ptr = (void*)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK); + void *ret_ptr = (void *)(MP_STATE_MEM(gc_pool_start) + start_block * BYTES_PER_BLOCK); DEBUG_printf("gc_alloc(%p)\n", ret_ptr); // If the allocation was long live then update the lowest value. Its used to trigger early @@ -630,20 +630,20 @@ void *gc_alloc(size_t n_bytes, bool has_finaliser, bool long_lived) { #if MICROPY_GC_CONSERVATIVE_CLEAR // be conservative and zero out all the newly allocated blocks - memset((byte*)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK); + memset((byte *)ret_ptr, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK); #else // zero out the additional bytes of the newly allocated blocks // This is needed because the blocks may have previously held pointers // to the heap and will not be set to something else if the caller // doesn't actually use the entire block. As such they will continue // to point to the heap and may prevent other blocks from being reclaimed. - memset((byte*)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes); + memset((byte *)ret_ptr + n_bytes, 0, (end_block - start_block + 1) * BYTES_PER_BLOCK - n_bytes); #endif #if MICROPY_ENABLE_FINALISER if (has_finaliser) { // clear type pointer in case it is never set - ((mp_obj_base_t*)ret_ptr)->type = NULL; + ((mp_obj_base_t *)ret_ptr)->type = NULL; // set mp_obj flag only if it has a finaliser GC_ENTER(); FTB_SET(start_block); @@ -754,7 +754,7 @@ size_t gc_nbytes(const void *ptr) { } bool gc_has_finaliser(const void *ptr) { -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER GC_ENTER(); if (VERIFY_PTR(ptr)) { bool has_finaliser = FTB_GET(BLOCK_FROM_PTR(ptr)); @@ -764,9 +764,9 @@ bool gc_has_finaliser(const void *ptr) { // invalid pointer GC_EXIT(); -#else - (void) ptr; -#endif + #else + (void)ptr; + #endif return false; } @@ -782,7 +782,7 @@ void *gc_make_long_lived(void *old_ptr) { bool has_finaliser = gc_has_finaliser(old_ptr); // Try and find a new area in the long lived section to copy the memory to. - void* new_ptr = gc_alloc(n_bytes, has_finaliser, true); + void *new_ptr = gc_alloc(n_bytes, has_finaliser, true); if (new_ptr == NULL) { return old_ptr; } else if (old_ptr > new_ptr) { @@ -808,11 +808,11 @@ void *gc_realloc(void *ptr, mp_uint_t n_bytes) { if (ptr == NULL) { has_finaliser = false; } else { -#if MICROPY_ENABLE_FINALISER + #if MICROPY_ENABLE_FINALISER has_finaliser = FTB_GET(BLOCK_FROM_PTR((mp_uint_t)ptr)); -#else + #else has_finaliser = false; -#endif + #endif } void *ptr2 = gc_alloc(n_bytes, has_finaliser); if (ptr2 == NULL) { @@ -861,7 +861,7 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { // free blocks to satisfy the realloc. Note that we need to compute the // total size of the existing memory chunk so we can correctly and // efficiently shrink it (see below for shrinking code). - size_t n_free = 0; + size_t n_free = 0; size_t n_blocks = 1; // counting HEAD block size_t max_block = MP_STATE_MEM(gc_alloc_table_byte_len) * BLOCKS_PER_ATB; for (size_t bl = block + n_blocks; bl < max_block; bl++) { @@ -933,10 +933,10 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { #if MICROPY_GC_CONSERVATIVE_CLEAR // be conservative and zero out all the newly allocated blocks - memset((byte*)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK); + memset((byte *)ptr_in + n_blocks * BYTES_PER_BLOCK, 0, (new_blocks - n_blocks) * BYTES_PER_BLOCK); #else // zero out the additional bytes of the newly allocated blocks (see comment above in gc_alloc) - memset((byte*)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes); + memset((byte *)ptr_in + n_bytes, 0, new_blocks * BYTES_PER_BLOCK - n_bytes); #endif #if EXTENSIVE_HEAP_PROFILING @@ -989,9 +989,9 @@ bool gc_never_free(void *ptr) { } // Pointers are stored in a linked list where each block is BYTES_PER_BLOCK long and the first // pointer is the next block of pointers. - void ** current_reference_block = MP_STATE_MEM(permanent_pointers); + void **current_reference_block = MP_STATE_MEM(permanent_pointers); while (current_reference_block != NULL) { - for (size_t i = 1; i < BYTES_PER_BLOCK / sizeof(void*); i++) { + for (size_t i = 1; i < BYTES_PER_BLOCK / sizeof(void *); i++) { if (current_reference_block[i] == NULL) { current_reference_block[i] = ptr; return true; @@ -999,7 +999,7 @@ bool gc_never_free(void *ptr) { } current_reference_block = current_reference_block[0]; } - void** next_block = gc_alloc(BYTES_PER_BLOCK, false, true); + void **next_block = gc_alloc(BYTES_PER_BLOCK, false, true); if (next_block == NULL) { return false; } @@ -1018,7 +1018,7 @@ void gc_dump_info(void) { mp_printf(&mp_plat_print, "GC: total: %u, used: %u, free: %u\n", (uint)info.total, (uint)info.used, (uint)info.free); mp_printf(&mp_plat_print, " No. of 1-blocks: %u, 2-blocks: %u, max blk sz: %u, max free sz: %u\n", - (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free); + (uint)info.num_1block, (uint)info.num_2block, (uint)info.max_block, (uint)info.max_free); } void gc_dump_alloc_table(void) { @@ -1050,12 +1050,14 @@ void gc_dump_alloc_table(void) { } // print header for new line of blocks // (the cast to uint32_t is for 16-bit ports) - //mp_printf(&mp_plat_print, "\n%05x: ", (uint)(PTR_FROM_BLOCK(bl) & (uint32_t)0xfffff)); + // mp_printf(&mp_plat_print, "\n%05x: ", (uint)(PTR_FROM_BLOCK(bl) & (uint32_t)0xfffff)); mp_printf(&mp_plat_print, "\n%05x: ", (uint)((bl * BYTES_PER_BLOCK) & (uint32_t)0xfffff)); } int c = ' '; switch (ATB_GET_KIND(bl)) { - case AT_FREE: c = '.'; break; + case AT_FREE: + c = '.'; + break; /* this prints out if the object is reachable from BSS or STACK (for unix only) case AT_HEAD: { c = 'h'; @@ -1084,38 +1086,51 @@ void gc_dump_alloc_table(void) { */ /* this prints the uPy object type of the head block */ case AT_HEAD: { -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wcast-align" - void **ptr = (void**)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK); -#pragma GCC diagnostic pop - if (*ptr == &mp_type_tuple) { c = 'T'; } - else if (*ptr == &mp_type_list) { c = 'L'; } - else if (*ptr == &mp_type_dict) { c = 'D'; } - else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) { c = 'S'; } + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + void **ptr = (void **)(MP_STATE_MEM(gc_pool_start) + bl * BYTES_PER_BLOCK); + #pragma GCC diagnostic pop + if (*ptr == &mp_type_tuple) { + c = 'T'; + } else if (*ptr == &mp_type_list) { + c = 'L'; + } else if (*ptr == &mp_type_dict) { + c = 'D'; + } else if (*ptr == &mp_type_str || *ptr == &mp_type_bytes) { + c = 'S'; + } #if MICROPY_PY_BUILTINS_BYTEARRAY - else if (*ptr == &mp_type_bytearray) { c = 'A'; } + else if (*ptr == &mp_type_bytearray) { + c = 'A'; + } #endif #if MICROPY_PY_ARRAY - else if (*ptr == &mp_type_array) { c = 'A'; } + else if (*ptr == &mp_type_array) { + c = 'A'; + } #endif #if MICROPY_PY_BUILTINS_FLOAT - else if (*ptr == &mp_type_float) { c = 'F'; } + else if (*ptr == &mp_type_float) { + c = 'F'; + } #endif - else if (*ptr == &mp_type_fun_bc) { c = 'B'; } - else if (*ptr == &mp_type_module) { c = 'M'; } - else { + else if (*ptr == &mp_type_fun_bc) { + c = 'B'; + } else if (*ptr == &mp_type_module) { + c = 'M'; + } else { c = 'h'; #if 0 // This code prints "Q" for qstr-pool data, and "q" for qstr-str // data. It can be useful to see how qstrs are being allocated, // but is disabled by default because it is very slow. for (qstr_pool_t *pool = MP_STATE_VM(last_pool); c == 'h' && pool != NULL; pool = pool->prev) { - if ((qstr_pool_t*)ptr == pool) { + if ((qstr_pool_t *)ptr == pool) { c = 'Q'; break; } for (const byte **q = pool->qstrs, **q_top = pool->qstrs + pool->len; q < q_top; q++) { - if ((const byte*)ptr == *q) { + if ((const byte *)ptr == *q) { c = 'q'; break; } @@ -1125,8 +1140,12 @@ void gc_dump_alloc_table(void) { } break; } - case AT_TAIL: c = '='; break; - case AT_MARK: c = 'm'; break; + case AT_TAIL: + c = '='; + break; + case AT_MARK: + c = 'm'; + break; } mp_printf(&mp_plat_print, "%c", c); } @@ -1151,11 +1170,11 @@ void gc_test(void) { p2[1] = p; ptrs[0] = p2; } - for (int i = 0; i < 25; i+=2) { + for (int i = 0; i < 25; i += 2) { mp_uint_t *p = gc_alloc(i, false); printf("p=%p\n", p); if (i & 3) { - //ptrs[i] = p; + // ptrs[i] = p; } } @@ -1163,7 +1182,7 @@ void gc_test(void) { gc_dump_alloc_table(); printf("Starting GC...\n"); gc_collect_start(); - gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void*)); + gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void *)); gc_collect_end(); printf("After GC:\n"); gc_dump_alloc_table(); diff --git a/py/gc.h b/py/gc.h index b7c2889d5c..ddbaeb40a6 100644 --- a/py/gc.h +++ b/py/gc.h @@ -37,9 +37,9 @@ // ptr should be of type void* #define VERIFY_PTR(ptr) ( \ - ((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) == 0 /* must be aligned on a block */ \ - && ptr >= (void*)MP_STATE_MEM(gc_pool_start) /* must be above start of pool */ \ - && ptr < (void*)MP_STATE_MEM(gc_pool_end) /* must be below end of pool */ \ + ((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) == 0 /* must be aligned on a block */ \ + && ptr >= (void *)MP_STATE_MEM(gc_pool_start) /* must be above start of pool */ \ + && ptr < (void *)MP_STATE_MEM(gc_pool_end) /* must be below end of pool */ \ ) void gc_init(void *start, void *end); diff --git a/py/gc_long_lived.c b/py/gc_long_lived.c old mode 100755 new mode 100644 index 0e94390e9d..8ee8a4a4e1 --- a/py/gc_long_lived.c +++ b/py/gc_long_lived.c @@ -36,7 +36,7 @@ mp_obj_fun_bc_t *make_fun_bc_long_lived(mp_obj_fun_bc_t *fun_bc, uint8_t max_dep if (fun_bc == NULL || fun_bc == mp_const_none || max_depth == 0) { return fun_bc; } - fun_bc->bytecode = gc_make_long_lived((byte*) fun_bc->bytecode); + fun_bc->bytecode = gc_make_long_lived((byte *)fun_bc->bytecode); fun_bc->globals = make_dict_long_lived(fun_bc->globals, max_depth - 1); for (uint32_t i = 0; i < gc_nbytes(fun_bc->const_table) / sizeof(mp_obj_t); i++) { // Skip things that aren't allocated on the heap (and hence have zero bytes.) @@ -44,18 +44,18 @@ mp_obj_fun_bc_t *make_fun_bc_long_lived(mp_obj_fun_bc_t *fun_bc, uint8_t max_dep continue; } // Try to detect raw code. - mp_raw_code_t* raw_code = MP_OBJ_TO_PTR(fun_bc->const_table[i]); + mp_raw_code_t *raw_code = MP_OBJ_TO_PTR(fun_bc->const_table[i]); if (raw_code->kind == MP_CODE_BYTECODE) { - raw_code->data.u_byte.bytecode = gc_make_long_lived((byte*) raw_code->data.u_byte.bytecode); - raw_code->data.u_byte.const_table = gc_make_long_lived((byte*) raw_code->data.u_byte.const_table); + raw_code->data.u_byte.bytecode = gc_make_long_lived((byte *)raw_code->data.u_byte.bytecode); + raw_code->data.u_byte.const_table = gc_make_long_lived((byte *)raw_code->data.u_byte.const_table); } - ((mp_uint_t *) fun_bc->const_table)[i] = (mp_uint_t) make_obj_long_lived( - (mp_obj_t) fun_bc->const_table[i], max_depth - 1); + ((mp_uint_t *)fun_bc->const_table)[i] = (mp_uint_t)make_obj_long_lived( + (mp_obj_t)fun_bc->const_table[i], max_depth - 1); } - fun_bc->const_table = gc_make_long_lived((mp_uint_t*) fun_bc->const_table); + fun_bc->const_table = gc_make_long_lived((mp_uint_t *)fun_bc->const_table); // extra_args stores keyword only argument default values. - size_t words = gc_nbytes(fun_bc) / sizeof(mp_uint_t*); + size_t words = gc_nbytes(fun_bc) / sizeof(mp_uint_t *); // Functions (mp_obj_fun_bc_t) have four pointers (base, globals, bytecode and const_table) // before the variable length extra_args so remove them from the length. for (size_t i = 0; i < words - 4; i++) { @@ -79,9 +79,9 @@ mp_obj_property_t *make_property_long_lived(mp_obj_property_t *prop, uint8_t max if (max_depth == 0) { return prop; } - prop->proxy[0] = make_obj_long_lived((mp_obj_fun_bc_t*) prop->proxy[0], max_depth - 1); - prop->proxy[1] = make_obj_long_lived((mp_obj_fun_bc_t*) prop->proxy[1], max_depth - 1); - prop->proxy[2] = make_obj_long_lived((mp_obj_fun_bc_t*) prop->proxy[2], max_depth - 1); + prop->proxy[0] = make_obj_long_lived((mp_obj_fun_bc_t *)prop->proxy[0], max_depth - 1); + prop->proxy[1] = make_obj_long_lived((mp_obj_fun_bc_t *)prop->proxy[1], max_depth - 1); + prop->proxy[2] = make_obj_long_lived((mp_obj_fun_bc_t *)prop->proxy[2], max_depth - 1); return gc_make_long_lived(prop); } @@ -115,11 +115,11 @@ mp_obj_dict_t *make_dict_long_lived(mp_obj_dict_t *dict, uint8_t max_depth) { } mp_obj_str_t *make_str_long_lived(mp_obj_str_t *str) { - str->data = gc_make_long_lived((byte *) str->data); + str->data = gc_make_long_lived((byte *)str->data); return gc_make_long_lived(str); } -mp_obj_t make_obj_long_lived(mp_obj_t obj, uint8_t max_depth){ +mp_obj_t make_obj_long_lived(mp_obj_t obj, uint8_t max_depth) { #ifndef MICROPY_ENABLE_GC return obj; #endif diff --git a/py/genlast.py b/py/genlast.py index 5b195d23e4..a3ac87128f 100644 --- a/py/genlast.py +++ b/py/genlast.py @@ -12,8 +12,9 @@ import subprocess from makeqstrdefs import qstr_unescape, QSTRING_BLACK_LIST re_line = re.compile(r"#[line]*\s(\d+)\s\"([^\"]+)\"", re.DOTALL) -re_qstr = re.compile(r'MP_QSTR_[_a-zA-Z0-9]+', re.DOTALL) -re_translate = re.compile(r'translate\(\"((?:(?=(\\?))\2.)*?)\"\)', re.DOTALL) +re_qstr = re.compile(r"MP_QSTR_[_a-zA-Z0-9]+", re.DOTALL) +re_translate = re.compile(r"translate\(\"((?:(?=(\\?))\2.)*?)\"\)", re.DOTALL) + def write_out(fname, output_dir, output): if output: @@ -22,13 +23,14 @@ def write_out(fname, output_dir, output): with open(output_dir + "/" + fname + ".qstr", "w") as f: f.write("\n".join(output) + "\n") + def process_file(fname, output_dir, content): - content = content.decode('utf-8', errors='ignore') + content = content.decode("utf-8", errors="ignore") output = [] for match in re_qstr.findall(content): - name = match.replace('MP_QSTR_', '') + name = match.replace("MP_QSTR_", "") if name not in QSTRING_BLACK_LIST: - output.append('Q(' + qstr_unescape(name) + ')') + output.append("Q(" + qstr_unescape(name) + ")") for match in re_translate.findall(content): output.append('TRANSLATE("' + match[0] + '")') @@ -36,9 +38,10 @@ def process_file(fname, output_dir, content): def checkoutput1(args): - info = subprocess.run(args, check=True, stdout=subprocess.PIPE, input='') + info = subprocess.run(args, check=True, stdout=subprocess.PIPE, input="") return info.stdout + def preprocess(command, output_dir, fn): try: output = checkoutput1(command + [fn]) @@ -46,27 +49,28 @@ def preprocess(command, output_dir, fn): except Exception as e: print(e, file=sys.stderr) + def maybe_preprocess(command, output_dir, fn): # Preprocess the source file if it contains "MP_QSTR", "translate", # or if it uses enum.h (which generates "MP_QSTR" strings. if subprocess.call(["grep", "-lqE", r"(MP_QSTR|translate|enum\.h)", fn]) == 0: preprocess(command, output_dir, fn) -if __name__ == '__main__': +if __name__ == "__main__": - idx1 = sys.argv.index('--') - idx2 = sys.argv.index('--', idx1+1) + idx1 = sys.argv.index("--") + idx2 = sys.argv.index("--", idx1 + 1) output_dir = sys.argv[1] check = sys.argv[2:idx1] - always = sys.argv[idx1+1:idx2] - command = sys.argv[idx2+1:] + always = sys.argv[idx1 + 1 : idx2] + command = sys.argv[idx2 + 1 :] if not os.path.isdir(output_dir): os.makedirs(output_dir) # Mac and Windows use 'spawn'. Uncomment this during testing to catch spawn-specific problems on Linux. - #multiprocessing.set_start_method("spawn") + # multiprocessing.set_start_method("spawn") executor = ProcessPoolExecutor(max_workers=multiprocessing.cpu_count() + 1) executor.map(maybe_preprocess, itertools.repeat(command), itertools.repeat(output_dir), check) executor.map(preprocess, itertools.repeat(command), itertools.repeat(output_dir), always) diff --git a/py/lexer.c b/py/lexer.c index de121f87a2..834a8d62e3 100644 --- a/py/lexer.c +++ b/py/lexer.c @@ -113,15 +113,15 @@ STATIC bool is_following_odigit(mp_lexer_t *lex) { STATIC bool is_string_or_bytes(mp_lexer_t *lex) { return is_char_or(lex, '\'', '\"') -#if MICROPY_COMP_FSTRING_LITERAL - || (is_char_or4(lex, 'r', 'u', 'b', 'f') && is_char_following_or(lex, '\'', '\"')) - || ((is_char_and(lex, 'r', 'f') || is_char_and(lex, 'f', 'r')) - && is_char_following_following_or(lex, '\'', '\"')) -#else - || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"')) -#endif - || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r')) - && is_char_following_following_or(lex, '\'', '\"')); + #if MICROPY_COMP_FSTRING_LITERAL + || (is_char_or4(lex, 'r', 'u', 'b', 'f') && is_char_following_or(lex, '\'', '\"')) + || ((is_char_and(lex, 'r', 'f') || is_char_and(lex, 'f', 'r')) + && is_char_following_following_or(lex, '\'', '\"')) + #else + || (is_char_or3(lex, 'r', 'u', 'b') && is_char_following_or(lex, '\'', '\"')) + #endif + || ((is_char_and(lex, 'r', 'b') || is_char_and(lex, 'b', 'r')) + && is_char_following_following_or(lex, '\'', '\"')); } // to easily parse utf-8 identifiers we allow any raw byte with high bit set @@ -174,7 +174,7 @@ STATIC void next_char(mp_lexer_t *lex) { lex->chr0 = lex->chr1; lex->chr1 = lex->chr2; -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL if (lex->vstr_postfix_processing) { if (lex->vstr_postfix_idx == lex->vstr_postfix.len) { lex->chr2 = '\0'; @@ -182,7 +182,7 @@ STATIC void next_char(mp_lexer_t *lex) { lex->chr2 = lex->vstr_postfix.buf[lex->vstr_postfix_idx++]; } } else -#endif + #endif { lex->chr2 = lex->reader.readbyte(lex->reader.data); } @@ -201,12 +201,12 @@ STATIC void next_char(mp_lexer_t *lex) { lex->chr2 = '\n'; } -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL if (lex->vstr_postfix_processing && lex->chr0 == '\0') { lex->vstr_postfix_processing = false; swap_char_banks(lex); } -#endif + #endif } STATIC void indent_push(mp_lexer_t *lex, size_t indent) { @@ -347,10 +347,10 @@ STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) } size_t n_closing = 0; -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL bool in_expression = false; bool expression_eat = true; -#endif + #endif while (!is_end(lex) && (num_quotes > 1 || !is_char(lex, '\n')) && n_closing < num_quotes) { if (is_char(lex, quote_char)) { @@ -358,7 +358,7 @@ STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) vstr_add_char(&lex->vstr, CUR_CHAR(lex)); } else { n_closing = 0; -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL if (is_fstring && is_char(lex, '{')) { vstr_add_char(&lex->vstr, CUR_CHAR(lex)); in_expression = !in_expression; @@ -406,7 +406,7 @@ STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) next_char(lex); continue; } -#endif + #endif if (is_char(lex, '\\')) { next_char(lex); @@ -419,17 +419,36 @@ STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) switch (c) { // note: "c" can never be MP_LEXER_EOF because next_char // always inserts a newline at the end of the input stream - case '\n': c = MP_LEXER_EOF; break; // backslash escape the newline, just ignore it - case '\\': break; - case '\'': break; - case '"': break; - case 'a': c = 0x07; break; - case 'b': c = 0x08; break; - case 't': c = 0x09; break; - case 'n': c = 0x0a; break; - case 'v': c = 0x0b; break; - case 'f': c = 0x0c; break; - case 'r': c = 0x0d; break; + case '\n': + c = MP_LEXER_EOF; + break; // backslash escape the newline, just ignore it + case '\\': + break; + case '\'': + break; + case '"': + break; + case 'a': + c = 0x07; + break; + case 'b': + c = 0x08; + break; + case 't': + c = 0x09; + break; + case 'n': + c = 0x0a; + break; + case 'v': + c = 0x0b; + break; + case 'f': + c = 0x0c; + break; + case 'r': + c = 0x0d; + break; case 'u': case 'U': if (lex->tok_kind == MP_TOKEN_BYTES) { @@ -437,9 +456,8 @@ STATIC void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) vstr_add_char(&lex->vstr, '\\'); break; } - // Otherwise fall through. - case 'x': - { + // Otherwise fall through. + case 'x': { mp_uint_t num = 0; if (!get_hex(lex, (c == 'x' ? 2 : c == 'u' ? 4 : 8), &num)) { // not enough hex chars for escape sequence @@ -542,14 +560,14 @@ STATIC bool skip_whitespace(mp_lexer_t *lex, bool stop_at_newline) { } void mp_lexer_to_next(mp_lexer_t *lex) { -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL if (lex->vstr_postfix.len && !lex->vstr_postfix_processing) { // end format call injection vstr_add_char(&lex->vstr_postfix, ')'); lex->vstr_postfix_processing = true; swap_char_banks(lex); } -#endif + #endif // start new token text vstr_reset(&lex->vstr); @@ -602,19 +620,19 @@ void mp_lexer_to_next(mp_lexer_t *lex) { // MP_TOKEN_END is used to indicate that this is the first string token lex->tok_kind = MP_TOKEN_END; -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL bool saw_normal = false, saw_fstring = false; -#endif + #endif // Loop to accumulate string/bytes literals do { // parse type codes bool is_raw = false; -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL bool is_fstring = false; -#else + #else const bool is_fstring = false; -#endif + #endif mp_token_kind_t kind = MP_TOKEN_STRING; int n_char = 0; if (is_char(lex, 'u')) { @@ -633,7 +651,7 @@ void mp_lexer_to_next(mp_lexer_t *lex) { kind = MP_TOKEN_BYTES; n_char = 2; } -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL if (is_char_following(lex, 'f')) { lex->tok_kind = MP_TOKEN_FSTRING_RAW; break; @@ -645,10 +663,10 @@ void mp_lexer_to_next(mp_lexer_t *lex) { } n_char = 1; is_fstring = true; -#endif + #endif } -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL if (is_fstring) { saw_fstring = true; } else { @@ -659,7 +677,7 @@ void mp_lexer_to_next(mp_lexer_t *lex) { // Can't concatenate f-string with normal string break; } -#endif + #endif // Set or check token kind if (lex->tok_kind == MP_TOKEN_END) { @@ -837,9 +855,9 @@ mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader) { lex->num_indent_level = 1; lex->indent_level = m_new(uint16_t, lex->alloc_indent_level); vstr_init(&lex->vstr, 32); -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL vstr_init(&lex->vstr_postfix, 0); -#endif + #endif // store sentinel for first indentation level lex->indent_level[0] = 0; @@ -865,7 +883,7 @@ mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader) { mp_lexer_t *mp_lexer_new_from_str_len(qstr src_name, const char *str, size_t len, size_t free_len) { mp_reader_t reader; - mp_reader_new_mem(&reader, (const byte*)str, len, free_len); + mp_reader_new_mem(&reader, (const byte *)str, len, free_len); return mp_lexer_new(src_name, reader); } diff --git a/py/lexer.h b/py/lexer.h index 74195fe030..dab34294a4 100644 --- a/py/lexer.h +++ b/py/lexer.h @@ -44,14 +44,14 @@ typedef enum _mp_token_kind_t { MP_TOKEN_INVALID, MP_TOKEN_DEDENT_MISMATCH, MP_TOKEN_LONELY_STRING_OPEN, -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL MP_TOKEN_FSTRING_BACKSLASH, MP_TOKEN_FSTRING_COMMENT, MP_TOKEN_FSTRING_UNCLOSED, MP_TOKEN_FSTRING_UNOPENED, MP_TOKEN_FSTRING_EMPTY_EXP, MP_TOKEN_FSTRING_RAW, -#endif + #endif MP_TOKEN_NEWLINE, MP_TOKEN_INDENT, @@ -158,9 +158,9 @@ typedef struct _mp_lexer_t { mp_reader_t reader; // stream source unichar chr0, chr1, chr2; // current cached characters from source -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL unichar chr3, chr4, chr5; // current cached characters from alt source -#endif + #endif size_t line; // current source line size_t column; // current source column @@ -176,11 +176,11 @@ typedef struct _mp_lexer_t { size_t tok_column; // token source column mp_token_kind_t tok_kind; // token kind vstr_t vstr; // token data -#if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_COMP_FSTRING_LITERAL vstr_t vstr_postfix; // postfix to apply to string bool vstr_postfix_processing; uint16_t vstr_postfix_idx; -#endif + #endif } mp_lexer_t; mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader); @@ -193,7 +193,7 @@ void mp_lexer_to_next(mp_lexer_t *lex); // platform specific import function; must be implemented for a specific port // TODO tidy up, rename, or put elsewhere -//mp_lexer_t *mp_import_open_file(qstr mod_name); +// mp_lexer_t *mp_import_open_file(qstr mod_name); typedef enum { MP_IMPORT_STAT_NO_EXIST, diff --git a/py/makemoduledefs.py b/py/makemoduledefs.py index 18d327f002..7745607131 100644 --- a/py/makemoduledefs.py +++ b/py/makemoduledefs.py @@ -12,14 +12,11 @@ import os import argparse -pattern = re.compile( - r"[\n;]\s*MP_REGISTER_MODULE\((.*?),\s*(.*?),\s*(.*?)\);", - flags=re.DOTALL -) +pattern = re.compile(r"[\n;]\s*MP_REGISTER_MODULE\((.*?),\s*(.*?),\s*(.*?)\);", flags=re.DOTALL) def find_c_file(obj_file, vpath): - """ Search vpaths for the c file that matches the provided object_file. + """Search vpaths for the c file that matches the provided object_file. :param str obj_file: object file to find the matching c file for :param List[str] vpath: List of base paths, similar to gcc vpath @@ -27,7 +24,7 @@ def find_c_file(obj_file, vpath): """ c_file = None relative_c_file = os.path.splitext(obj_file)[0] + ".c" - relative_c_file = relative_c_file.lstrip('/\\') + relative_c_file = relative_c_file.lstrip("/\\") for p in vpath: possible_c_file = os.path.join(p, relative_c_file) if os.path.exists(possible_c_file): @@ -38,7 +35,7 @@ def find_c_file(obj_file, vpath): def find_module_registrations(c_file): - """ Find any MP_REGISTER_MODULE definitions in the provided c file. + """Find any MP_REGISTER_MODULE definitions in the provided c file. :param str c_file: path to c file to check :return: List[(module_name, obj_module, enabled_define)] @@ -54,7 +51,7 @@ def find_module_registrations(c_file): def generate_module_table_header(modules): - """ Generate header with module table entries for builtin modules. + """Generate header with module table entries for builtin modules. :param List[(module_name, obj_module, enabled_define)] modules: module defs :return: None @@ -66,15 +63,20 @@ def generate_module_table_header(modules): for module_name, obj_module, enabled_define in modules: mod_def = "MODULE_DEF_{}".format(module_name.upper()) mod_defs.append(mod_def) - print(( - "#if ({enabled_define})\n" - " extern const struct _mp_obj_module_t {obj_module};\n" - " #define {mod_def} {{ MP_ROM_QSTR({module_name}), MP_ROM_PTR(&{obj_module}) }},\n" - "#else\n" - " #define {mod_def}\n" - "#endif\n" - ).format(module_name=module_name, obj_module=obj_module, - enabled_define=enabled_define, mod_def=mod_def) + print( + ( + "#if ({enabled_define})\n" + " extern const struct _mp_obj_module_t {obj_module};\n" + " #define {mod_def} {{ MP_ROM_QSTR({module_name}), MP_ROM_PTR(&{obj_module}) }},\n" + "#else\n" + " #define {mod_def}\n" + "#endif\n" + ).format( + module_name=module_name, + obj_module=obj_module, + enabled_define=enabled_define, + mod_def=mod_def, + ) ) print("\n#define MICROPY_REGISTERED_MODULES \\") @@ -87,13 +89,13 @@ def generate_module_table_header(modules): def main(): parser = argparse.ArgumentParser() - parser.add_argument("--vpath", default=".", - help="comma separated list of folders to search for c files in") - parser.add_argument("files", nargs="*", - help="list of c files to search") + parser.add_argument( + "--vpath", default=".", help="comma separated list of folders to search for c files in" + ) + parser.add_argument("files", nargs="*", help="list of c files to search") args = parser.parse_args() - vpath = [p.strip() for p in args.vpath.split(',')] + vpath = [p.strip() for p in args.vpath.split(",")] modules = set() for obj_file in args.files: @@ -103,5 +105,5 @@ def main(): generate_module_table_header(sorted(modules)) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/py/makeqstrdata.py b/py/makeqstrdata.py index b4f4f1b035..0ad749005c 100644 --- a/py/makeqstrdata.py +++ b/py/makeqstrdata.py @@ -17,9 +17,9 @@ import collections import gettext import os.path -if hasattr(sys.stdout, 'reconfigure'): - sys.stdout.reconfigure(encoding='utf-8') - sys.stderr.reconfigure(errors='backslashreplace') +if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + sys.stderr.reconfigure(errors="backslashreplace") py = os.path.dirname(sys.argv[0]) top = os.path.dirname(py) @@ -32,43 +32,44 @@ import huffman # - iterating through bytes is different # - codepoint2name lives in a different module import platform -if platform.python_version_tuple()[0] == '2': + +if platform.python_version_tuple()[0] == "2": bytes_cons = lambda val, enc=None: bytearray(val) from htmlentitydefs import codepoint2name -elif platform.python_version_tuple()[0] == '3': +elif platform.python_version_tuple()[0] == "3": bytes_cons = bytes from html.entities import codepoint2name # end compatibility code -codepoint2name[ord('-')] = 'hyphen'; +codepoint2name[ord("-")] = "hyphen" # add some custom names to map characters that aren't in HTML -codepoint2name[ord(' ')] = 'space' -codepoint2name[ord('\'')] = 'squot' -codepoint2name[ord(',')] = 'comma' -codepoint2name[ord('.')] = 'dot' -codepoint2name[ord(':')] = 'colon' -codepoint2name[ord(';')] = 'semicolon' -codepoint2name[ord('/')] = 'slash' -codepoint2name[ord('%')] = 'percent' -codepoint2name[ord('#')] = 'hash' -codepoint2name[ord('(')] = 'paren_open' -codepoint2name[ord(')')] = 'paren_close' -codepoint2name[ord('[')] = 'bracket_open' -codepoint2name[ord(']')] = 'bracket_close' -codepoint2name[ord('{')] = 'brace_open' -codepoint2name[ord('}')] = 'brace_close' -codepoint2name[ord('*')] = 'star' -codepoint2name[ord('!')] = 'bang' -codepoint2name[ord('\\')] = 'backslash' -codepoint2name[ord('+')] = 'plus' -codepoint2name[ord('$')] = 'dollar' -codepoint2name[ord('=')] = 'equals' -codepoint2name[ord('?')] = 'question' -codepoint2name[ord('@')] = 'at_sign' -codepoint2name[ord('^')] = 'caret' -codepoint2name[ord('|')] = 'pipe' -codepoint2name[ord('~')] = 'tilde' +codepoint2name[ord(" ")] = "space" +codepoint2name[ord("'")] = "squot" +codepoint2name[ord(",")] = "comma" +codepoint2name[ord(".")] = "dot" +codepoint2name[ord(":")] = "colon" +codepoint2name[ord(";")] = "semicolon" +codepoint2name[ord("/")] = "slash" +codepoint2name[ord("%")] = "percent" +codepoint2name[ord("#")] = "hash" +codepoint2name[ord("(")] = "paren_open" +codepoint2name[ord(")")] = "paren_close" +codepoint2name[ord("[")] = "bracket_open" +codepoint2name[ord("]")] = "bracket_close" +codepoint2name[ord("{")] = "brace_open" +codepoint2name[ord("}")] = "brace_close" +codepoint2name[ord("*")] = "star" +codepoint2name[ord("!")] = "bang" +codepoint2name[ord("\\")] = "backslash" +codepoint2name[ord("+")] = "plus" +codepoint2name[ord("$")] = "dollar" +codepoint2name[ord("=")] = "equals" +codepoint2name[ord("?")] = "question" +codepoint2name[ord("@")] = "at_sign" +codepoint2name[ord("^")] = "caret" +codepoint2name[ord("|")] = "pipe" +codepoint2name[ord("~")] = "tilde" C_ESCAPES = { "\a": "\\a", @@ -78,8 +79,8 @@ C_ESCAPES = { "\r": "\\r", "\t": "\\t", "\v": "\\v", - "\'": "\\'", - "\"": "\\\"" + "'": "\\'", + '"': '\\"', } # this must match the equivalent function in qstr.c @@ -90,6 +91,7 @@ def compute_hash(qstr, bytes_hash): # Make sure that valid hash is never zero, zero means "hash not computed" return (hash & ((1 << (8 * bytes_hash)) - 1)) or 1 + def translate(translation_file, i18ns): with open(translation_file, "rb") as f: table = gettext.GNUTranslations(f) @@ -105,6 +107,7 @@ def translate(translation_file, i18ns): translations.append((original, translation)) return translations + class TextSplitter: def __init__(self, words): words.sort(key=lambda x: len(x), reverse=True) @@ -134,6 +137,7 @@ class TextSplitter: for m in self.pat.finditer(text): yield m.group(0) + def iter_substrings(s, minlen, maxlen): len_s = len(s) maxlen = min(len_s, maxlen) @@ -141,18 +145,19 @@ def iter_substrings(s, minlen, maxlen): for begin in range(0, len_s - n + 1): yield s[begin : begin + n] + def compute_huffman_coding(translations, compression_filename): texts = [t[1] for t in translations] words = [] start_unused = 0x80 - end_unused = 0xff + end_unused = 0xFF max_ord = 0 for text in texts: for c in text: ord_c = ord(c) max_ord = max(ord_c, max_ord) - if 0x80 <= ord_c < 0xff: + if 0x80 <= ord_c < 0xFF: end_unused = min(ord_c, end_unused) max_words = end_unused - 0x80 @@ -180,10 +185,7 @@ def compute_huffman_coding(translations, compression_filename): # Score the candidates we found. This is an empirical formula only, # chosen for its effectiveness. scores = sorted( - ( - (s, (len(s) - 1) ** log(max(occ - 2, 1)), occ) - for (s, occ) in counter.items() - ), + ((s, (len(s) - 1) ** log(max(occ - 2, 1)), occ) for (s, occ) in counter.items()), key=lambda x: x[1], reverse=True, ) @@ -234,8 +236,8 @@ def compute_huffman_coding(translations, compression_filename): length_count[length] = 0 length_count[length] += 1 if last_length: - renumbered <<= (length - last_length) - canonical[atom] = '{0:0{width}b}'.format(renumbered, width=length) + renumbered <<= length - last_length + canonical[atom] = "{0:0{width}b}".format(renumbered, width=length) # print(f"atom={repr(atom)} code={code}", file=sys.stderr) if len(atom) > 1: o = words.index(atom) + 0x80 @@ -257,7 +259,8 @@ def compute_huffman_coding(translations, compression_filename): values = [(atom if len(atom) == 1 else chr(0x80 + words.index(atom))) for atom in values] print("//", values, lengths) max_translation_encoded_length = max( - len(translation.encode("utf-8")) for (original, translation) in translations) + len(translation.encode("utf-8")) for (original, translation) in translations + ) wends = list(len(w) - 2 for w in words) for i in range(1, len(wends)): @@ -265,15 +268,28 @@ def compute_huffman_coding(translations, compression_filename): with open(compression_filename, "w") as f: f.write("const uint8_t lengths[] = {{ {} }};\n".format(", ".join(map(str, lengths)))) - f.write("const {} values[] = {{ {} }};\n".format(values_type, ", ".join(str(ord(u)) for u in values))) - f.write("#define compress_max_length_bits ({})\n".format(max_translation_encoded_length.bit_length())) - f.write("const {} words[] = {{ {} }};\n".format(values_type, ", ".join(str(ord(c)) for w in words for c in w))) + f.write( + "const {} values[] = {{ {} }};\n".format( + values_type, ", ".join(str(ord(u)) for u in values) + ) + ) + f.write( + "#define compress_max_length_bits ({})\n".format( + max_translation_encoded_length.bit_length() + ) + ) + f.write( + "const {} words[] = {{ {} }};\n".format( + values_type, ", ".join(str(ord(c)) for w in words for c in w) + ) + ) f.write("const uint8_t wends[] = {{ {} }};\n".format(", ".join(str(p) for p in wends))) f.write("#define word_start {}\n".format(word_start)) f.write("#define word_end {}\n".format(word_end)) return (values, lengths, words, canonical, extractor) + def decompress(encoding_table, encoded, encoded_length_bits): (values, lengths, words, _, _) = encoding_table dec = [] @@ -317,7 +333,7 @@ def decompress(encoding_table, encoded, encoded_length_bits): else: this_bit -= 1 if max_code > 0 and bits < max_code: - #print('{0:0{width}b}'.format(bits, width=bit_length)) + # print('{0:0{width}b}'.format(bits, width=bit_length)) break max_code = (max_code << 1) + lengths[bit_length] searched_length += lengths[bit_length] @@ -325,9 +341,10 @@ def decompress(encoding_table, encoded, encoded_length_bits): v = values[searched_length + bits - max_code] if v >= chr(0x80) and v < chr(0x80 + len(words)): v = words[ord(v) - 0x80] - i += len(v.encode('utf-8')) + i += len(v.encode("utf-8")) dec.append(v) - return ''.join(dec) + return "".join(dec) + def compress(encoding_table, decompressed, encoded_length_bits, len_translation_encoded): if not isinstance(decompressed, str): @@ -362,15 +379,18 @@ def compress(encoding_table, decompressed, encoded_length_bits, len_translation_ current_byte += 1 return enc[:current_byte] + def qstr_escape(qst): def esc_char(m): c = ord(m.group(0)) try: name = codepoint2name[c] except KeyError: - name = '0x%02x' % c - return "_" + name + '_' - return re.sub(r'[^A-Za-z0-9_]', esc_char, qst) + name = "0x%02x" % c + return "_" + name + "_" + + return re.sub(r"[^A-Za-z0-9_]", esc_char, qst) + def parse_input_headers(infiles): # read the qstrs in from the input files @@ -378,28 +398,27 @@ def parse_input_headers(infiles): qstrs = {} i18ns = set() for infile in infiles: - with open(infile, 'rt') as f: + with open(infile, "rt") as f: for line in f: line = line.strip() # is this a config line? - match = re.match(r'^QCFG\((.+), (.+)\)', line) + match = re.match(r"^QCFG\((.+), (.+)\)", line) if match: value = match.group(2) - if value[0] == '(' and value[-1] == ')': + if value[0] == "(" and value[-1] == ")": # strip parenthesis from config value value = value[1:-1] qcfgs[match.group(1)] = value continue - match = re.match(r'^TRANSLATE\("(.*)"\)$', line) if match: i18ns.add(match.group(1)) continue # is this a QSTR line? - match = re.match(r'^Q\((.*)\)$', line) + match = re.match(r"^Q\((.*)\)$", line) if not match: continue @@ -407,8 +426,8 @@ def parse_input_headers(infiles): qstr = match.group(1) # special case to specify control characters - if qstr == '\\n': - qstr = '\n' + if qstr == "\\n": + qstr = "\n" # work out the corresponding qstr name ident = qstr_escape(qstr) @@ -437,56 +456,73 @@ def parse_input_headers(infiles): return qcfgs, qstrs, i18ns + def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr): - qbytes = bytes_cons(qstr, 'utf8') + qbytes = bytes_cons(qstr, "utf8") qlen = len(qbytes) qhash = compute_hash(qbytes, cfg_bytes_hash) - if all(32 <= ord(c) <= 126 and c != '\\' and c != '"' for c in qstr): + if all(32 <= ord(c) <= 126 and c != "\\" and c != '"' for c in qstr): # qstr is all printable ASCII so render it as-is (for easier debugging) qdata = qstr else: # qstr contains non-printable codes so render entire thing as hex pairs - qdata = ''.join(('\\x%02x' % b) for b in qbytes) + qdata = "".join(("\\x%02x" % b) for b in qbytes) if qlen >= (1 << (8 * cfg_bytes_len)): - print('qstr is too long:', qstr) + print("qstr is too long:", qstr) assert False - qlen_str = ('\\x%02x' * cfg_bytes_len) % tuple(((qlen >> (8 * i)) & 0xff) for i in range(cfg_bytes_len)) - qhash_str = ('\\x%02x' * cfg_bytes_hash) % tuple(((qhash >> (8 * i)) & 0xff) for i in range(cfg_bytes_hash)) + qlen_str = ("\\x%02x" * cfg_bytes_len) % tuple( + ((qlen >> (8 * i)) & 0xFF) for i in range(cfg_bytes_len) + ) + qhash_str = ("\\x%02x" * cfg_bytes_hash) % tuple( + ((qhash >> (8 * i)) & 0xFF) for i in range(cfg_bytes_hash) + ) return '(const byte*)"%s%s" "%s"' % (qhash_str, qlen_str, qdata) + def print_qstr_data(encoding_table, qcfgs, qstrs, i18ns): # get config variables - cfg_bytes_len = int(qcfgs['BYTES_IN_LEN']) - cfg_bytes_hash = int(qcfgs['BYTES_IN_HASH']) + cfg_bytes_len = int(qcfgs["BYTES_IN_LEN"]) + cfg_bytes_hash = int(qcfgs["BYTES_IN_HASH"]) # print out the starter of the generated C header file - print('// This file was automatically generated by makeqstrdata.py') - print('') + print("// This file was automatically generated by makeqstrdata.py") + print("") # add NULL qstr with no hash or data - print('QDEF(MP_QSTR_NULL, (const byte*)"%s%s" "")' % ('\\x00' * cfg_bytes_hash, '\\x00' * cfg_bytes_len)) + print( + 'QDEF(MP_QSTR_NULL, (const byte*)"%s%s" "")' + % ("\\x00" * cfg_bytes_hash, "\\x00" * cfg_bytes_len) + ) total_qstr_size = 0 total_qstr_compressed_size = 0 # go through each qstr and print it out for order, ident, qstr in sorted(qstrs.values(), key=lambda x: x[0]): qbytes = make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr) - print('QDEF(MP_QSTR_%s, %s)' % (ident, qbytes)) + print("QDEF(MP_QSTR_%s, %s)" % (ident, qbytes)) total_qstr_size += len(qstr) total_text_size = 0 total_text_compressed_size = 0 - max_translation_encoded_length = max(len(translation.encode("utf-8")) for original, translation in i18ns) + max_translation_encoded_length = max( + len(translation.encode("utf-8")) for original, translation in i18ns + ) encoded_length_bits = max_translation_encoded_length.bit_length() for original, translation in i18ns: translation_encoded = translation.encode("utf-8") - compressed = compress(encoding_table, translation, encoded_length_bits, len(translation_encoded)) + compressed = compress( + encoding_table, translation, encoded_length_bits, len(translation_encoded) + ) total_text_compressed_size += len(compressed) decompressed = decompress(encoding_table, compressed, encoded_length_bits) assert decompressed == translation for c in C_ESCAPES: decompressed = decompressed.replace(c, C_ESCAPES[c]) - print("TRANSLATION(\"{}\", {}) // {}".format(original, ", ".join(["{:d}".format(x) for x in compressed]), decompressed)) + print( + 'TRANSLATION("{}", {}) // {}'.format( + original, ", ".join(["{:d}".format(x) for x in compressed]), decompressed + ) + ) total_text_size += len(translation.encode("utf-8")) print() @@ -495,28 +531,35 @@ def print_qstr_data(encoding_table, qcfgs, qstrs, i18ns): print("// {} bytes worth of translations compressed".format(total_text_compressed_size)) print("// {} bytes saved".format(total_text_size - total_text_compressed_size)) + def print_qstr_enums(qstrs): # print out the starter of the generated C header file - print('// This file was automatically generated by makeqstrdata.py') - print('') + print("// This file was automatically generated by makeqstrdata.py") + print("") # add NULL qstr with no hash or data - print('QENUM(MP_QSTR_NULL)') + print("QENUM(MP_QSTR_NULL)") # go through each qstr and print it out for order, ident, qstr in sorted(qstrs.values(), key=lambda x: x[0]): - print('QENUM(MP_QSTR_%s)' % (ident,)) + print("QENUM(MP_QSTR_%s)" % (ident,)) + if __name__ == "__main__": import argparse - parser = argparse.ArgumentParser(description='Process QSTR definitions into headers for compilation') - parser.add_argument('infiles', metavar='N', type=str, nargs='+', - help='an integer for the accumulator') - parser.add_argument('--translation', default=None, type=str, - help='translations for i18n() items') - parser.add_argument('--compression_filename', default=None, type=str, - help='header for compression info') + parser = argparse.ArgumentParser( + description="Process QSTR definitions into headers for compilation" + ) + parser.add_argument( + "infiles", metavar="N", type=str, nargs="+", help="an integer for the accumulator" + ) + parser.add_argument( + "--translation", default=None, type=str, help="translations for i18n() items" + ) + parser.add_argument( + "--compression_filename", default=None, type=str, help="header for compression info" + ) args = parser.parse_args() diff --git a/py/makeqstrdefs.py b/py/makeqstrdefs.py index d3e90ba486..e6c0033113 100644 --- a/py/makeqstrdefs.py +++ b/py/makeqstrdefs.py @@ -15,51 +15,54 @@ import os # - iterating through bytes is different # - codepoint2name lives in a different module import platform -if platform.python_version_tuple()[0] == '2': + +if platform.python_version_tuple()[0] == "2": bytes_cons = lambda val, enc=None: bytearray(val) from htmlentitydefs import name2codepoint -elif platform.python_version_tuple()[0] == '3': +elif platform.python_version_tuple()[0] == "3": bytes_cons = bytes from html.entities import name2codepoint + unichr = chr # end compatibility code # Blacklist of qstrings that are specially handled in further # processing and should be ignored -QSTRING_BLACK_LIST = set(['NULL', 'number_of']) +QSTRING_BLACK_LIST = set(["NULL", "number_of"]) # add some custom names to map characters that aren't in HTML -name2codepoint['hyphen'] = ord('-') -name2codepoint['space'] = ord(' ') -name2codepoint['squot'] = ord('\'') -name2codepoint['comma'] = ord(',') -name2codepoint['dot'] = ord('.') -name2codepoint['colon'] = ord(':') -name2codepoint['semicolon'] = ord(';') -name2codepoint['slash'] = ord('/') -name2codepoint['percent'] = ord('%') -name2codepoint['hash'] = ord('#') -name2codepoint['paren_open'] = ord('(') -name2codepoint['paren_close'] = ord(')') -name2codepoint['bracket_open'] = ord('[') -name2codepoint['bracket_close'] = ord(']') -name2codepoint['brace_open'] = ord('{') -name2codepoint['brace_close'] = ord('}') -name2codepoint['star'] = ord('*') -name2codepoint['bang'] = ord('!') -name2codepoint['backslash'] = ord('\\') -name2codepoint['plus'] = ord('+') -name2codepoint['dollar'] = ord('$') -name2codepoint['equals'] = ord('=') -name2codepoint['question'] = ord('?') -name2codepoint['at_sign'] = ord('@') -name2codepoint['caret'] = ord('^') -name2codepoint['pipe'] = ord('|') -name2codepoint['tilde'] = ord('~') +name2codepoint["hyphen"] = ord("-") +name2codepoint["space"] = ord(" ") +name2codepoint["squot"] = ord("'") +name2codepoint["comma"] = ord(",") +name2codepoint["dot"] = ord(".") +name2codepoint["colon"] = ord(":") +name2codepoint["semicolon"] = ord(";") +name2codepoint["slash"] = ord("/") +name2codepoint["percent"] = ord("%") +name2codepoint["hash"] = ord("#") +name2codepoint["paren_open"] = ord("(") +name2codepoint["paren_close"] = ord(")") +name2codepoint["bracket_open"] = ord("[") +name2codepoint["bracket_close"] = ord("]") +name2codepoint["brace_open"] = ord("{") +name2codepoint["brace_close"] = ord("}") +name2codepoint["star"] = ord("*") +name2codepoint["bang"] = ord("!") +name2codepoint["backslash"] = ord("\\") +name2codepoint["plus"] = ord("+") +name2codepoint["dollar"] = ord("$") +name2codepoint["equals"] = ord("=") +name2codepoint["question"] = ord("?") +name2codepoint["at_sign"] = ord("@") +name2codepoint["caret"] = ord("^") +name2codepoint["pipe"] = ord("|") +name2codepoint["tilde"] = ord("~") # These are just vexing! -del name2codepoint['and'] -del name2codepoint['or'] +del name2codepoint["and"] +del name2codepoint["or"] + def write_out(fname, output): if output: @@ -68,18 +71,20 @@ def write_out(fname, output): with open(args.output_dir + "/" + fname + ".qstr", "w") as f: f.write("\n".join(output) + "\n") + def qstr_unescape(qstr): for name in name2codepoint: if "__" + name + "__" in qstr: continue if "_" + name + "_" in qstr: - qstr = qstr.replace("_" + name + "_", str(unichr(name2codepoint[name]))) + qstr = qstr.replace("_" + name + "_", str(unichr(name2codepoint[name]))) return qstr + def process_file(f): re_line = re.compile(r"#[line]*\s(\d+)\s\"([^\"]+)\"") - re_qstr = re.compile(r'MP_QSTR_[_a-zA-Z0-9]+') - re_translate = re.compile(r'translate\(\"((?:(?=(\\?))\2.)*?)\"\)') + re_qstr = re.compile(r"MP_QSTR_[_a-zA-Z0-9]+") + re_translate = re.compile(r"translate\(\"((?:(?=(\\?))\2.)*?)\"\)") output = [] last_fname = None lineno = 0 @@ -87,10 +92,10 @@ def process_file(f): if line.isspace(): continue # match gcc-like output (# n "file") and msvc-like output (#line n "file") - if line.startswith(('# ', '#line')): + if line.startswith(("# ", "#line")): m = re_line.match(line) assert m is not None - #print(m.groups()) + # print(m.groups()) lineno = int(m.group(1)) fname = m.group(2) if not fname.endswith(".c"): @@ -101,9 +106,9 @@ def process_file(f): last_fname = fname continue for match in re_qstr.findall(line): - name = match.replace('MP_QSTR_', '') + name = match.replace("MP_QSTR_", "") if name not in QSTRING_BLACK_LIST: - output.append('Q(' + qstr_unescape(name) + ')') + output.append("Q(" + qstr_unescape(name) + ")") for match in re_translate.findall(line): output.append('TRANSLATE("' + match[0] + '")') lineno += 1 @@ -115,6 +120,7 @@ def process_file(f): def cat_together(): import glob import hashlib + hasher = hashlib.md5() all_lines = [] outf = open(args.output_dir + "/out", "wb") @@ -128,7 +134,7 @@ def cat_together(): outf.close() hasher.update(all_lines) new_hash = hasher.hexdigest() - #print(new_hash) + # print(new_hash) old_hash = None try: with open(args.output_file + ".hash") as f: @@ -151,11 +157,12 @@ def cat_together(): if __name__ == "__main__": if len(sys.argv) != 5: - print('usage: %s command input_filename output_dir output_file' % sys.argv[0]) + print("usage: %s command input_filename output_dir output_file" % sys.argv[0]) sys.exit(2) class Args: pass + args = Args() args.command = sys.argv[1] args.input_filename = sys.argv[2] diff --git a/py/makeversionhdr.py b/py/makeversionhdr.py index 7ceeaeadde..41e5956542 100644 --- a/py/makeversionhdr.py +++ b/py/makeversionhdr.py @@ -11,6 +11,7 @@ import os import datetime import subprocess + def get_version_info_from_git(): # Python 2.6 doesn't have check_output, so check for that try: @@ -21,7 +22,11 @@ def get_version_info_from_git(): # Note: git describe doesn't work if no tag is available try: - git_tag = subprocess.check_output(["git", "describe", "--dirty", "--always", "--tags"], stderr=subprocess.STDOUT, universal_newlines=True).strip() + git_tag = subprocess.check_output( + ["git", "describe", "--dirty", "--always", "--tags"], + stderr=subprocess.STDOUT, + universal_newlines=True, + ).strip() except subprocess.CalledProcessError as er: if er.returncode == 128: # git exit code of 128 means no repository found @@ -30,7 +35,11 @@ def get_version_info_from_git(): except OSError: return None try: - git_hash = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"], stderr=subprocess.STDOUT, universal_newlines=True).strip() + git_hash = subprocess.check_output( + ["git", "rev-parse", "--short", "HEAD"], + stderr=subprocess.STDOUT, + universal_newlines=True, + ).strip() except subprocess.CalledProcessError: git_hash = "unknown" except OSError: @@ -38,9 +47,13 @@ def get_version_info_from_git(): try: # Check if there are any modified files. - subprocess.check_call(["git", "diff", "--no-ext-diff", "--quiet", "--exit-code"], stderr=subprocess.STDOUT) + subprocess.check_call( + ["git", "diff", "--no-ext-diff", "--quiet", "--exit-code"], stderr=subprocess.STDOUT + ) # Check if there are any staged files. - subprocess.check_call(["git", "diff-index", "--cached", "--quiet", "HEAD", "--"], stderr=subprocess.STDOUT) + subprocess.check_call( + ["git", "diff-index", "--cached", "--quiet", "HEAD", "--"], stderr=subprocess.STDOUT + ) except subprocess.CalledProcessError: git_hash += "-dirty" except OSError: @@ -51,6 +64,7 @@ def get_version_info_from_git(): return git_tag, git_hash, ver + def get_version_info_from_docs_conf(): with open(os.path.join(os.path.dirname(sys.argv[0]), "..", "conf.py")) as f: for line in f: @@ -63,6 +77,7 @@ def get_version_info_from_docs_conf(): return git_tag, "", ver return None + def make_version_header(filename): # Get version info using git, with fallback to docs/conf.py info = get_version_info_from_git() @@ -87,21 +102,29 @@ def make_version_header(filename): #define MICROPY_VERSION_MICRO (%s) #define MICROPY_VERSION_STRING "%s" #define MICROPY_FULL_VERSION_INFO ("Adafruit CircuitPython " MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE "; " MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME) -""" % (git_tag, git_hash, datetime.date.today().strftime("%Y-%m-%d"), - ver[0].replace('v', ''), ver[1], ver[2], version_string) +""" % ( + git_tag, + git_hash, + datetime.date.today().strftime("%Y-%m-%d"), + ver[0].replace("v", ""), + ver[1], + ver[2], + version_string, + ) # Check if the file contents changed from last time write_file = True if os.path.isfile(filename): - with open(filename, 'r') as f: + with open(filename, "r") as f: existing_data = f.read() if existing_data == file_data: write_file = False # Only write the file if we need to if write_file: - with open(filename, 'w') as f: + with open(filename, "w") as f: f.write(file_data) + if __name__ == "__main__": make_version_header(sys.argv[1]) diff --git a/py/malloc.c b/py/malloc.c index c923e89a65..e06d20e956 100644 --- a/py/malloc.c +++ b/py/malloc.c @@ -82,22 +82,22 @@ void *m_malloc(size_t num_bytes, bool long_lived) { if (ptr == NULL && num_bytes != 0) { m_malloc_fail(num_bytes); } -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS MP_STATE_MEM(total_bytes_allocated) += num_bytes; MP_STATE_MEM(current_bytes_allocated) += num_bytes; UPDATE_PEAK(); -#endif + #endif DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); return ptr; } void *m_malloc_maybe(size_t num_bytes, bool long_lived) { void *ptr = malloc_ll(num_bytes, long_lived); -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS MP_STATE_MEM(total_bytes_allocated) += num_bytes; MP_STATE_MEM(current_bytes_allocated) += num_bytes; UPDATE_PEAK(); -#endif + #endif DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); return ptr; } @@ -108,11 +108,11 @@ void *m_malloc_with_finaliser(size_t num_bytes, bool long_lived) { if (ptr == NULL && num_bytes != 0) { m_malloc_fail(num_bytes); } -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS MP_STATE_MEM(total_bytes_allocated) += num_bytes; MP_STATE_MEM(current_bytes_allocated) += num_bytes; UPDATE_PEAK(); -#endif + #endif DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); return ptr; } @@ -131,12 +131,12 @@ void *m_malloc0(size_t num_bytes, bool long_lived) { void *m_realloc(void *ptr, size_t old_num_bytes, size_t new_num_bytes) { #else void *m_realloc(void *ptr, size_t new_num_bytes) { -#endif + #endif void *new_ptr = realloc(ptr, new_num_bytes); if (new_ptr == NULL && new_num_bytes != 0) { m_malloc_fail(new_num_bytes); } -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS // At first thought, "Total bytes allocated" should only grow, // after all, it's *total*. But consider for example 2K block // shrunk to 1K and then grown to 2K again. It's still 2K @@ -146,7 +146,7 @@ void *m_realloc(void *ptr, size_t new_num_bytes) { MP_STATE_MEM(total_bytes_allocated) += diff; MP_STATE_MEM(current_bytes_allocated) += diff; UPDATE_PEAK(); -#endif + #endif #if MICROPY_MALLOC_USES_ALLOCATED_SIZE DEBUG_printf("realloc %p, %d, %d : %p\n", ptr, old_num_bytes, new_num_bytes, new_ptr); #else @@ -159,9 +159,9 @@ void *m_realloc(void *ptr, size_t new_num_bytes) { void *m_realloc_maybe(void *ptr, size_t old_num_bytes, size_t new_num_bytes, bool allow_move) { #else void *m_realloc_maybe(void *ptr, size_t new_num_bytes, bool allow_move) { -#endif + #endif void *new_ptr = realloc_ext(ptr, new_num_bytes, allow_move); -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS // At first thought, "Total bytes allocated" should only grow, // after all, it's *total*. But consider for example 2K block // shrunk to 1K and then grown to 2K again. It's still 2K @@ -174,7 +174,7 @@ void *m_realloc_maybe(void *ptr, size_t new_num_bytes, bool allow_move) { MP_STATE_MEM(current_bytes_allocated) += diff; UPDATE_PEAK(); } -#endif + #endif #if MICROPY_MALLOC_USES_ALLOCATED_SIZE DEBUG_printf("realloc %p, %d, %d : %p\n", ptr, old_num_bytes, new_num_bytes, new_ptr); #else @@ -187,11 +187,11 @@ void *m_realloc_maybe(void *ptr, size_t new_num_bytes, bool allow_move) { void m_free(void *ptr, size_t num_bytes) { #else void m_free(void *ptr) { -#endif + #endif free(ptr); -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS MP_STATE_MEM(current_bytes_allocated) -= num_bytes; -#endif + #endif #if MICROPY_MALLOC_USES_ALLOCATED_SIZE DEBUG_printf("free %p, %d\n", ptr, num_bytes); #else diff --git a/py/map.c b/py/map.c index 69eed9d3b9..a37a3c984d 100644 --- a/py/map.c +++ b/py/map.c @@ -98,7 +98,7 @@ void mp_map_init_fixed_table(mp_map_t *map, size_t n, const mp_obj_t *table) { map->all_keys_are_qstrs = 1; map->is_fixed = 1; map->is_ordered = 1; - map->table = (mp_map_elem_t*)table; + map->table = (mp_map_elem_t *)table; } // Differentiate from mp_map_clear() - semantics is different @@ -145,7 +145,7 @@ STATIC void mp_map_rehash(mp_map_t *map) { // - returns slot, with key non-null and value=MP_OBJ_NULL if it was added // MP_MAP_LOOKUP_REMOVE_IF_FOUND behaviour: // - returns NULL if not found, else the slot if was found in with key null and value non-null -mp_map_elem_t *PLACE_IN_ITCM(mp_map_lookup)(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t lookup_kind) { +mp_map_elem_t *PLACE_IN_ITCM(mp_map_lookup)(mp_map_t * map, mp_obj_t index, mp_map_lookup_kind_t lookup_kind) { // If the map is a fixed array then we must only be called for a lookup assert(!map->is_fixed || lookup_kind == MP_MAP_LOOKUP); diff --git a/py/misc.h b/py/misc.h index 0fef7e249e..cb7192a56f 100644 --- a/py/misc.h +++ b/py/misc.h @@ -59,35 +59,35 @@ typedef unsigned int uint; // TODO make a lazy m_renew that can increase by a smaller amount than requested (but by at least 1 more element) -#define m_new(type, num) ((type*)(m_malloc(sizeof(type) * (num), false))) -#define m_new_ll(type, num) ((type*)(m_malloc(sizeof(type) * (num), true))) -#define m_new_maybe(type, num) ((type*)(m_malloc_maybe(sizeof(type) * (num), false))) -#define m_new_ll_maybe(type, num) ((type*)(m_malloc_maybe(sizeof(type) * (num), true))) -#define m_new0(type, num) ((type*)(m_malloc0(sizeof(type) * (num), false))) -#define m_new0_ll(type, num) ((type*)(m_malloc0(sizeof(type) * (num), true))) +#define m_new(type, num) ((type *)(m_malloc(sizeof(type) * (num), false))) +#define m_new_ll(type, num) ((type *)(m_malloc(sizeof(type) * (num), true))) +#define m_new_maybe(type, num) ((type *)(m_malloc_maybe(sizeof(type) * (num), false))) +#define m_new_ll_maybe(type, num) ((type *)(m_malloc_maybe(sizeof(type) * (num), true))) +#define m_new0(type, num) ((type *)(m_malloc0(sizeof(type) * (num), false))) +#define m_new0_ll(type, num) ((type *)(m_malloc0(sizeof(type) * (num), true))) #define m_new_obj(type) (m_new(type, 1)) #define m_new_ll_obj(type) (m_new_ll(type, 1)) #define m_new_obj_maybe(type) (m_new_maybe(type, 1)) -#define m_new_obj_var(obj_type, var_type, var_num) ((obj_type*)m_malloc(sizeof(obj_type) + sizeof(var_type) * (var_num), false)) -#define m_new_obj_var_maybe(obj_type, var_type, var_num) ((obj_type*)m_malloc_maybe(sizeof(obj_type) + sizeof(var_type) * (var_num), false)) -#define m_new_ll_obj_var_maybe(obj_type, var_type, var_num) ((obj_type*)m_malloc_maybe(sizeof(obj_type) + sizeof(var_type) * (var_num), true)) +#define m_new_obj_var(obj_type, var_type, var_num) ((obj_type *)m_malloc(sizeof(obj_type) + sizeof(var_type) * (var_num), false)) +#define m_new_obj_var_maybe(obj_type, var_type, var_num) ((obj_type *)m_malloc_maybe(sizeof(obj_type) + sizeof(var_type) * (var_num), false)) +#define m_new_ll_obj_var_maybe(obj_type, var_type, var_num) ((obj_type *)m_malloc_maybe(sizeof(obj_type) + sizeof(var_type) * (var_num), true)) #if MICROPY_ENABLE_FINALISER -#define m_new_obj_with_finaliser(type) ((type*)(m_malloc_with_finaliser(sizeof(type), false))) -#define m_new_obj_var_with_finaliser(type, var_type, var_num) ((type*)m_malloc_with_finaliser(sizeof(type) + sizeof(var_type) * (var_num), false)) -#define m_new_ll_obj_with_finaliser(type) ((type*)(m_malloc_with_finaliser(sizeof(type), true))) +#define m_new_obj_with_finaliser(type) ((type *)(m_malloc_with_finaliser(sizeof(type), false))) +#define m_new_obj_var_with_finaliser(type, var_type, var_num) ((type *)m_malloc_with_finaliser(sizeof(type) + sizeof(var_type) * (var_num), false)) +#define m_new_ll_obj_with_finaliser(type) ((type *)(m_malloc_with_finaliser(sizeof(type), true))) #else #define m_new_obj_with_finaliser(type) m_new_obj(type) #define m_new_obj_var_with_finaliser(type, var_type, var_num) m_new_obj_var(type, var_type, var_num) #define m_new_ll_obj_with_finaliser(type) m_new_ll_obj(type) #endif #if MICROPY_MALLOC_USES_ALLOCATED_SIZE -#define m_renew(type, ptr, old_num, new_num) ((type*)(m_realloc((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num)))) -#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type*)(m_realloc_maybe((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num), (allow_move)))) +#define m_renew(type, ptr, old_num, new_num) ((type *)(m_realloc((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num)))) +#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type *)(m_realloc_maybe((ptr), sizeof(type) * (old_num), sizeof(type) * (new_num), (allow_move)))) #define m_del(type, ptr, num) m_free(ptr, sizeof(type) * (num)) #define m_del_var(obj_type, var_type, var_num, ptr) (m_free(ptr, sizeof(obj_type) + sizeof(var_type) * (var_num))) #else -#define m_renew(type, ptr, old_num, new_num) ((type*)(m_realloc((ptr), sizeof(type) * (new_num)))) -#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type*)(m_realloc_maybe((ptr), sizeof(type) * (new_num), (allow_move)))) +#define m_renew(type, ptr, old_num, new_num) ((type *)(m_realloc((ptr), sizeof(type) * (new_num)))) +#define m_renew_maybe(type, ptr, old_num, new_num, allow_move) ((type *)(m_realloc_maybe((ptr), sizeof(type) * (new_num), (allow_move)))) #define m_del(type, ptr, num) ((void)(num), m_free(ptr)) #define m_del_var(obj_type, var_type, var_num, ptr) ((void)(var_num), m_free(ptr)) #endif @@ -120,7 +120,7 @@ size_t m_get_peak_bytes_allocated(void); #define MP_ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0])) // align ptr to the nearest multiple of "alignment" -#define MP_ALIGN(ptr, alignment) (void*)(((uintptr_t)(ptr) + ((alignment) - 1)) & ~((alignment) - 1)) +#define MP_ALIGN(ptr, alignment) (void *)(((uintptr_t)(ptr) + ((alignment) - 1)) & ~((alignment) - 1)) #define sizeof_field(TYPE, MEMBER) sizeof((((TYPE *)0)->MEMBER)) @@ -140,9 +140,16 @@ unichar utf8_get_char(const byte *s); const byte *utf8_next_char(const byte *s); size_t utf8_charlen(const byte *str, size_t len); #else -static inline unichar utf8_get_char(const byte *s) { return *s; } -static inline const byte *utf8_next_char(const byte *s) { return s + 1; } -static inline size_t utf8_charlen(const byte *str, size_t len) { (void)str; return len; } +static inline unichar utf8_get_char(const byte *s) { + return *s; +} +static inline const byte *utf8_next_char(const byte *s) { + return s + 1; +} +static inline size_t utf8_charlen(const byte *str, size_t len) { + (void)str; + return len; +} #endif bool unichar_isspace(unichar c); @@ -179,9 +186,15 @@ void vstr_init_print(vstr_t *vstr, size_t alloc, struct _mp_print_t *print); void vstr_clear(vstr_t *vstr); vstr_t *vstr_new(size_t alloc); void vstr_free(vstr_t *vstr); -static inline void vstr_reset(vstr_t *vstr) { vstr->len = 0; } -static inline char *vstr_str(vstr_t *vstr) { return vstr->buf; } -static inline size_t vstr_len(vstr_t *vstr) { return vstr->len; } +static inline void vstr_reset(vstr_t *vstr) { + vstr->len = 0; +} +static inline char *vstr_str(vstr_t *vstr) { + return vstr->buf; +} +static inline size_t vstr_len(vstr_t *vstr) { + return vstr->len; +} void vstr_hint_size(vstr_t *vstr, size_t size); char *vstr_extend(vstr_t *vstr, size_t size); char *vstr_add_len(vstr_t *vstr, size_t len); @@ -202,10 +215,10 @@ void vstr_printf(vstr_t *vstr, const char *fmt, ...); #define CHECKBUF(buf, max_size) char buf[max_size + 1]; size_t buf##_len = max_size; char *buf##_p = buf; #define CHECKBUF_RESET(buf, max_size) buf##_len = max_size; buf##_p = buf; #define CHECKBUF_APPEND(buf, src, src_len) \ - { size_t l = MIN(src_len, buf##_len); \ - memcpy(buf##_p, src, l); \ - buf##_len -= l; \ - buf##_p += l; } + { size_t l = MIN(src_len, buf##_len); \ + memcpy(buf##_p, src, l); \ + buf##_len -= l; \ + buf##_p += l; } #define CHECKBUF_APPEND_0(buf) { *buf##_p = 0; } #define CHECKBUF_LEN(buf) (buf##_p - buf) diff --git a/py/modarray.c b/py/modarray.c index 75bc5169f8..a47684bf97 100644 --- a/py/modarray.c +++ b/py/modarray.c @@ -37,7 +37,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_array_globals, mp_module_array_globals_tab const mp_obj_module_t mp_module_array = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_array_globals, + .globals = (mp_obj_dict_t *)&mp_module_array_globals, }; #endif diff --git a/py/modbuiltins.c b/py/modbuiltins.c index fe3c366eec..ccf29cfe1c 100644 --- a/py/modbuiltins.c +++ b/py/modbuiltins.c @@ -142,7 +142,8 @@ STATIC mp_obj_t mp_builtin_chr(mp_obj_t o_in) { uint8_t str[4]; int len = 0; if (c < 0x80) { - *str = c; len = 1; + *str = c; + len = 1; } else if (c < 0x800) { str[0] = (c >> 6) | 0xC0; str[1] = (c & 0x3F) | 0x80; @@ -161,12 +162,12 @@ STATIC mp_obj_t mp_builtin_chr(mp_obj_t o_in) { } else { mp_raise_ValueError(translate("chr() arg not in range(0x110000)")); } - return mp_obj_new_str_via_qstr((char*)str, len); + return mp_obj_new_str_via_qstr((char *)str, len); #else mp_int_t ord = mp_obj_get_int(o_in); if (0 <= ord && ord <= 0xff) { uint8_t str[1] = {ord}; - return mp_obj_new_str_via_qstr((char*)str, 1); + return mp_obj_new_str_via_qstr((char *)str, 1); } else { mp_raise_ValueError(translate("chr() arg not in range(256)")); } @@ -330,7 +331,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_oct_obj, mp_builtin_oct); STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) { size_t len; - const byte *str = (const byte*)mp_obj_str_get_data(o_in, &len); + const byte *str = (const byte *)mp_obj_str_get_data(o_in, &len); #if MICROPY_PY_BUILTINS_STR_UNICODE if (MP_OBJ_IS_STR(o_in)) { len = utf8_charlen(str, len); @@ -347,25 +348,26 @@ STATIC mp_obj_t mp_builtin_ord(mp_obj_t o_in) { } #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("ord expects a character")); + mp_raise_TypeError(translate("ord expects a character")); #else - mp_raise_TypeError_varg( - translate("ord() expected a character, but string of length %d found"), (int)len); + mp_raise_TypeError_varg( + translate("ord() expected a character, but string of length %d found"), (int)len); #endif } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_ord_obj, mp_builtin_ord); STATIC mp_obj_t mp_builtin_pow(size_t n_args, const mp_obj_t *args) { switch (n_args) { - case 2: return mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]); + case 2: + return mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]); default: -#if !MICROPY_PY_BUILTINS_POW3 + #if !MICROPY_PY_BUILTINS_POW3 mp_raise_msg(&mp_type_NotImplementedError, translate("3-arg pow() not supported")); -#elif MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_MPZ + #elif MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_MPZ return mp_binary_op(MP_BINARY_OP_MODULO, mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]), args[2]); -#else + #else return mp_obj_int_pow3(args[0], args[1], args[2]); -#endif + #endif } } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_pow_obj, 2, 3, mp_builtin_pow); @@ -464,7 +466,7 @@ STATIC mp_obj_t mp_builtin_round(size_t n_args, const mp_obj_t *args) { #else mp_obj_t mult = mp_binary_op(MP_BINARY_OP_POWER, MP_OBJ_NEW_SMALL_INT(10), MP_OBJ_NEW_SMALL_INT(-num_dig)); - mp_obj_t half_mult = mp_binary_op(MP_BINARY_OP_FLOOR_DIVIDE, mult, MP_OBJ_NEW_SMALL_INT(2)); + mp_obj_t half_mult = mp_binary_op(MP_BINARY_OP_FLOOR_DIVIDE, mult, MP_OBJ_NEW_SMALL_INT(2)); mp_obj_t modulo = mp_binary_op(MP_BINARY_OP_MODULO, o_in, mult); mp_obj_t rounded = mp_binary_op(MP_BINARY_OP_SUBTRACT, o_in, modulo); if (mp_obj_is_true(mp_binary_op(MP_BINARY_OP_MORE, half_mult, modulo))) { @@ -482,7 +484,7 @@ STATIC mp_obj_t mp_builtin_round(size_t n_args, const mp_obj_t *args) { } #endif } -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT mp_float_t val = mp_obj_get_float(o_in); if (n_args > 1) { mp_int_t num_dig = mp_obj_get_int(args[1]); @@ -493,18 +495,22 @@ STATIC mp_obj_t mp_builtin_round(size_t n_args, const mp_obj_t *args) { } mp_float_t rounded = MICROPY_FLOAT_C_FUN(nearbyint)(val); return mp_obj_new_int_from_float(rounded); -#else + #else mp_int_t r = mp_obj_get_int(o_in); return mp_obj_new_int(r); -#endif + #endif } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_round_obj, 1, 2, mp_builtin_round); STATIC mp_obj_t mp_builtin_sum(size_t n_args, const mp_obj_t *args) { mp_obj_t value; switch (n_args) { - case 1: value = MP_OBJ_NEW_SMALL_INT(0); break; - default: value = args[1]; break; + case 1: + value = MP_OBJ_NEW_SMALL_INT(0); + break; + default: + value = args[1]; + break; } mp_obj_iter_buf_t iter_buf; mp_obj_t iterable = mp_getiter(args[0], &iter_buf); @@ -726,9 +732,9 @@ STATIC const mp_rom_map_elem_t mp_module_builtins_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_NameError), MP_ROM_PTR(&mp_type_NameError) }, { MP_ROM_QSTR(MP_QSTR_NotImplementedError), MP_ROM_PTR(&mp_type_NotImplementedError) }, { MP_ROM_QSTR(MP_QSTR_OSError), MP_ROM_PTR(&mp_type_OSError) }, - { MP_ROM_QSTR(MP_QSTR_TimeoutError), MP_ROM_PTR(&mp_type_TimeoutError) }, - { MP_ROM_QSTR(MP_QSTR_ConnectionError), MP_ROM_PTR(&mp_type_ConnectionError) }, - { MP_ROM_QSTR(MP_QSTR_BrokenPipeError), MP_ROM_PTR(&mp_type_BrokenPipeError) }, + { MP_ROM_QSTR(MP_QSTR_TimeoutError), MP_ROM_PTR(&mp_type_TimeoutError) }, + { MP_ROM_QSTR(MP_QSTR_ConnectionError), MP_ROM_PTR(&mp_type_ConnectionError) }, + { MP_ROM_QSTR(MP_QSTR_BrokenPipeError), MP_ROM_PTR(&mp_type_BrokenPipeError) }, { MP_ROM_QSTR(MP_QSTR_OverflowError), MP_ROM_PTR(&mp_type_OverflowError) }, { MP_ROM_QSTR(MP_QSTR_RuntimeError), MP_ROM_PTR(&mp_type_RuntimeError) }, #if MICROPY_PY_ASYNC_AWAIT @@ -757,5 +763,5 @@ MP_DEFINE_CONST_DICT(mp_module_builtins_globals, mp_module_builtins_globals_tabl const mp_obj_module_t mp_module_builtins = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_builtins_globals, + .globals = (mp_obj_dict_t *)&mp_module_builtins_globals, }; diff --git a/py/modcmath.c b/py/modcmath.c index d6b364733d..63f289d498 100644 --- a/py/modcmath.c +++ b/py/modcmath.c @@ -43,7 +43,7 @@ STATIC mp_obj_t mp_cmath_polar(mp_obj_t z_obj) { mp_float_t real, imag; mp_obj_get_complex(z_obj, &real, &imag); mp_obj_t tuple[2] = { - mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(real*real + imag*imag)), + mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(real * real + imag * imag)), mp_obj_new_float(MICROPY_FLOAT_C_FUN(atan2)(imag, real)), }; return mp_obj_new_tuple(2, tuple); @@ -72,7 +72,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_exp_obj, mp_cmath_exp); STATIC mp_obj_t mp_cmath_log(mp_obj_t z_obj) { mp_float_t real, imag; mp_obj_get_complex(z_obj, &real, &imag); - return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log)(real*real + imag*imag), MICROPY_FLOAT_C_FUN(atan2)(imag, real)); + return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log)(real * real + imag * imag), MICROPY_FLOAT_C_FUN(atan2)(imag, real)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log_obj, mp_cmath_log); @@ -81,7 +81,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log_obj, mp_cmath_log); STATIC mp_obj_t mp_cmath_log10(mp_obj_t z_obj) { mp_float_t real, imag; mp_obj_get_complex(z_obj, &real, &imag); - return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log10)(real*real + imag*imag), 0.4342944819032518 * MICROPY_FLOAT_C_FUN(atan2)(imag, real)); + return mp_obj_new_complex(0.5 * MICROPY_FLOAT_C_FUN(log10)(real * real + imag * imag), 0.4342944819032518 * MICROPY_FLOAT_C_FUN(atan2)(imag, real)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log10_obj, mp_cmath_log10); #endif @@ -90,7 +90,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_cmath_log10_obj, mp_cmath_log10); STATIC mp_obj_t mp_cmath_sqrt(mp_obj_t z_obj) { mp_float_t real, imag; mp_obj_get_complex(z_obj, &real, &imag); - mp_float_t sqrt_abs = MICROPY_FLOAT_C_FUN(pow)(real*real + imag*imag, 0.25); + mp_float_t sqrt_abs = MICROPY_FLOAT_C_FUN(pow)(real * real + imag * imag, 0.25); mp_float_t theta = 0.5 * MICROPY_FLOAT_C_FUN(atan2)(imag, real); return mp_obj_new_complex(sqrt_abs * MICROPY_FLOAT_C_FUN(cos)(theta), sqrt_abs * MICROPY_FLOAT_C_FUN(sin)(theta)); } @@ -125,28 +125,28 @@ STATIC const mp_rom_map_elem_t mp_module_cmath_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_log10), MP_ROM_PTR(&mp_cmath_log10_obj) }, #endif { MP_ROM_QSTR(MP_QSTR_sqrt), MP_ROM_PTR(&mp_cmath_sqrt_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_acos), MP_ROM_PTR(&mp_cmath_acos_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_asin), MP_ROM_PTR(&mp_cmath_asin_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_atan), MP_ROM_PTR(&mp_cmath_atan_obj) }, + // { MP_ROM_QSTR(MP_QSTR_acos), MP_ROM_PTR(&mp_cmath_acos_obj) }, + // { MP_ROM_QSTR(MP_QSTR_asin), MP_ROM_PTR(&mp_cmath_asin_obj) }, + // { MP_ROM_QSTR(MP_QSTR_atan), MP_ROM_PTR(&mp_cmath_atan_obj) }, { MP_ROM_QSTR(MP_QSTR_cos), MP_ROM_PTR(&mp_cmath_cos_obj) }, { MP_ROM_QSTR(MP_QSTR_sin), MP_ROM_PTR(&mp_cmath_sin_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_tan), MP_ROM_PTR(&mp_cmath_tan_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_acosh), MP_ROM_PTR(&mp_cmath_acosh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_asinh), MP_ROM_PTR(&mp_cmath_asinh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_atanh), MP_ROM_PTR(&mp_cmath_atanh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_cosh), MP_ROM_PTR(&mp_cmath_cosh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_sinh), MP_ROM_PTR(&mp_cmath_sinh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_tanh), MP_ROM_PTR(&mp_cmath_tanh_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_isfinite), MP_ROM_PTR(&mp_cmath_isfinite_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_isinf), MP_ROM_PTR(&mp_cmath_isinf_obj) }, - //{ MP_ROM_QSTR(MP_QSTR_isnan), MP_ROM_PTR(&mp_cmath_isnan_obj) }, + // { MP_ROM_QSTR(MP_QSTR_tan), MP_ROM_PTR(&mp_cmath_tan_obj) }, + // { MP_ROM_QSTR(MP_QSTR_acosh), MP_ROM_PTR(&mp_cmath_acosh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_asinh), MP_ROM_PTR(&mp_cmath_asinh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_atanh), MP_ROM_PTR(&mp_cmath_atanh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_cosh), MP_ROM_PTR(&mp_cmath_cosh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_sinh), MP_ROM_PTR(&mp_cmath_sinh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_tanh), MP_ROM_PTR(&mp_cmath_tanh_obj) }, + // { MP_ROM_QSTR(MP_QSTR_isfinite), MP_ROM_PTR(&mp_cmath_isfinite_obj) }, + // { MP_ROM_QSTR(MP_QSTR_isinf), MP_ROM_PTR(&mp_cmath_isinf_obj) }, + // { MP_ROM_QSTR(MP_QSTR_isnan), MP_ROM_PTR(&mp_cmath_isnan_obj) }, }; STATIC MP_DEFINE_CONST_DICT(mp_module_cmath_globals, mp_module_cmath_globals_table); const mp_obj_module_t mp_module_cmath = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_cmath_globals, + .globals = (mp_obj_dict_t *)&mp_module_cmath_globals, }; #endif // MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_CMATH diff --git a/py/modcollections.c b/py/modcollections.c index 9634c5ce73..235745f584 100644 --- a/py/modcollections.c +++ b/py/modcollections.c @@ -43,7 +43,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_collections_globals, mp_module_collections const mp_obj_module_t mp_module_collections = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_collections_globals, + .globals = (mp_obj_dict_t *)&mp_module_collections_globals, }; #endif // MICROPY_PY_COLLECTIONS diff --git a/py/modgc.c b/py/modgc.c index b01876422a..e655cfa93e 100644 --- a/py/modgc.c +++ b/py/modgc.c @@ -33,11 +33,11 @@ // collect(): run a garbage collection STATIC mp_obj_t py_gc_collect(void) { gc_collect(); -#if MICROPY_PY_GC_COLLECT_RETVAL + #if MICROPY_PY_GC_COLLECT_RETVAL return MP_OBJ_NEW_SMALL_INT(MP_STATE_MEM(gc_collected)); -#else + #else return mp_const_none; -#endif + #endif } MP_DEFINE_CONST_FUN_OBJ_0(gc_collect_obj, py_gc_collect); @@ -112,7 +112,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_gc_globals, mp_module_gc_globals_table); const mp_obj_module_t mp_module_gc = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_gc_globals, + .globals = (mp_obj_dict_t *)&mp_module_gc_globals, }; #endif diff --git a/py/modio.c b/py/modio.c index 4bcc3971eb..01cb65af59 100644 --- a/py/modio.c +++ b/py/modio.c @@ -72,7 +72,7 @@ STATIC mp_uint_t iobase_read(mp_obj_t obj, void *buf, mp_uint_t size, int *errco } STATIC mp_uint_t iobase_write(mp_obj_t obj, const void *buf, mp_uint_t size, int *errcode) { - return iobase_read_write(obj, (void*)buf, size, errcode, MP_QSTR_write); + return iobase_read_write(obj, (void *)buf, size, errcode, MP_QSTR_write); } STATIC mp_uint_t iobase_ioctl(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode) { @@ -145,7 +145,7 @@ STATIC mp_uint_t bufwriter_write(mp_obj_t self_in, const void *buf, mp_uint_t si // is word-aligned, to guard against obscure cases when it matters, e.g. // https://github.com/micropython/micropython/issues/1863 memcpy(self->buf + self->len, buf, rem); - buf = (byte*)buf + rem; + buf = (byte *)buf + rem; size -= rem; mp_uint_t out_sz = mp_stream_write_exactly(self->stream, self->buf, self->alloc, errcode); if (*errcode != 0) { @@ -195,7 +195,7 @@ STATIC const mp_obj_type_t bufwriter_type = { .name = MP_QSTR_BufferedWriter, .make_new = bufwriter_make_new, .protocol = &bufwriter_stream_p, - .locals_dict = (mp_obj_dict_t*)&bufwriter_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bufwriter_locals_dict, }; #endif // MICROPY_PY_IO_BUFFEREDWRITER @@ -238,14 +238,14 @@ STATIC mp_obj_t resource_stream(mp_obj_t package_in, mp_obj_t path_in) { mp_obj_stringio_t *o = m_new_obj(mp_obj_stringio_t); o->base.type = &mp_type_bytesio; o->vstr = m_new_obj(vstr_t); - vstr_init_fixed_buf(o->vstr, file_len + 1, (char*)data); + vstr_init_fixed_buf(o->vstr, file_len + 1, (char *)data); o->vstr->len = file_len; o->pos = 0; return MP_OBJ_FROM_PTR(o); } mp_obj_t path_out = mp_obj_new_str(path_buf.buf, path_buf.len); - return mp_builtin_open(1, &path_out, (mp_map_t*)&mp_const_empty_map); + return mp_builtin_open(1, &path_out, (mp_map_t *)&mp_const_empty_map); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(resource_stream_obj, resource_stream); #endif @@ -280,7 +280,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_io_globals, mp_module_io_globals_table); const mp_obj_module_t mp_module_io = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_io_globals, + .globals = (mp_obj_dict_t *)&mp_module_io_globals, }; #endif diff --git a/py/modmath.c b/py/modmath.c index ec520bb6f2..2e271aed3d 100644 --- a/py/modmath.c +++ b/py/modmath.c @@ -61,30 +61,30 @@ STATIC mp_obj_t math_generic_2(mp_obj_t x_obj, mp_obj_t y_obj, mp_float_t (*f)(m } #define MATH_FUN_1(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { \ + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { \ return math_generic_1(x_obj, MICROPY_FLOAT_C_FUN(c_name)); \ } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_1_TO_BOOL(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_bool(c_name(mp_obj_get_float(x_obj))); } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_bool(c_name(mp_obj_get_float(x_obj))); } \ + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_1_TO_INT(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_int_from_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_int_from_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \ + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_2(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \ + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \ return math_generic_2(x_obj, y_obj, MICROPY_FLOAT_C_FUN(c_name)); \ } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_2_FLT_INT(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \ + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj, mp_obj_t y_obj) { \ return mp_obj_new_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj), mp_obj_get_int(y_obj))); \ } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_##py_name##_obj, mp_math_##py_name); #if MP_NEED_LOG2 #undef log2 @@ -148,7 +148,7 @@ STATIC mp_float_t MICROPY_FLOAT_C_FUN(fabs_func)(mp_float_t x) { } MATH_FUN_1(fabs, fabs_func) // floor(x) -MATH_FUN_1_TO_INT(floor, floor) //TODO: delegate to x.__floor__() if x is not a float +MATH_FUN_1_TO_INT(floor, floor) // TODO: delegate to x.__floor__() if x is not a float // fmod(x, y) MATH_FUN_2(fmod, fmod) // isfinite(x) @@ -171,7 +171,7 @@ MATH_FUN_1(gamma, tgamma) // lgamma(x): return the natural logarithm of the gamma function of x MATH_FUN_1(lgamma, lgamma) #endif -//TODO: factorial, fsum +// TODO: factorial, fsum // Function that takes a variable number of arguments @@ -189,10 +189,10 @@ STATIC mp_obj_t mp_math_log(size_t n_args, const mp_obj_t *args) { if (base <= (mp_float_t)0.0) { math_error(); // Turn off warning when comparing exactly with integral value 1.0 -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" } else if (base == (mp_float_t)1.0) { -#pragma GCC diagnostic pop + #pragma GCC diagnostic pop mp_raise_msg(&mp_type_ZeroDivisionError, translate("division by zero")); } return mp_obj_new_float(l / MICROPY_FLOAT_C_FUN(log)(base)); @@ -292,7 +292,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_math_globals, mp_module_math_globals_table const mp_obj_module_t mp_module_math = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_math_globals, + .globals = (mp_obj_dict_t *)&mp_module_math_globals, }; #endif // MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_MATH diff --git a/py/modmicropython.c b/py/modmicropython.c index 7e29825ae4..4cd9160bd0 100644 --- a/py/modmicropython.c +++ b/py/modmicropython.c @@ -70,25 +70,25 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_mem_peak_obj, mp_micropython_mem mp_obj_t mp_micropython_mem_info(size_t n_args, const mp_obj_t *args) { (void)args; -#if MICROPY_MEM_STATS + #if MICROPY_MEM_STATS mp_printf(&mp_plat_print, "mem: total=" UINT_FMT ", current=" UINT_FMT ", peak=" UINT_FMT "\n", (mp_uint_t)m_get_total_bytes_allocated(), (mp_uint_t)m_get_current_bytes_allocated(), (mp_uint_t)m_get_peak_bytes_allocated()); -#endif -#if MICROPY_STACK_CHECK + #endif + #if MICROPY_STACK_CHECK mp_printf(&mp_plat_print, "stack: " UINT_FMT " out of " UINT_FMT "\n", mp_stack_usage(), (mp_uint_t)MP_STATE_THREAD(stack_limit)); -#else + #else mp_printf(&mp_plat_print, "stack: " UINT_FMT "\n", mp_stack_usage()); -#endif -#if MICROPY_ENABLE_GC + #endif + #if MICROPY_ENABLE_GC gc_dump_info(); if (n_args == 1) { // arg given means dump gc allocation table gc_dump_alloc_table(); } -#else + #else (void)n_args; -#endif + #endif return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_micropython_mem_info_obj, 0, 1, mp_micropython_mem_info); @@ -165,21 +165,21 @@ STATIC const mp_rom_map_elem_t mp_module_micropython_globals_table[] = { #if MICROPY_ENABLE_COMPILER { MP_ROM_QSTR(MP_QSTR_opt_level), MP_ROM_PTR(&mp_micropython_opt_level_obj) }, #endif -#if MICROPY_PY_MICROPYTHON_MEM_INFO -#if MICROPY_MEM_STATS + #if MICROPY_PY_MICROPYTHON_MEM_INFO + #if MICROPY_MEM_STATS { MP_ROM_QSTR(MP_QSTR_mem_total), MP_ROM_PTR(&mp_micropython_mem_total_obj) }, { MP_ROM_QSTR(MP_QSTR_mem_current), MP_ROM_PTR(&mp_micropython_mem_current_obj) }, { MP_ROM_QSTR(MP_QSTR_mem_peak), MP_ROM_PTR(&mp_micropython_mem_peak_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_mem_info), MP_ROM_PTR(&mp_micropython_mem_info_obj) }, { MP_ROM_QSTR(MP_QSTR_qstr_info), MP_ROM_PTR(&mp_micropython_qstr_info_obj) }, -#endif + #endif #if MICROPY_PY_MICROPYTHON_STACK_USE { MP_ROM_QSTR(MP_QSTR_stack_use), MP_ROM_PTR(&mp_micropython_stack_use_obj) }, #endif -#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF && (MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE == 0) + #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF && (MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE == 0) { MP_ROM_QSTR(MP_QSTR_alloc_emergency_exception_buf), MP_ROM_PTR(&mp_alloc_emergency_exception_buf_obj) }, -#endif + #endif #if MICROPY_ENABLE_PYSTACK { MP_ROM_QSTR(MP_QSTR_pystack_use), MP_ROM_PTR(&mp_micropython_pystack_use_obj) }, #endif @@ -199,5 +199,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_micropython_globals, mp_module_micropython const mp_obj_module_t mp_module_micropython = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_micropython_globals, + .globals = (mp_obj_dict_t *)&mp_module_micropython_globals, }; diff --git a/py/modstruct.c b/py/modstruct.c index 7675de275d..1c5319608d 100644 --- a/py/modstruct.c +++ b/py/modstruct.c @@ -186,11 +186,11 @@ STATIC void struct_pack_into_internal(mp_obj_t fmt_in, byte *p, size_t n_args, c size_t size; size_t count = calc_size_items(mp_obj_str_get_str(fmt_in), &size); if (count != n_args) { -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE mp_raise_ValueError(NULL); -#else + #else mp_raise_ValueError_varg(translate("pack expected %d items for packing (got %d)"), count, n_args); -#endif + #endif } const char *fmt = mp_obj_str_get_str(fmt_in); char fmt_type = get_fmt_type(&fmt); @@ -229,7 +229,7 @@ STATIC mp_obj_t struct_pack(size_t n_args, const mp_obj_t *args) { mp_int_t size = MP_OBJ_SMALL_INT_VALUE(struct_calcsize(args[0])); vstr_t vstr; vstr_init_len(&vstr, size); - byte *p = (byte*)vstr.buf; + byte *p = (byte *)vstr.buf; memset(p, 0, size); struct_pack_into_internal(args[0], p, n_args - 1, &args[1]); return mp_obj_new_str_from_vstr(&mp_type_bytes, &vstr); @@ -275,7 +275,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_struct_globals, mp_module_struct_globals_t const mp_obj_module_t mp_module_ustruct = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_struct_globals, + .globals = (mp_obj_dict_t *)&mp_module_struct_globals, }; #endif diff --git a/py/modsys.c b/py/modsys.c index 81628683d8..9cbc5e314c 100644 --- a/py/modsys.c +++ b/py/modsys.c @@ -69,9 +69,9 @@ STATIC MP_DEFINE_ATTRTUPLE( mp_sys_implementation_obj, impl_fields, 2, - MP_ROM_QSTR(MP_QSTR_circuitpython), - MP_ROM_PTR(&mp_sys_implementation_version_info_obj) -); + MP_ROM_QSTR(MP_QSTR_circuitpython), + MP_ROM_PTR(&mp_sys_implementation_version_info_obj) + ); #else STATIC const mp_rom_obj_tuple_t mp_sys_implementation_obj = { {&mp_type_tuple}, @@ -207,7 +207,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_sys_globals, mp_module_sys_globals_table); const mp_obj_module_t mp_module_sys = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_sys_globals, + .globals = (mp_obj_dict_t *)&mp_module_sys_globals, }; #endif diff --git a/py/modthread.c b/py/modthread.c index 250756ef27..89b4f3fb66 100644 --- a/py/modthread.c +++ b/py/modthread.c @@ -122,7 +122,7 @@ STATIC MP_DEFINE_CONST_DICT(thread_lock_locals_dict, thread_lock_locals_dict_tab STATIC const mp_obj_type_t mp_type_thread_lock = { { &mp_type_type }, .name = MP_QSTR_lock, - .locals_dict = (mp_obj_dict_t*)&thread_lock_locals_dict, + .locals_dict = (mp_obj_dict_t *)&thread_lock_locals_dict, }; /****************************************************************/ @@ -159,7 +159,7 @@ typedef struct _thread_entry_args_t { STATIC void *thread_entry(void *args_in) { // Execution begins here for a new thread. We do not have the GIL. - thread_entry_args_t *args = (thread_entry_args_t*)args_in; + thread_entry_args_t *args = (thread_entry_args_t *)args_in; mp_state_thread_t ts; mp_thread_set_state(&ts); @@ -195,7 +195,7 @@ STATIC void *thread_entry(void *args_in) { } else { // uncaught exception // check for SystemExit - mp_obj_base_t *exc = (mp_obj_base_t*)nlr.ret_val; + mp_obj_base_t *exc = (mp_obj_base_t *)nlr.ret_val; if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exc->type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) { // swallow exception silently } else { @@ -239,7 +239,7 @@ STATIC mp_obj_t mod_thread_start_new_thread(size_t n_args, const mp_obj_t *args) if (mp_obj_get_type(args[2]) != &mp_type_dict) { mp_raise_TypeError(translate("expecting a dict for keyword args")); } - mp_map_t *map = &((mp_obj_dict_t*)MP_OBJ_TO_PTR(args[2]))->map; + mp_map_t *map = &((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[2]))->map; th_args = m_new_obj_var(thread_entry_args_t, mp_obj_t, pos_args_len + 2 * map->used); th_args->n_kw = map->used; // copy across the keyword arguments @@ -296,7 +296,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_thread_globals, mp_module_thread_globals_t const mp_obj_module_t mp_module_thread = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_thread_globals, + .globals = (mp_obj_dict_t *)&mp_module_thread_globals, }; #endif // MICROPY_PY_THREAD diff --git a/py/moduerrno.c b/py/moduerrno.c index 3928f8cd89..6ead6a8054 100644 --- a/py/moduerrno.c +++ b/py/moduerrno.c @@ -65,9 +65,9 @@ #if MICROPY_PY_UERRNO_ERRORCODE STATIC const mp_rom_map_elem_t errorcode_table[] = { - #define X(e) { MP_ROM_INT(MP_ ## e), MP_ROM_QSTR(MP_QSTR_## e) }, + #define X(e) { MP_ROM_INT(MP_##e), MP_ROM_QSTR(MP_QSTR_##e) }, MICROPY_PY_UERRNO_LIST - #undef X +#undef X }; STATIC const mp_obj_dict_t errorcode_dict = { @@ -78,38 +78,38 @@ STATIC const mp_obj_dict_t errorcode_dict = { .is_ordered = 1, .used = MP_ARRAY_SIZE(errorcode_table), .alloc = MP_ARRAY_SIZE(errorcode_table), - .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)errorcode_table, + .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)errorcode_table, }, }; #endif STATIC const mp_rom_map_elem_t mp_module_uerrno_globals_table[] = { -#if CIRCUITPY + #if CIRCUITPY { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_errno) }, -#else + #else { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_uerrno) }, -#endif + #endif #if MICROPY_PY_UERRNO_ERRORCODE { MP_ROM_QSTR(MP_QSTR_errorcode), MP_ROM_PTR(&errorcode_dict) }, #endif - #define X(e) { MP_ROM_QSTR(MP_QSTR_## e), MP_ROM_INT(MP_ ## e) }, + #define X(e) { MP_ROM_QSTR(MP_QSTR_##e), MP_ROM_INT(MP_##e) }, MICROPY_PY_UERRNO_LIST - #undef X +#undef X }; STATIC MP_DEFINE_CONST_DICT(mp_module_uerrno_globals, mp_module_uerrno_globals_table); const mp_obj_module_t mp_module_uerrno = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_uerrno_globals, + .globals = (mp_obj_dict_t *)&mp_module_uerrno_globals, }; -const char* mp_errno_to_str(mp_obj_t errno_val) { +const char *mp_errno_to_str(mp_obj_t errno_val) { // Otherwise, return the Exxxx string for that error code #if MICROPY_PY_UERRNO_ERRORCODE // We have the errorcode dict so can do a lookup using the hash map - mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP); + mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)&errorcode_dict.map, errno_val, MP_MAP_LOOKUP); if (elem == NULL) { return ""; } else { @@ -126,18 +126,18 @@ const char* mp_errno_to_str(mp_obj_t errno_val) { #endif } -#else //MICROPY_PY_UERRNO +#else // MICROPY_PY_UERRNO -const char* mp_errno_to_str(mp_obj_t errno_val) { +const char *mp_errno_to_str(mp_obj_t errno_val) { int v = MP_OBJ_SMALL_INT_VALUE(errno_val); - #define X(e) if (v == e) return qstr_str(MP_QSTR_ ## e); + #define X(e) if (v == e) return qstr_str(MP_QSTR_##e); MICROPY_PY_UERRNO_LIST - #undef X +#undef X return ""; } -#endif //MICROPY_PY_UERRNO +#endif // MICROPY_PY_UERRNO // For commonly encountered errors, return human readable strings, otherwise try errno name @@ -146,17 +146,35 @@ const char *mp_common_errno_to_str(mp_obj_t errno_val, char *buf, size_t len) { return NULL; } - const compressed_string_t* desc = NULL; + const compressed_string_t *desc = NULL; switch (MP_OBJ_SMALL_INT_VALUE(errno_val)) { - case EPERM: desc = translate("Permission denied"); break; - case ENOENT: desc = translate("No such file/directory"); break; - case EIO: desc = translate("Input/output error"); break; - case EACCES: desc = translate("Permission denied"); break; - case EEXIST: desc = translate("File exists"); break; - case ENODEV: desc = translate("Unsupported operation"); break; - case EINVAL: desc = translate("Invalid argument"); break; - case ENOSPC: desc = translate("No space left on device"); break; - case EROFS: desc = translate("Read-only filesystem"); break; + case EPERM: + desc = translate("Permission denied"); + break; + case ENOENT: + desc = translate("No such file/directory"); + break; + case EIO: + desc = translate("Input/output error"); + break; + case EACCES: + desc = translate("Permission denied"); + break; + case EEXIST: + desc = translate("File exists"); + break; + case ENODEV: + desc = translate("Unsupported operation"); + break; + case EINVAL: + desc = translate("Invalid argument"); + break; + case ENOSPC: + desc = translate("No space left on device"); + break; + case EROFS: + desc = translate("Read-only filesystem"); + break; } if (desc != NULL && decompress_length(desc) <= len) { decompress(desc, buf); diff --git a/py/mpconfig.h b/py/mpconfig.h old mode 100755 new mode 100644 index 1f6f96bd15..043386d7c0 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -512,9 +512,9 @@ #define MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF (0) #endif #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF -# ifndef MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE -# define MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE (0) // 0 - implies dynamic allocation -# endif +#ifndef MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE +#define MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE (0) // 0 - implies dynamic allocation +#endif #endif // Whether to provide the mp_kbd_exception object, and micropython.kbd_intr function @@ -1370,7 +1370,7 @@ typedef double mp_float_t; #elif defined(MP_ENDIANNESS_BIG) #define MP_ENDIANNESS_LITTLE (!MP_ENDIANNESS_BIG) #else - // Endianness not defined by port so try to autodetect it. +// Endianness not defined by port so try to autodetect it. #if defined(__BYTE_ORDER__) #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ #define MP_ENDIANNESS_LITTLE (1) @@ -1433,7 +1433,7 @@ typedef double mp_float_t; #define UINT_FMT "%u" #define INT_FMT "%d" #endif -#endif //INT_FMT +#endif // INT_FMT // Modifier for function which doesn't return #ifndef NORETURN @@ -1476,21 +1476,21 @@ typedef double mp_float_t; #ifndef MP_HTOBE16 #if MP_ENDIANNESS_LITTLE -# define MP_HTOBE16(x) ((uint16_t)( (((x) & 0xff) << 8) | (((x) >> 8) & 0xff) )) -# define MP_BE16TOH(x) MP_HTOBE16(x) +#define MP_HTOBE16(x) ((uint16_t)((((x) & 0xff) << 8) | (((x) >> 8) & 0xff))) +#define MP_BE16TOH(x) MP_HTOBE16(x) #else -# define MP_HTOBE16(x) (x) -# define MP_BE16TOH(x) (x) +#define MP_HTOBE16(x) (x) +#define MP_BE16TOH(x) (x) #endif #endif #ifndef MP_HTOBE32 #if MP_ENDIANNESS_LITTLE -# define MP_HTOBE32(x) ((uint32_t)( (((x) & 0xff) << 24) | (((x) & 0xff00) << 8) | (((x) >> 8) & 0xff00) | (((x) >> 24) & 0xff) )) -# define MP_BE32TOH(x) MP_HTOBE32(x) +#define MP_HTOBE32(x) ((uint32_t)((((x) & 0xff) << 24) | (((x) & 0xff00) << 8) | (((x) >> 8) & 0xff00) | (((x) >> 24) & 0xff))) +#define MP_BE32TOH(x) MP_HTOBE32(x) #else -# define MP_HTOBE32(x) (x) -# define MP_BE32TOH(x) (x) +#define MP_HTOBE32(x) (x) +#define MP_BE32TOH(x) (x) #endif #endif diff --git a/py/mperrno.h b/py/mperrno.h index e339fde852..02c618958a 100644 --- a/py/mperrno.h +++ b/py/mperrno.h @@ -140,7 +140,7 @@ #endif -const char* mp_errno_to_str(mp_obj_t errno_val); +const char *mp_errno_to_str(mp_obj_t errno_val); const char *mp_common_errno_to_str(mp_obj_t errno_val, char *buf, size_t len); #endif // MICROPY_INCLUDED_PY_MPERRNO_H diff --git a/py/mpprint.c b/py/mpprint.c index e814d2ebe5..032ce8e97b 100644 --- a/py/mpprint.c +++ b/py/mpprint.c @@ -269,14 +269,14 @@ int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char // We add the pad in this function, so since the pad goes after // the sign & prefix, we format without a prefix str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size, - x, base, NULL, base_char, comma); + x, base, NULL, base_char, comma); if (*str == '-') { sign = *str++; fmt_size--; } } else { str = mp_obj_int_formatted(&buf, &buf_size, &fmt_size, - x, base, prefix, base_char, comma); + x, base, prefix, base_char, comma); } int spaces_before = 0; @@ -347,8 +347,7 @@ int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, c if (flags & PF_FLAG_SHOW_SIGN) { sign = '+'; - } - else + } else if (flags & PF_FLAG_SPACE_SIGN) { sign = ' '; } @@ -411,14 +410,20 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { int flags = 0; char fill = ' '; while (*fmt != '\0') { - if (*fmt == '-') flags |= PF_FLAG_LEFT_ADJUST; - else if (*fmt == '+') flags |= PF_FLAG_SHOW_SIGN; - else if (*fmt == ' ') flags |= PF_FLAG_SPACE_SIGN; - else if (*fmt == '!') flags |= PF_FLAG_NO_TRAILZ; - else if (*fmt == '0') { + if (*fmt == '-') { + flags |= PF_FLAG_LEFT_ADJUST; + } else if (*fmt == '+') { + flags |= PF_FLAG_SHOW_SIGN; + } else if (*fmt == ' ') { + flags |= PF_FLAG_SPACE_SIGN; + } else if (*fmt == '!') { + flags |= PF_FLAG_NO_TRAILZ; + } else if (*fmt == '0') { flags |= PF_FLAG_PAD_AFTER_SIGN; fill = '0'; - } else break; + } else { + break; + } ++fmt; } @@ -470,26 +475,23 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { chrs += mp_print_strn(print, "false", 5, flags, fill, width); } break; - case 'c': - { + case 'c': { char str = va_arg(args, int); chrs += mp_print_strn(print, &str, 1, flags, fill, width); break; } - case 'q': - { + case 'q': { qstr qst = va_arg(args, qstr); size_t len; - const char *str = (const char*)qstr_data(qst, &len); + const char *str = (const char *)qstr_data(qst, &len); if (prec < 0) { prec = len; } chrs += mp_print_strn(print, str, prec, flags, fill, width); break; } - case 's': - { - const char *str = va_arg(args, const char*); + case 's': { + const char *str = va_arg(args, const char *); #ifndef NDEBUG // With debugging enabled, catch printing of null string pointers if (prec != 0 && str == NULL) { @@ -526,26 +528,25 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { // Use unsigned long int to work on both ILP32 and LP64 systems chrs += mp_print_int(print, va_arg(args, unsigned long int), 0, 16, 'a', flags, fill, width); break; -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'e': case 'E': case 'f': case 'F': case 'g': - case 'G': - { -#if ((MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT) || (MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE)) + case 'G': { + #if ((MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT) || (MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE)) mp_float_t f = va_arg(args, double); chrs += mp_print_float(print, f, *fmt, flags, fill, width, prec); -#else -#error Unknown MICROPY FLOAT IMPL -#endif + #else + #error Unknown MICROPY FLOAT IMPL + #endif break; } -#endif - // Because 'l' is eaten above, another 'l' means %ll. We need to support - // this length specifier for OBJ_REPR_D (64-bit NaN boxing). - // TODO Either enable this unconditionally, or provide a specific config var. + #endif + // Because 'l' is eaten above, another 'l' means %ll. We need to support + // this length specifier for OBJ_REPR_D (64-bit NaN boxing). + // TODO Either enable this unconditionally, or provide a specific config var. #if (MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D) || defined(_WIN64) case 'l': { unsigned long long int arg_value = va_arg(args, unsigned long long int); diff --git a/py/mpprint.h b/py/mpprint.h index 0d12b9a3d0..4458ea883b 100644 --- a/py/mpprint.h +++ b/py/mpprint.h @@ -40,9 +40,9 @@ #define PF_FLAG_SHOW_OCTAL_LETTER (0x200) #if MICROPY_PY_IO && MICROPY_PY_SYS_STDFILES -# define MP_PYTHON_PRINTER &mp_sys_stdout_print +#define MP_PYTHON_PRINTER &mp_sys_stdout_print #else -# define MP_PYTHON_PRINTER &mp_plat_print +#define MP_PYTHON_PRINTER &mp_plat_print #endif typedef void (*mp_print_strn_t)(void *data, const char *str, size_t len); diff --git a/py/mpstate.h b/py/mpstate.h index 32f353528c..139f23cb4f 100644 --- a/py/mpstate.h +++ b/py/mpstate.h @@ -104,7 +104,7 @@ typedef struct _mp_state_mem_t { mp_thread_mutex_t gc_mutex; #endif - void** permanent_pointers; + void **permanent_pointers; } mp_state_mem_t; // This structure hold runtime and VM information. It includes a section @@ -233,7 +233,7 @@ typedef struct _mp_state_thread_t { char *stack_top; #if MICROPY_MAX_STACK_USAGE - char* stack_bottom; + char *stack_bottom; #endif #if MICROPY_STACK_CHECK diff --git a/py/mpthread.h b/py/mpthread.h index 3a6983e9d0..bd023e6279 100644 --- a/py/mpthread.h +++ b/py/mpthread.h @@ -40,7 +40,7 @@ struct _mp_state_thread_t; struct _mp_state_thread_t *mp_thread_get_state(void); void mp_thread_set_state(void *state); -void mp_thread_create(void *(*entry)(void*), void *arg, size_t *stack_size); +void mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size); void mp_thread_start(void); void mp_thread_finish(void); void mp_thread_mutex_init(mp_thread_mutex_t *mutex); diff --git a/py/mpz.c b/py/mpz.c index 41b46f92ff..248d0ec359 100644 --- a/py/mpz.c +++ b/py/mpz.c @@ -60,13 +60,21 @@ STATIC size_t mpn_remove_trailing_zeros(mpz_dig_t *oidig, mpz_dig_t *idig) { assumes i, j are normalised */ STATIC int mpn_cmp(const mpz_dig_t *idig, size_t ilen, const mpz_dig_t *jdig, size_t jlen) { - if (ilen < jlen) { return -1; } - if (ilen > jlen) { return 1; } + if (ilen < jlen) { + return -1; + } + if (ilen > jlen) { + return 1; + } for (idig += ilen, jdig += ilen; ilen > 0; --ilen) { mpz_dbl_dig_signed_t cmp = (mpz_dbl_dig_t)*(--idig) - (mpz_dbl_dig_t)*(--jdig); - if (cmp < 0) { return -1; } - if (cmp > 0) { return 1; } + if (cmp < 0) { + return -1; + } + if (cmp > 0) { + return 1; + } } return 0; @@ -228,7 +236,7 @@ STATIC size_t mpn_and(mpz_dig_t *idig, const mpz_dig_t *jdig, const mpz_dig_t *k can have i, j, k pointing to same memory */ STATIC size_t mpn_and_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen, - mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { + mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { mpz_dig_t *oidig = idig; mpz_dig_t imask = (0 == carryi) ? 0 : DIG_MASK; mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK; @@ -289,7 +297,7 @@ STATIC size_t mpn_or(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const #if MICROPY_OPT_MPZ_BITWISE STATIC size_t mpn_or_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen, - mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { + mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { mpz_dig_t *oidig = idig; mpz_dbl_dig_t carryi = 1; mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK; @@ -319,7 +327,7 @@ STATIC size_t mpn_or_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, co #else STATIC size_t mpn_or_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen, - mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { + mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { mpz_dig_t *oidig = idig; mpz_dig_t imask = (0 == carryi) ? 0 : DIG_MASK; mpz_dig_t jmask = (0 == carryj) ? 0 : DIG_MASK; @@ -378,7 +386,7 @@ STATIC size_t mpn_xor(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const can have i, j, k pointing to same memory */ STATIC size_t mpn_xor_neg(mpz_dig_t *idig, const mpz_dig_t *jdig, size_t jlen, const mpz_dig_t *kdig, size_t klen, - mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { + mpz_dbl_dig_t carryi, mpz_dbl_dig_t carryj, mpz_dbl_dig_t carryk) { mpz_dig_t *oidig = idig; for (; jlen > 0; ++idig, ++jdig) { @@ -775,17 +783,19 @@ void mpz_set_from_ll(mpz_t *z, long long val, bool is_signed) { #if MICROPY_PY_BUILTINS_FLOAT void mpz_set_from_float(mpz_t *z, mp_float_t src) { -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE -typedef uint64_t mp_float_int_t; -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT -typedef uint32_t mp_float_int_t; -#endif + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + typedef uint64_t mp_float_int_t; + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + typedef uint32_t mp_float_int_t; + #endif union { mp_float_t f; #if MP_ENDIANNESS_LITTLE - struct { mp_float_int_t frc:MP_FLOAT_FRAC_BITS, exp:MP_FLOAT_EXP_BITS, sgn:1; } p; + struct { mp_float_int_t frc : MP_FLOAT_FRAC_BITS, exp : MP_FLOAT_EXP_BITS, sgn : 1; + } p; #else - struct { mp_float_int_t sgn:1, exp:MP_FLOAT_EXP_BITS, frc:MP_FLOAT_FRAC_BITS; } p; + struct { mp_float_int_t sgn : 1, exp : MP_FLOAT_EXP_BITS, frc : MP_FLOAT_FRAC_BITS; + } p; #endif } u = {src}; @@ -829,16 +839,16 @@ typedef uint32_t mp_float_int_t; z->dig[dig_ind++] = (frc << shft) & DIG_MASK; frc >>= DIG_SIZE - shft; } -#if DIG_SIZE < (MP_FLOAT_FRAC_BITS + 1) + #if DIG_SIZE < (MP_FLOAT_FRAC_BITS + 1) while (dig_ind != dig_cnt) { z->dig[dig_ind++] = frc & DIG_MASK; frc >>= DIG_SIZE; } -#else + #else if (dig_ind != dig_cnt) { z->dig[dig_ind] = frc; } -#endif + #endif } } } @@ -861,7 +871,7 @@ size_t mpz_set_from_str(mpz_t *z, const char *str, size_t len, bool neg, unsigne z->len = 0; for (; cur < top; ++cur) { // XXX UTF8 next char - //mp_uint_t v = char_to_numeric(cur#); // XXX UTF8 get char + // mp_uint_t v = char_to_numeric(cur#); // XXX UTF8 get char mp_uint_t v = *cur; if ('0' <= v && v <= '9') { v -= '0'; @@ -952,28 +962,48 @@ int mpz_cmp(const mpz_t *z1, const mpz_t *z2) { mp_int_t mpz_cmp_sml_int(const mpz_t *z, mp_int_t sml_int) { mp_int_t cmp; if (z->neg == 0) { - if (sml_int < 0) return 1; - if (sml_int == 0) { - if (z->len == 0) return 0; + if (sml_int < 0) { return 1; } - if (z->len == 0) return -1; - assert(sml_int < (1 << DIG_SIZE)); - if (z->len != 1) return 1; - cmp = z->dig[0] - sml_int; - } else { - if (sml_int > 0) return -1; if (sml_int == 0) { - if (z->len == 0) return 0; + if (z->len == 0) { + return 0; + } + return 1; + } + if (z->len == 0) { return -1; } - if (z->len == 0) return 1; + assert(sml_int < (1 << DIG_SIZE)); + if (z->len != 1) { + return 1; + } + cmp = z->dig[0] - sml_int; + } else { + if (sml_int > 0) { + return -1; + } + if (sml_int == 0) { + if (z->len == 0) { + return 0; + } + return -1; + } + if (z->len == 0) { + return 1; + } assert(sml_int > -(1 << DIG_SIZE)); - if (z->len != 1) return -1; + if (z->len != 1) { + return -1; + } cmp = -z->dig[0] - sml_int; } - if (cmp < 0) return -1; - if (cmp > 0) return 1; + if (cmp < 0) { + return -1; + } + if (cmp > 0) { + return 1; + } return 0; } #endif @@ -1211,7 +1241,7 @@ void mpz_and_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { } else { mpz_need_dig(dest, lhs->len + 1); dest->len = mpn_and_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - lhs->neg == rhs->neg, 0 != lhs->neg, 0 != rhs->neg); + lhs->neg == rhs->neg, 0 != lhs->neg, 0 != rhs->neg); dest->neg = lhs->neg & rhs->neg; } @@ -1219,7 +1249,7 @@ void mpz_and_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg)); dest->len = mpn_and_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - (lhs->neg == rhs->neg) ? lhs->neg : 0, lhs->neg, rhs->neg); + (lhs->neg == rhs->neg) ? lhs->neg : 0, lhs->neg, rhs->neg); dest->neg = lhs->neg & rhs->neg; #endif @@ -1245,7 +1275,7 @@ void mpz_or_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { } else { mpz_need_dig(dest, lhs->len + 1); dest->len = mpn_or_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - 0 != lhs->neg, 0 != rhs->neg); + 0 != lhs->neg, 0 != rhs->neg); dest->neg = 1; } @@ -1253,7 +1283,7 @@ void mpz_or_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg)); dest->len = mpn_or_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - (lhs->neg || rhs->neg), lhs->neg, rhs->neg); + (lhs->neg || rhs->neg), lhs->neg, rhs->neg); dest->neg = lhs->neg | rhs->neg; #endif @@ -1283,7 +1313,7 @@ void mpz_xor_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { } else { mpz_need_dig(dest, lhs->len + 1); dest->len = mpn_xor_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, 1, - 0 == lhs->neg, 0 == rhs->neg); + 0 == lhs->neg, 0 == rhs->neg); dest->neg = 1; } @@ -1291,7 +1321,7 @@ void mpz_xor_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { mpz_need_dig(dest, lhs->len + (lhs->neg || rhs->neg)); dest->len = mpn_xor_neg(dest->dig, lhs->dig, lhs->len, rhs->dig, rhs->len, - (lhs->neg != rhs->neg), 0 == lhs->neg, 0 == rhs->neg); + (lhs->neg != rhs->neg), 0 == lhs->neg, 0 == rhs->neg); dest->neg = lhs->neg ^ rhs->neg; #endif @@ -1380,7 +1410,8 @@ void mpz_pow3_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs, const mpz_t mpz_t *x = mpz_clone(lhs); mpz_t *n = mpz_clone(rhs); - mpz_t quo; mpz_init_zero(&quo); + mpz_t quo; + mpz_init_zero(&quo); while (n->len > 0) { if ((n->dig[0] & 1) != 0) { @@ -1423,7 +1454,8 @@ mpz_t *mpz_gcd(const mpz_t *z1, const mpz_t *z2) { mpz_t *a = mpz_clone(z1); mpz_t *b = mpz_clone(z2); - mpz_t c; mpz_init_zero(&c); + mpz_t c; + mpz_init_zero(&c); a->neg = 0; b->neg = 0; @@ -1434,7 +1466,9 @@ mpz_t *mpz_gcd(const mpz_t *z1, const mpz_t *z2) { mpz_deinit(&c); return b; } - mpz_t *t = a; a = b; b = t; + mpz_t *t = a; + a = b; + b = t; } if (!(b->len >= 2 || (b->len == 1 && b->dig[0] > 1))) { // compute b > 0; could be mpz_cmp_small_int(b, 1) > 0 break; @@ -1501,7 +1535,8 @@ void mpz_divmod_inpl(mpz_t *dest_quo, mpz_t *dest_rem, const mpz_t *lhs, const m if (lhs->neg != rhs->neg) { dest_quo->neg = 1; if (!mpz_is_zero(dest_rem)) { - mpz_t mpzone; mpz_init_from_int(&mpzone, -1); + mpz_t mpzone; + mpz_init_from_int(&mpzone, -1); mpz_add_inpl(dest_quo, dest_quo, &mpzone); mpz_add_inpl(dest_rem, dest_rem, rhs); } @@ -1516,7 +1551,8 @@ these functions are unused */ mpz_t *mpz_div(const mpz_t *lhs, const mpz_t *rhs) { mpz_t *quo = mpz_zero(); - mpz_t rem; mpz_init_zero(&rem); + mpz_t rem; + mpz_init_zero(&rem); mpz_divmod_inpl(quo, &rem, lhs, rhs); mpz_deinit(&rem); return quo; @@ -1526,7 +1562,8 @@ mpz_t *mpz_div(const mpz_t *lhs, const mpz_t *rhs) { can have lhs, rhs the same */ mpz_t *mpz_mod(const mpz_t *lhs, const mpz_t *rhs) { - mpz_t quo; mpz_init_zero(&quo); + mpz_t quo; + mpz_init_zero(&quo); mpz_t *rem = mpz_zero(); mpz_divmod_inpl(&quo, rem, lhs, rhs); mpz_deinit(&quo); @@ -1663,8 +1700,9 @@ size_t mpz_as_str_inpl(const mpz_t *i, unsigned int base, const char *prefix, ch char *s = str; if (ilen == 0) { if (prefix) { - while (*prefix) + while (*prefix) { *s++ = *prefix++; + } } *s++ = '0'; *s = '\0'; diff --git a/py/mpz.h b/py/mpz.h index ade04a4f7c..6b941cb7b9 100644 --- a/py/mpz.h +++ b/py/mpz.h @@ -46,10 +46,10 @@ #ifndef MPZ_DIG_SIZE #if defined(__x86_64__) || defined(_WIN64) - // 64-bit machine, using 32-bit storage for digits +// 64-bit machine, using 32-bit storage for digits #define MPZ_DIG_SIZE (32) #else - // default: 32-bit machine, using 16-bit storage for digits +// default: 32-bit machine, using 16-bit storage for digits #define MPZ_DIG_SIZE (16) #endif #endif @@ -99,7 +99,7 @@ typedef struct _mpz_t { } mpz_t; // convenience macro to declare an mpz with a digit array from the stack, initialised by an integer -#define MPZ_CONST_INT(z, val) mpz_t z; mpz_dig_t z ## _digits[MPZ_NUM_DIG_FOR_INT]; mpz_init_fixed_from_int(&z, z_digits, MPZ_NUM_DIG_FOR_INT, val); +#define MPZ_CONST_INT(z, val) mpz_t z; mpz_dig_t z##_digits[MPZ_NUM_DIG_FOR_INT]; mpz_init_fixed_from_int(&z, z_digits, MPZ_NUM_DIG_FOR_INT, val); void mpz_init_zero(mpz_t *z); void mpz_init_from_int(mpz_t *z, mp_int_t val); @@ -115,8 +115,12 @@ void mpz_set_from_float(mpz_t *z, mp_float_t src); size_t mpz_set_from_str(mpz_t *z, const char *str, size_t len, bool neg, unsigned int base); void mpz_set_from_bytes(mpz_t *z, bool big_endian, size_t len, const byte *buf); -static inline bool mpz_is_zero(const mpz_t *z) { return z->len == 0; } -static inline bool mpz_is_neg(const mpz_t *z) { return z->len != 0 && z->neg != 0; } +static inline bool mpz_is_zero(const mpz_t *z) { + return z->len == 0; +} +static inline bool mpz_is_neg(const mpz_t *z) { + return z->len != 0 && z->neg != 0; +} int mpz_cmp(const mpz_t *lhs, const mpz_t *rhs); void mpz_abs_inpl(mpz_t *dest, const mpz_t *z); @@ -134,10 +138,13 @@ void mpz_or_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs); void mpz_xor_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs); void mpz_divmod_inpl(mpz_t *dest_quo, mpz_t *dest_rem, const mpz_t *lhs, const mpz_t *rhs); -static inline size_t mpz_max_num_bits(const mpz_t *z) { return z->len * MPZ_DIG_SIZE; } +static inline size_t mpz_max_num_bits(const mpz_t *z) { + return z->len * MPZ_DIG_SIZE; +} static inline size_t mpz_num_bits(const mpz_t *z) { - size_t last_bits = (8 * (sizeof(long) - sizeof(mpz_dig_t))) - __builtin_clzl(z->dig[z->len-1]); - return z->len * MPZ_DIG_SIZE + last_bits; } + size_t last_bits = (8 * (sizeof(long) - sizeof(mpz_dig_t))) - __builtin_clzl(z->dig[z->len - 1]); + return z->len * MPZ_DIG_SIZE + last_bits; +} mp_int_t mpz_hash(const mpz_t *z); bool mpz_as_int_checked(const mpz_t *z, mp_int_t *value); bool mpz_as_uint_checked(const mpz_t *z, mp_uint_t *value); diff --git a/py/nativeglue.c b/py/nativeglue.c index 9ac8060097..05e257ab02 100644 --- a/py/nativeglue.c +++ b/py/nativeglue.c @@ -45,10 +45,12 @@ mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type) { DEBUG_printf("mp_convert_obj_to_native(%p, " UINT_FMT ")\n", obj, type); switch (type & 0xf) { - case MP_NATIVE_TYPE_OBJ: return (mp_uint_t)obj; + case MP_NATIVE_TYPE_OBJ: + return (mp_uint_t)obj; case MP_NATIVE_TYPE_BOOL: case MP_NATIVE_TYPE_INT: - case MP_NATIVE_TYPE_UINT: return mp_obj_get_int_truncated(obj); + case MP_NATIVE_TYPE_UINT: + return mp_obj_get_int_truncated(obj); default: { // cast obj to a pointer mp_buffer_info_t bufinfo; if (mp_get_buffer(obj, &bufinfo, MP_BUFFER_RW)) { @@ -69,10 +71,14 @@ mp_uint_t mp_convert_obj_to_native(mp_obj_t obj, mp_uint_t type) { mp_obj_t mp_convert_native_to_obj(mp_uint_t val, mp_uint_t type) { DEBUG_printf("mp_convert_native_to_obj(" UINT_FMT ", " UINT_FMT ")\n", val, type); switch (type & 0xf) { - case MP_NATIVE_TYPE_OBJ: return (mp_obj_t)val; - case MP_NATIVE_TYPE_BOOL: return mp_obj_new_bool(val); - case MP_NATIVE_TYPE_INT: return mp_obj_new_int(val); - case MP_NATIVE_TYPE_UINT: return mp_obj_new_int_from_uint(val); + case MP_NATIVE_TYPE_OBJ: + return (mp_obj_t)val; + case MP_NATIVE_TYPE_BOOL: + return mp_obj_new_bool(val); + case MP_NATIVE_TYPE_INT: + return mp_obj_new_int(val); + case MP_NATIVE_TYPE_UINT: + return mp_obj_new_int_from_uint(val); default: // a pointer // we return just the value of the pointer as an integer return mp_obj_new_int_from_uint(val); @@ -145,10 +151,10 @@ void *const mp_fun_table[MP_F_NUMBER_OF] = { mp_obj_list_append, mp_obj_new_dict, mp_obj_dict_store, -#if MICROPY_PY_BUILTINS_SET + #if MICROPY_PY_BUILTINS_SET mp_obj_set_store, mp_obj_new_set, -#endif + #endif mp_make_function_from_raw_code, mp_native_call_function_n_kw, mp_call_method_n_kw, @@ -161,9 +167,9 @@ void *const mp_fun_table[MP_F_NUMBER_OF] = { mp_import_name, mp_import_from, mp_import_all, -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE mp_obj_new_slice, -#endif + #endif mp_unpack_sequence, mp_unpack_ex, mp_delete_name, diff --git a/py/nlr.c b/py/nlr.c index 95d833177d..6dfd162196 100644 --- a/py/nlr.c +++ b/py/nlr.c @@ -30,7 +30,7 @@ // When not using setjmp, nlr_push_tail is called from inline asm so needs special care #if defined(MICROPY_NLR_X86) && MICROPY_NLR_X86 && defined(MICROPY_NLR_OS_WINDOWS) && MICROPY_NLR_OS_WINDOWS // On these 32-bit platforms make sure nlr_push_tail doesn't have a leading underscore -unsigned int nlr_push_tail(nlr_buf_t *nlr) asm("nlr_push_tail"); +unsigned int nlr_push_tail(nlr_buf_t *nlr) asm ("nlr_push_tail"); #else // LTO can't see inside inline asm functions so explicitly mark nlr_push_tail as used __attribute__((used)) unsigned int nlr_push_tail(nlr_buf_t *nlr); diff --git a/py/nlr.h b/py/nlr.h index aed24e277a..00f10b75fd 100644 --- a/py/nlr.h +++ b/py/nlr.h @@ -57,9 +57,9 @@ #if defined(__SOFTFP__) #define MICROPY_NLR_NUM_REGS (10) #else - // With hardware FP registers s16-s31 are callee save so in principle - // should be saved and restored by the NLR code. gcc only uses s16-s21 - // so only save/restore those as an optimisation. +// With hardware FP registers s16-s31 are callee save so in principle +// should be saved and restored by the NLR code. gcc only uses s16-s21 +// so only save/restore those as an optimisation. #define MICROPY_NLR_NUM_REGS (10 + 6) #endif #elif defined(__xtensa__) @@ -67,7 +67,7 @@ #define MICROPY_NLR_NUM_REGS (10) #else #define MICROPY_NLR_SETJMP (1) - //#warning "No native NLR support for this arch, using setjmp implementation" +// #warning "No native NLR support for this arch, using setjmp implementation" #endif #endif diff --git a/py/nlrthumb.c b/py/nlrthumb.c index 464995fa88..1cdc2f063c 100644 --- a/py/nlrthumb.c +++ b/py/nlrthumb.c @@ -39,53 +39,53 @@ __attribute__((naked)) unsigned int nlr_push(nlr_buf_t *nlr) { __asm volatile ( - "str r4, [r0, #12] \n" // store r4 into nlr_buf - "str r5, [r0, #16] \n" // store r5 into nlr_buf - "str r6, [r0, #20] \n" // store r6 into nlr_buf - "str r7, [r0, #24] \n" // store r7 into nlr_buf + "str r4, [r0, #12] \n" // store r4 into nlr_buf + "str r5, [r0, #16] \n" // store r5 into nlr_buf + "str r6, [r0, #20] \n" // store r6 into nlr_buf + "str r7, [r0, #24] \n" // store r7 into nlr_buf -#if defined(__ARM_ARCH_6M__) - "mov r1, r8 \n" - "str r1, [r0, #28] \n" // store r8 into nlr_buf - "mov r1, r9 \n" - "str r1, [r0, #32] \n" // store r9 into nlr_buf - "mov r1, r10 \n" - "str r1, [r0, #36] \n" // store r10 into nlr_buf - "mov r1, r11 \n" - "str r1, [r0, #40] \n" // store r11 into nlr_buf - "mov r1, r13 \n" - "str r1, [r0, #44] \n" // store r13=sp into nlr_buf - "mov r1, lr \n" - "str r1, [r0, #8] \n" // store lr into nlr_buf -#else - "str r8, [r0, #28] \n" // store r8 into nlr_buf - "str r9, [r0, #32] \n" // store r9 into nlr_buf - "str r10, [r0, #36] \n" // store r10 into nlr_buf - "str r11, [r0, #40] \n" // store r11 into nlr_buf - "str r13, [r0, #44] \n" // store r13=sp into nlr_buf - #if MICROPY_NLR_NUM_REGS == 16 - "vstr d8, [r0, #48] \n" // store s16-s17 into nlr_buf - "vstr d9, [r0, #56] \n" // store s18-s19 into nlr_buf - "vstr d10, [r0, #64] \n" // store s20-s21 into nlr_buf - #endif - "str lr, [r0, #8] \n" // store lr into nlr_buf -#endif + #if defined(__ARM_ARCH_6M__) + "mov r1, r8 \n" + "str r1, [r0, #28] \n" // store r8 into nlr_buf + "mov r1, r9 \n" + "str r1, [r0, #32] \n" // store r9 into nlr_buf + "mov r1, r10 \n" + "str r1, [r0, #36] \n" // store r10 into nlr_buf + "mov r1, r11 \n" + "str r1, [r0, #40] \n" // store r11 into nlr_buf + "mov r1, r13 \n" + "str r1, [r0, #44] \n" // store r13=sp into nlr_buf + "mov r1, lr \n" + "str r1, [r0, #8] \n" // store lr into nlr_buf + #else + "str r8, [r0, #28] \n" // store r8 into nlr_buf + "str r9, [r0, #32] \n" // store r9 into nlr_buf + "str r10, [r0, #36] \n" // store r10 into nlr_buf + "str r11, [r0, #40] \n" // store r11 into nlr_buf + "str r13, [r0, #44] \n" // store r13=sp into nlr_buf + #if MICROPY_NLR_NUM_REGS == 16 + "vstr d8, [r0, #48] \n" // store s16-s17 into nlr_buf + "vstr d9, [r0, #56] \n" // store s18-s19 into nlr_buf + "vstr d10, [r0, #64] \n" // store s20-s21 into nlr_buf + #endif + "str lr, [r0, #8] \n" // store lr into nlr_buf + #endif -#if defined(__ARM_ARCH_6M__) - "ldr r1, nlr_push_tail_var \n" - "bx r1 \n" // do the rest in C - ".align 2 \n" - "nlr_push_tail_var: .word nlr_push_tail \n" -#else - "b nlr_push_tail \n" // do the rest in C -#endif - : // output operands - : "r" (nlr) // input operands - // Do not use r1, r2, r3 as temporary saving registers. - // gcc 7.2.1 started doing this, and r3 got clobbered in nlr_push_tail. - // See https://github.com/adafruit/circuitpython/issues/500 for details. - : "r1", "r2", "r3" // clobbers - ); + #if defined(__ARM_ARCH_6M__) + "ldr r1, nlr_push_tail_var \n" + "bx r1 \n" // do the rest in C + ".align 2 \n" + "nlr_push_tail_var: .word nlr_push_tail \n" + #else + "b nlr_push_tail \n" // do the rest in C + #endif + : // output operands + : "r" (nlr) // input operands + // Do not use r1, r2, r3 as temporary saving registers. + // gcc 7.2.1 started doing this, and r3 got clobbered in nlr_push_tail. + // See https://github.com/adafruit/circuitpython/issues/500 for details. + : "r1", "r2", "r3" // clobbers + ); #if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)) // Older versions of gcc give an error when naked functions don't return a value @@ -98,44 +98,44 @@ NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( - "mov r0, %0 \n" // r0 points to nlr_buf - "ldr r4, [r0, #12] \n" // load r4 from nlr_buf - "ldr r5, [r0, #16] \n" // load r5 from nlr_buf - "ldr r6, [r0, #20] \n" // load r6 from nlr_buf - "ldr r7, [r0, #24] \n" // load r7 from nlr_buf + "mov r0, %0 \n" // r0 points to nlr_buf + "ldr r4, [r0, #12] \n" // load r4 from nlr_buf + "ldr r5, [r0, #16] \n" // load r5 from nlr_buf + "ldr r6, [r0, #20] \n" // load r6 from nlr_buf + "ldr r7, [r0, #24] \n" // load r7 from nlr_buf -#if defined(__ARM_ARCH_6M__) - "ldr r1, [r0, #28] \n" // load r8 from nlr_buf - "mov r8, r1 \n" - "ldr r1, [r0, #32] \n" // load r9 from nlr_buf - "mov r9, r1 \n" - "ldr r1, [r0, #36] \n" // load r10 from nlr_buf - "mov r10, r1 \n" - "ldr r1, [r0, #40] \n" // load r11 from nlr_buf - "mov r11, r1 \n" - "ldr r1, [r0, #44] \n" // load r13=sp from nlr_buf - "mov r13, r1 \n" - "ldr r1, [r0, #8] \n" // load lr from nlr_buf - "mov lr, r1 \n" -#else - "ldr r8, [r0, #28] \n" // load r8 from nlr_buf - "ldr r9, [r0, #32] \n" // load r9 from nlr_buf - "ldr r10, [r0, #36] \n" // load r10 from nlr_buf - "ldr r11, [r0, #40] \n" // load r11 from nlr_buf - "ldr r13, [r0, #44] \n" // load r13=sp from nlr_buf - #if MICROPY_NLR_NUM_REGS == 16 - "vldr d8, [r0, #48] \n" // load s16-s17 from nlr_buf - "vldr d9, [r0, #56] \n" // load s18-s19 from nlr_buf - "vldr d10, [r0, #64] \n" // load s20-s21 from nlr_buf - #endif - "ldr lr, [r0, #8] \n" // load lr from nlr_buf -#endif - "movs r0, #1 \n" // return 1, non-local return - "bx lr \n" // return - : // output operands - : "r"(top) // input operands - : // clobbered registers - ); + #if defined(__ARM_ARCH_6M__) + "ldr r1, [r0, #28] \n" // load r8 from nlr_buf + "mov r8, r1 \n" + "ldr r1, [r0, #32] \n" // load r9 from nlr_buf + "mov r9, r1 \n" + "ldr r1, [r0, #36] \n" // load r10 from nlr_buf + "mov r10, r1 \n" + "ldr r1, [r0, #40] \n" // load r11 from nlr_buf + "mov r11, r1 \n" + "ldr r1, [r0, #44] \n" // load r13=sp from nlr_buf + "mov r13, r1 \n" + "ldr r1, [r0, #8] \n" // load lr from nlr_buf + "mov lr, r1 \n" + #else + "ldr r8, [r0, #28] \n" // load r8 from nlr_buf + "ldr r9, [r0, #32] \n" // load r9 from nlr_buf + "ldr r10, [r0, #36] \n" // load r10 from nlr_buf + "ldr r11, [r0, #40] \n" // load r11 from nlr_buf + "ldr r13, [r0, #44] \n" // load r13=sp from nlr_buf + #if MICROPY_NLR_NUM_REGS == 16 + "vldr d8, [r0, #48] \n" // load s16-s17 from nlr_buf + "vldr d9, [r0, #56] \n" // load s18-s19 from nlr_buf + "vldr d10, [r0, #64] \n" // load s20-s21 from nlr_buf + #endif + "ldr lr, [r0, #8] \n" // load lr from nlr_buf + #endif + "movs r0, #1 \n" // return 1, non-local return + "bx lr \n" // return + : // output operands + : "r" (top) // input operands + : // clobbered registers + ); MP_UNREACHABLE } diff --git a/py/nlrx64.c b/py/nlrx64.c index 246d6a95b8..d9ef0d8138 100644 --- a/py/nlrx64.c +++ b/py/nlrx64.c @@ -41,41 +41,41 @@ unsigned int nlr_push(nlr_buf_t *nlr) { #if MICROPY_NLR_OS_WINDOWS __asm volatile ( - "movq (%rsp), %rax \n" // load return %rip - "movq %rax, 16(%rcx) \n" // store %rip into nlr_buf - "movq %rbp, 24(%rcx) \n" // store %rbp into nlr_buf - "movq %rsp, 32(%rcx) \n" // store %rsp into nlr_buf - "movq %rbx, 40(%rcx) \n" // store %rbx into nlr_buf - "movq %r12, 48(%rcx) \n" // store %r12 into nlr_buf - "movq %r13, 56(%rcx) \n" // store %r13 into nlr_buf - "movq %r14, 64(%rcx) \n" // store %r14 into nlr_buf - "movq %r15, 72(%rcx) \n" // store %r15 into nlr_buf - "movq %rdi, 80(%rcx) \n" // store %rdr into nlr_buf - "movq %rsi, 88(%rcx) \n" // store %rsi into nlr_buf - "jmp nlr_push_tail \n" // do the rest in C - ); + "movq (%rsp), %rax \n" // load return %rip + "movq %rax, 16(%rcx) \n" // store %rip into nlr_buf + "movq %rbp, 24(%rcx) \n" // store %rbp into nlr_buf + "movq %rsp, 32(%rcx) \n" // store %rsp into nlr_buf + "movq %rbx, 40(%rcx) \n" // store %rbx into nlr_buf + "movq %r12, 48(%rcx) \n" // store %r12 into nlr_buf + "movq %r13, 56(%rcx) \n" // store %r13 into nlr_buf + "movq %r14, 64(%rcx) \n" // store %r14 into nlr_buf + "movq %r15, 72(%rcx) \n" // store %r15 into nlr_buf + "movq %rdi, 80(%rcx) \n" // store %rdr into nlr_buf + "movq %rsi, 88(%rcx) \n" // store %rsi into nlr_buf + "jmp nlr_push_tail \n" // do the rest in C + ); #else __asm volatile ( - #if defined(__APPLE__) || defined(__MACH__) - "pop %rbp \n" // undo function's prelude - #endif - "movq (%rsp), %rax \n" // load return %rip - "movq %rax, 16(%rdi) \n" // store %rip into nlr_buf - "movq %rbp, 24(%rdi) \n" // store %rbp into nlr_buf - "movq %rsp, 32(%rdi) \n" // store %rsp into nlr_buf - "movq %rbx, 40(%rdi) \n" // store %rbx into nlr_buf - "movq %r12, 48(%rdi) \n" // store %r12 into nlr_buf - "movq %r13, 56(%rdi) \n" // store %r13 into nlr_buf - "movq %r14, 64(%rdi) \n" // store %r14 into nlr_buf - "movq %r15, 72(%rdi) \n" // store %r15 into nlr_buf - #if defined(__APPLE__) || defined(__MACH__) - "jmp _nlr_push_tail \n" // do the rest in C - #else - "jmp nlr_push_tail \n" // do the rest in C - #endif - ); + #if defined(__APPLE__) || defined(__MACH__) + "pop %rbp \n" // undo function's prelude + #endif + "movq (%rsp), %rax \n" // load return %rip + "movq %rax, 16(%rdi) \n" // store %rip into nlr_buf + "movq %rbp, 24(%rdi) \n" // store %rbp into nlr_buf + "movq %rsp, 32(%rdi) \n" // store %rsp into nlr_buf + "movq %rbx, 40(%rdi) \n" // store %rbx into nlr_buf + "movq %r12, 48(%rdi) \n" // store %r12 into nlr_buf + "movq %r13, 56(%rdi) \n" // store %r13 into nlr_buf + "movq %r14, 64(%rdi) \n" // store %r14 into nlr_buf + "movq %r15, 72(%rdi) \n" // store %r15 into nlr_buf + #if defined(__APPLE__) || defined(__MACH__) + "jmp _nlr_push_tail \n" // do the rest in C + #else + "jmp nlr_push_tail \n" // do the rest in C + #endif + ); #endif @@ -86,27 +86,27 @@ NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( - "movq %0, %%rcx \n" // %rcx points to nlr_buf - #if MICROPY_NLR_OS_WINDOWS - "movq 88(%%rcx), %%rsi \n" // load saved %rsi - "movq 80(%%rcx), %%rdi \n" // load saved %rdr - #endif - "movq 72(%%rcx), %%r15 \n" // load saved %r15 - "movq 64(%%rcx), %%r14 \n" // load saved %r14 - "movq 56(%%rcx), %%r13 \n" // load saved %r13 - "movq 48(%%rcx), %%r12 \n" // load saved %r12 - "movq 40(%%rcx), %%rbx \n" // load saved %rbx - "movq 32(%%rcx), %%rsp \n" // load saved %rsp - "movq 24(%%rcx), %%rbp \n" // load saved %rbp - "movq 16(%%rcx), %%rax \n" // load saved %rip - "movq %%rax, (%%rsp) \n" // store saved %rip to stack - "xorq %%rax, %%rax \n" // clear return register - "inc %%al \n" // increase to make 1, non-local return - "ret \n" // return - : // output operands - : "r"(top) // input operands - : // clobbered registers - ); + "movq %0, %%rcx \n" // %rcx points to nlr_buf + #if MICROPY_NLR_OS_WINDOWS + "movq 88(%%rcx), %%rsi \n" // load saved %rsi + "movq 80(%%rcx), %%rdi \n" // load saved %rdr + #endif + "movq 72(%%rcx), %%r15 \n" // load saved %r15 + "movq 64(%%rcx), %%r14 \n" // load saved %r14 + "movq 56(%%rcx), %%r13 \n" // load saved %r13 + "movq 48(%%rcx), %%r12 \n" // load saved %r12 + "movq 40(%%rcx), %%rbx \n" // load saved %rbx + "movq 32(%%rcx), %%rsp \n" // load saved %rsp + "movq 24(%%rcx), %%rbp \n" // load saved %rbp + "movq 16(%%rcx), %%rax \n" // load saved %rip + "movq %%rax, (%%rsp) \n" // store saved %rip to stack + "xorq %%rax, %%rax \n" // clear return register + "inc %%al \n" // increase to make 1, non-local return + "ret \n" // return + : // output operands + : "r" (top) // input operands + : // clobbered registers + ); MP_UNREACHABLE } diff --git a/py/nlrx86.c b/py/nlrx86.c index 18306253d7..598b199c29 100644 --- a/py/nlrx86.c +++ b/py/nlrx86.c @@ -34,7 +34,7 @@ // ebx, esi, edi, ebp, esp, eip #if defined(MICROPY_NLR_OS_WINDOWS) && MICROPY_NLR_OS_WINDOWS -unsigned int nlr_push_tail(nlr_buf_t *nlr) asm("nlr_push_tail"); +unsigned int nlr_push_tail(nlr_buf_t *nlr) asm ("nlr_push_tail"); #else __attribute__((used)) unsigned int nlr_push_tail(nlr_buf_t *nlr); #endif @@ -61,19 +61,19 @@ unsigned int nlr_push(nlr_buf_t *nlr) { #endif __asm volatile ( - #if UNDO_PRELUDE - "pop %ebp \n" // undo function's prelude - #endif - "mov 4(%esp), %edx \n" // load nlr_buf - "mov (%esp), %eax \n" // load return %eip - "mov %eax, 8(%edx) \n" // store %eip into nlr_buf - "mov %ebp, 12(%edx) \n" // store %ebp into nlr_buf - "mov %esp, 16(%edx) \n" // store %esp into nlr_buf - "mov %ebx, 20(%edx) \n" // store %ebx into nlr_buf - "mov %edi, 24(%edx) \n" // store %edi into nlr_buf - "mov %esi, 28(%edx) \n" // store %esi into nlr_buf - "jmp nlr_push_tail \n" // do the rest in C - ); + #if UNDO_PRELUDE + "pop %ebp \n" // undo function's prelude + #endif + "mov 4(%esp), %edx \n" // load nlr_buf + "mov (%esp), %eax \n" // load return %eip + "mov %eax, 8(%edx) \n" // store %eip into nlr_buf + "mov %ebp, 12(%edx) \n" // store %ebp into nlr_buf + "mov %esp, 16(%edx) \n" // store %esp into nlr_buf + "mov %ebx, 20(%edx) \n" // store %ebx into nlr_buf + "mov %edi, 24(%edx) \n" // store %edi into nlr_buf + "mov %esi, 28(%edx) \n" // store %esi into nlr_buf + "jmp nlr_push_tail \n" // do the rest in C + ); #if !USE_NAKED return 0; // needed to silence compiler warning @@ -84,21 +84,21 @@ NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( - "mov %0, %%edx \n" // %edx points to nlr_buf - "mov 28(%%edx), %%esi \n" // load saved %esi - "mov 24(%%edx), %%edi \n" // load saved %edi - "mov 20(%%edx), %%ebx \n" // load saved %ebx - "mov 16(%%edx), %%esp \n" // load saved %esp - "mov 12(%%edx), %%ebp \n" // load saved %ebp - "mov 8(%%edx), %%eax \n" // load saved %eip - "mov %%eax, (%%esp) \n" // store saved %eip to stack - "xor %%eax, %%eax \n" // clear return register - "inc %%al \n" // increase to make 1, non-local return - "ret \n" // return - : // output operands - : "r"(top) // input operands - : // clobbered registers - ); + "mov %0, %%edx \n" // %edx points to nlr_buf + "mov 28(%%edx), %%esi \n" // load saved %esi + "mov 24(%%edx), %%edi \n" // load saved %edi + "mov 20(%%edx), %%ebx \n" // load saved %ebx + "mov 16(%%edx), %%esp \n" // load saved %esp + "mov 12(%%edx), %%ebp \n" // load saved %ebp + "mov 8(%%edx), %%eax \n" // load saved %eip + "mov %%eax, (%%esp) \n" // store saved %eip to stack + "xor %%eax, %%eax \n" // clear return register + "inc %%al \n" // increase to make 1, non-local return + "ret \n" // return + : // output operands + : "r" (top) // input operands + : // clobbered registers + ); MP_UNREACHABLE } diff --git a/py/nlrxtensa.c b/py/nlrxtensa.c index e04535ff83..5aa767aaeb 100644 --- a/py/nlrxtensa.c +++ b/py/nlrxtensa.c @@ -39,18 +39,18 @@ unsigned int nlr_push(nlr_buf_t *nlr) { __asm volatile ( - "s32i.n a0, a2, 8 \n" // save regs... - "s32i.n a1, a2, 12 \n" - "s32i.n a8, a2, 16 \n" - "s32i.n a9, a2, 20 \n" - "s32i.n a10, a2, 24 \n" - "s32i.n a11, a2, 28 \n" - "s32i.n a12, a2, 32 \n" - "s32i.n a13, a2, 36 \n" - "s32i.n a14, a2, 40 \n" - "s32i.n a15, a2, 44 \n" - "j nlr_push_tail \n" // do the rest in C - ); + "s32i.n a0, a2, 8 \n" // save regs... + "s32i.n a1, a2, 12 \n" + "s32i.n a8, a2, 16 \n" + "s32i.n a9, a2, 20 \n" + "s32i.n a10, a2, 24 \n" + "s32i.n a11, a2, 28 \n" + "s32i.n a12, a2, 32 \n" + "s32i.n a13, a2, 36 \n" + "s32i.n a14, a2, 40 \n" + "s32i.n a15, a2, 44 \n" + "j nlr_push_tail \n" // do the rest in C + ); return 0; // needed to silence compiler warning } @@ -59,23 +59,23 @@ NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( - "mov.n a2, %0 \n" // a2 points to nlr_buf - "l32i.n a0, a2, 8 \n" // restore regs... - "l32i.n a1, a2, 12 \n" - "l32i.n a8, a2, 16 \n" - "l32i.n a9, a2, 20 \n" - "l32i.n a10, a2, 24 \n" - "l32i.n a11, a2, 28 \n" - "l32i.n a12, a2, 32 \n" - "l32i.n a13, a2, 36 \n" - "l32i.n a14, a2, 40 \n" - "l32i.n a15, a2, 44 \n" - "movi.n a2, 1 \n" // return 1, non-local return - "ret.n \n" // return - : // output operands - : "r"(top) // input operands - : // clobbered registers - ); + "mov.n a2, %0 \n" // a2 points to nlr_buf + "l32i.n a0, a2, 8 \n" // restore regs... + "l32i.n a1, a2, 12 \n" + "l32i.n a8, a2, 16 \n" + "l32i.n a9, a2, 20 \n" + "l32i.n a10, a2, 24 \n" + "l32i.n a11, a2, 28 \n" + "l32i.n a12, a2, 32 \n" + "l32i.n a13, a2, 36 \n" + "l32i.n a14, a2, 40 \n" + "l32i.n a15, a2, 44 \n" + "movi.n a2, 1 \n" // return 1, non-local return + "ret.n \n" // return + : // output operands + : "r" (top) // input operands + : // clobbered registers + ); MP_UNREACHABLE } diff --git a/py/obj.c b/py/obj.c index 5f19089e85..b271362536 100644 --- a/py/obj.c +++ b/py/obj.c @@ -45,16 +45,16 @@ mp_obj_type_t *mp_obj_get_type(mp_const_obj_t o_in) { if (MP_OBJ_IS_SMALL_INT(o_in)) { - return (mp_obj_type_t*)&mp_type_int; + return (mp_obj_type_t *)&mp_type_int; } else if (MP_OBJ_IS_QSTR(o_in)) { - return (mp_obj_type_t*)&mp_type_str; + return (mp_obj_type_t *)&mp_type_str; #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(o_in)) { - return (mp_obj_type_t*)&mp_type_float; + return (mp_obj_type_t *)&mp_type_float; #endif } else { const mp_obj_base_t *o = MP_OBJ_TO_PTR(o_in); - return (mp_obj_type_t*)o->type; + return (mp_obj_type_t *)o->type; } } @@ -75,15 +75,15 @@ void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t } #endif -#ifndef NDEBUG + #ifndef NDEBUG if (o_in == MP_OBJ_NULL) { mp_print_str(print, "(nil)"); return; } -#endif + #endif mp_obj_type_t *type = mp_obj_get_type(o_in); if (type->print != NULL) { - type->print((mp_print_t*)print, o_in, kind); + type->print((mp_print_t *)print, o_in, kind); } else { mp_printf(print, "<%q>", type->name); } @@ -101,28 +101,28 @@ void mp_obj_print_exception(const mp_print_t *print, mp_obj_t exc) { if (n > 0) { assert(n % 3 == 0); // Decompress the format strings - const compressed_string_t* traceback = translate("Traceback (most recent call last):\n"); + const compressed_string_t *traceback = translate("Traceback (most recent call last):\n"); char decompressed[decompress_length(traceback)]; decompress(traceback, decompressed); -#if MICROPY_ENABLE_SOURCE_LINE - const compressed_string_t* frame = translate(" File \"%q\", line %d"); -#else - const compressed_string_t* frame = translate(" File \"%q\""); -#endif + #if MICROPY_ENABLE_SOURCE_LINE + const compressed_string_t *frame = translate(" File \"%q\", line %d"); + #else + const compressed_string_t *frame = translate(" File \"%q\""); + #endif char decompressed_frame[decompress_length(frame)]; decompress(frame, decompressed_frame); - const compressed_string_t* block_fmt = translate(", in %q\n"); + const compressed_string_t *block_fmt = translate(", in %q\n"); char decompressed_block[decompress_length(block_fmt)]; decompress(block_fmt, decompressed_block); // Print the traceback mp_print_str(print, decompressed); for (int i = n - 3; i >= 0; i -= 3) { -#if MICROPY_ENABLE_SOURCE_LINE + #if MICROPY_ENABLE_SOURCE_LINE mp_printf(print, decompressed_frame, values[i], (int)values[i + 1]); -#else + #else mp_printf(print, decompressed_frame, values[i]); -#endif + #endif // the block name can be NULL if it's unknown qstr block = values[i + 2]; if (block == MP_QSTR_NULL) { @@ -214,7 +214,9 @@ bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2) { // both SMALL_INT, and not equal if we get here return false; } else { - mp_obj_t temp = o2; o2 = o1; o1 = temp; + mp_obj_t temp = o2; + o2 = o1; + o1 = temp; // o2 is now the SMALL_INT, o1 is not // fall through to generic op } @@ -268,10 +270,10 @@ mp_int_t mp_obj_get_int(mp_const_obj_t arg) { return mp_obj_int_get_checked(arg); } else { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError_varg(translate("can't convert to %q"), MP_QSTR_int); + mp_raise_TypeError_varg(translate("can't convert to %q"), MP_QSTR_int); #else - mp_raise_TypeError_varg( - translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_int); + mp_raise_TypeError_varg( + translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_int); #endif } } @@ -331,10 +333,10 @@ mp_float_t mp_obj_get_float(mp_obj_t arg) { if (!mp_obj_get_float_maybe(arg, &val)) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError_varg(translate("can't convert to %q"), MP_QSTR_float); + mp_raise_TypeError_varg(translate("can't convert to %q"), MP_QSTR_float); #else - mp_raise_TypeError_varg( - translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_float); + mp_raise_TypeError_varg( + translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_float); #endif } @@ -364,10 +366,10 @@ void mp_obj_get_complex(mp_obj_t arg, mp_float_t *real, mp_float_t *imag) { mp_obj_complex_get(arg, real, imag); } else { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError_varg(translate("can't convert to %q"), MP_QSTR_complex); + mp_raise_TypeError_varg(translate("can't convert to %q"), MP_QSTR_complex); #else - mp_raise_TypeError_varg( - translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_complex); + mp_raise_TypeError_varg( + translate("can't convert %q to %q"), mp_obj_get_type_qstr(arg), MP_QSTR_complex); #endif } } @@ -382,10 +384,10 @@ void mp_obj_get_array(mp_obj_t o, size_t *len, mp_obj_t **items) { mp_obj_list_get(o, len, items); } else { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("expected tuple/list")); + mp_raise_TypeError(translate("expected tuple/list")); #else - mp_raise_TypeError_varg( - translate("object '%q' is not a tuple or list"), mp_obj_get_type_qstr(o)); + mp_raise_TypeError_varg( + translate("object '%q' is not a tuple or list"), mp_obj_get_type_qstr(o)); #endif } } @@ -396,10 +398,10 @@ void mp_obj_get_array_fixed_n(mp_obj_t o, size_t len, mp_obj_t **items) { mp_obj_get_array(o, &seq_len, items); if (seq_len != len) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_ValueError(translate("tuple/list has wrong length")); + mp_raise_ValueError(translate("tuple/list has wrong length")); #else - mp_raise_ValueError_varg(translate("requested length %d but object has length %d"), - (int)len, (int)seq_len); + mp_raise_ValueError_varg(translate("requested length %d but object has length %d"), + (int)len, (int)seq_len); #endif } } @@ -411,11 +413,11 @@ size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool i = MP_OBJ_SMALL_INT_VALUE(index); } else if (!mp_obj_get_int_maybe(index, &i)) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("indices must be integers")); + mp_raise_TypeError(translate("indices must be integers")); #else - mp_raise_TypeError_varg( - translate("%q indices must be integers, not %q"), - type->name, mp_obj_get_type_qstr(index)); + mp_raise_TypeError_varg( + translate("%q indices must be integers, not %q"), + type->name, mp_obj_get_type_qstr(index)); #endif } @@ -431,10 +433,10 @@ size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool } else { if (i < 0 || (mp_uint_t)i >= len) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_IndexError(translate("index out of range")); + mp_raise_IndexError(translate("index out of range")); #else - mp_raise_msg_varg(&mp_type_IndexError, - translate("%q index out of range"), type->name); + mp_raise_msg_varg(&mp_type_IndexError, + translate("%q index out of range"), type->name); #endif } } @@ -466,10 +468,10 @@ mp_obj_t mp_obj_len(mp_obj_t o_in) { mp_obj_t len = mp_obj_len_maybe(o_in); if (len == MP_OBJ_NULL) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object has no len")); + mp_raise_TypeError(translate("object has no len")); #else - mp_raise_TypeError_varg( - translate("object of type '%q' has no len()"), mp_obj_get_type_qstr(o_in)); + mp_raise_TypeError_varg( + translate("object of type '%q' has no len()"), mp_obj_get_type_qstr(o_in)); #endif } else { return len; @@ -479,10 +481,10 @@ mp_obj_t mp_obj_len(mp_obj_t o_in) { // may return MP_OBJ_NULL mp_obj_t mp_obj_len_maybe(mp_obj_t o_in) { if ( -#if !MICROPY_PY_BUILTINS_STR_UNICODE + #if !MICROPY_PY_BUILTINS_STR_UNICODE // It's simple - unicode is slow, non-unicode is fast MP_OBJ_IS_STR(o_in) || -#endif + #endif MP_OBJ_IS_TYPE(o_in, &mp_type_bytes)) { GET_STR_LEN(o_in, l); return MP_OBJ_NEW_SMALL_INT(l); @@ -509,24 +511,24 @@ mp_obj_t mp_obj_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t value) { } if (value == MP_OBJ_NULL) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object does not support item deletion")); + mp_raise_TypeError(translate("object does not support item deletion")); #else - mp_raise_TypeError_varg( - translate("'%q' object does not support item deletion"), mp_obj_get_type_qstr(base)); + mp_raise_TypeError_varg( + translate("'%q' object does not support item deletion"), mp_obj_get_type_qstr(base)); #endif } else if (value == MP_OBJ_SENTINEL) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object is not subscriptable")); + mp_raise_TypeError(translate("object is not subscriptable")); #else - mp_raise_TypeError_varg( - translate("'%q' object is not subscriptable"), mp_obj_get_type_qstr(base)); + mp_raise_TypeError_varg( + translate("'%q' object is not subscriptable"), mp_obj_get_type_qstr(base)); #endif } else { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object does not support item assignment")); + mp_raise_TypeError(translate("object does not support item assignment")); #else - mp_raise_TypeError_varg( - translate("'%q' object does not support item assignment"), mp_obj_get_type_qstr(base)); + mp_raise_TypeError_varg( + translate("'%q' object does not support item assignment"), mp_obj_get_type_qstr(base)); #endif } } @@ -565,7 +567,7 @@ STATIC mp_obj_t generic_it_iternext(mp_obj_t self_in) { mp_obj_t mp_obj_new_generic_iterator(mp_obj_t obj, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_generic_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_generic_it_t *o = (mp_obj_generic_it_t*)iter_buf; + mp_obj_generic_it_t *o = (mp_obj_generic_it_t *)iter_buf; o->base.type = &mp_type_polymorph_iter; o->iternext = generic_it_iternext; o->obj = obj; @@ -593,7 +595,9 @@ void mp_get_buffer_raise(mp_obj_t obj, mp_buffer_info_t *bufinfo, mp_uint_t flag mp_obj_t mp_generic_unary_op(mp_unary_op_t op, mp_obj_t o_in) { switch (op) { - case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_HASH: + return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in); + default: + return MP_OBJ_NULL; // op not supported } } diff --git a/py/obj.h b/py/obj.h index c3ab63b5cc..fcea402c63 100644 --- a/py/obj.h +++ b/py/obj.h @@ -70,13 +70,13 @@ typedef struct _mp_obj_base_t mp_obj_base_t; // as many as we can to MP_OBJ_NULL because it's cheaper to load/compare 0. #ifdef NDEBUG -#define MP_OBJ_NULL (MP_OBJ_FROM_PTR((void*)0)) -#define MP_OBJ_STOP_ITERATION (MP_OBJ_FROM_PTR((void*)0)) -#define MP_OBJ_SENTINEL (MP_OBJ_FROM_PTR((void*)4)) +#define MP_OBJ_NULL (MP_OBJ_FROM_PTR((void *)0)) +#define MP_OBJ_STOP_ITERATION (MP_OBJ_FROM_PTR((void *)0)) +#define MP_OBJ_SENTINEL (MP_OBJ_FROM_PTR((void *)4)) #else -#define MP_OBJ_NULL (MP_OBJ_FROM_PTR((void*)0)) -#define MP_OBJ_STOP_ITERATION (MP_OBJ_FROM_PTR((void*)4)) -#define MP_OBJ_SENTINEL (MP_OBJ_FROM_PTR((void*)8)) +#define MP_OBJ_NULL (MP_OBJ_FROM_PTR((void *)0)) +#define MP_OBJ_STOP_ITERATION (MP_OBJ_FROM_PTR((void *)4)) +#define MP_OBJ_SENTINEL (MP_OBJ_FROM_PTR((void *)8)) #endif // These macros/inline functions operate on objects and depend on the @@ -85,13 +85,15 @@ typedef struct _mp_obj_base_t mp_obj_base_t; #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 1) != 0); } +static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 1) != 0; +} #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1)) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 2); } +static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 2; +} #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 2) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 2) | 2)) @@ -106,18 +108,21 @@ mp_float_t mp_obj_float_get(mp_obj_t self_in); mp_obj_t mp_obj_new_float(mp_float_t value); #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 0); } +static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 0; +} #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 1); } +static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 1; +} #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 2) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 2) | 1)) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 3); } +static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 3; +} #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 2) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 2) | 3)) @@ -132,21 +137,24 @@ mp_float_t mp_obj_float_get(mp_obj_t self_in); mp_obj_t mp_obj_new_float(mp_float_t value); #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 1) == 0); } +static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 1) == 0; +} #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 1) != 0); } +static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 1) != 0; +} #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)(o)) >> 1) #define MP_OBJ_NEW_SMALL_INT(small_int) ((mp_obj_t)((((mp_uint_t)(small_int)) << 1) | 1)) #define mp_const_float_e MP_ROM_PTR((mp_obj_t)(((0x402df854 & ~3) | 2) + 0x80800000)) #define mp_const_float_pi MP_ROM_PTR((mp_obj_t)(((0x40490fdb & ~3) | 2) + 0x80800000)) -static inline bool mp_obj_is_float(mp_const_obj_t o) - { return (((mp_uint_t)(o)) & 3) == 2 && (((mp_uint_t)(o)) & 0xff800007) != 0x00000006; } +static inline bool mp_obj_is_float(mp_const_obj_t o) { + return (((mp_uint_t)(o)) & 3) == 2 && (((mp_uint_t)(o)) & 0xff800007) != 0x00000006; +} static inline mp_float_t mp_obj_float_get(mp_const_obj_t o) { union { mp_float_t f; @@ -162,23 +170,27 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { return (mp_obj_t)(((num.u & ~0x3) | 2) + 0x80800000); } -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) - { return (((mp_uint_t)(o)) & 0xff800007) == 0x00000006; } +static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { + return (((mp_uint_t)(o)) & 0xff800007) == 0x00000006; +} #define MP_OBJ_QSTR_VALUE(o) (((mp_uint_t)(o)) >> 3) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 3) | 0x00000006)) -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 3) == 0); } +static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 3) == 0; +} #elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D -static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 0xffff000000000000) == 0x0001000000000000); } +static inline bool MP_OBJ_IS_SMALL_INT(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 0xffff000000000000) == 0x0001000000000000; +} #define MP_OBJ_SMALL_INT_VALUE(o) (((mp_int_t)((o) << 16)) >> 17) #define MP_OBJ_NEW_SMALL_INT(small_int) (((((uint64_t)(small_int)) & 0x7fffffffffff) << 1) | 0x0001000000000001) -static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) - { return ((((mp_int_t)(o)) & 0xffff000000000000) == 0x0002000000000000); } +static inline bool MP_OBJ_IS_QSTR(mp_const_obj_t o) { + return (((mp_int_t)(o)) & 0xffff000000000000) == 0x0002000000000000; +} #define MP_OBJ_QSTR_VALUE(o) ((((uint32_t)(o)) >> 1) & 0xffffffff) #define MP_OBJ_NEW_QSTR(qst) ((mp_obj_t)((((mp_uint_t)(qst)) << 1) | 0x0002000000000001)) @@ -205,13 +217,17 @@ static inline mp_obj_t mp_obj_new_float(mp_float_t f) { } #endif -static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) - { return ((((uint64_t)(o)) & 0xffff000000000000) == 0x0000000000000000); } -#define MP_OBJ_TO_PTR(o) ((void*)(uintptr_t)(o)) +static inline bool MP_OBJ_IS_OBJ(mp_const_obj_t o) { + return (((uint64_t)(o)) & 0xffff000000000000) == 0x0000000000000000; +} +#define MP_OBJ_TO_PTR(o) ((void *)(uintptr_t)(o)) #define MP_OBJ_FROM_PTR(p) ((mp_obj_t)((uintptr_t)(p))) // rom object storage needs special handling to widen 32-bit pointer to 64-bits -typedef union _mp_rom_obj_t { uint64_t u64; struct { const void *lo, *hi; } u32; } mp_rom_obj_t; +typedef union _mp_rom_obj_t { uint64_t u64; + struct { const void *lo, *hi; + } u32; +} mp_rom_obj_t; #define MP_ROM_INT(i) {MP_OBJ_NEW_SMALL_INT(i)} #define MP_ROM_QSTR(q) {MP_OBJ_NEW_QSTR(q)} #if MP_ENDIANNESS_LITTLE @@ -229,7 +245,7 @@ typedef union _mp_rom_obj_t { uint64_t u64; struct { const void *lo, *hi; } u32; // Cast mp_obj_t to object pointer #ifndef MP_OBJ_TO_PTR -#define MP_OBJ_TO_PTR(o) ((void*)o) +#define MP_OBJ_TO_PTR(o) ((void *)o) #endif // Cast object pointer to mp_obj_t @@ -257,11 +273,11 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; // Note: these are kept as macros because inline functions sometimes use much // more code space than the equivalent macros, depending on the compiler. -#define MP_OBJ_IS_TYPE(o, t) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type == (t))) // this does not work for checking int, str or fun; use below macros for that +#define MP_OBJ_IS_TYPE(o, t) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type == (t))) // this does not work for checking int, str or fun; use below macros for that #define MP_OBJ_IS_INT(o) (MP_OBJ_IS_SMALL_INT(o) || MP_OBJ_IS_TYPE(o, &mp_type_int)) #define MP_OBJ_IS_STR(o) (MP_OBJ_IS_QSTR(o) || MP_OBJ_IS_TYPE(o, &mp_type_str)) -#define MP_OBJ_IS_STR_OR_BYTES(o) (MP_OBJ_IS_QSTR(o) || (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->binary_op == mp_obj_str_binary_op)) -#define MP_OBJ_IS_FUN(o) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_function)) +#define MP_OBJ_IS_STR_OR_BYTES(o) (MP_OBJ_IS_QSTR(o) || (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->binary_op == mp_obj_str_binary_op)) +#define MP_OBJ_IS_FUN(o) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_function)) // These macros are used to declare and define constant function objects // You can put "static" in front of the definitions to make them local @@ -276,25 +292,25 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; #define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_0}, .fun._0 = fun_name} + {{&mp_type_fun_builtin_0}, .fun._0 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_1(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_1}, .fun._1 = fun_name} + {{&mp_type_fun_builtin_1}, .fun._1 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_2(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_2}, .fun._2 = fun_name} + {{&mp_type_fun_builtin_2}, .fun._2 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_3(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_3}, .fun._3 = fun_name} + {{&mp_type_fun_builtin_3}, .fun._3 = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_VAR(obj_name, n_args_min, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, false, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.var = fun_name} + {{&mp_type_fun_builtin_var}, false, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.var = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(obj_name, n_args_min, n_args_max, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, false, n_args_min, n_args_max, .fun.var = fun_name} + {{&mp_type_fun_builtin_var}, false, n_args_min, n_args_max, .fun.var = fun_name} #define MP_DEFINE_CONST_FUN_OBJ_KW(obj_name, n_args_min, fun_name) \ const mp_obj_fun_builtin_var_t obj_name = \ - {{&mp_type_fun_builtin_var}, true, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.kw = fun_name} + {{&mp_type_fun_builtin_var}, true, n_args_min, MP_OBJ_FUN_ARGS_MAX, .fun.kw = fun_name} #define MP_DEFINE_CONST_PROP_GET(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t fun_name##_obj = {{&mp_type_fun_builtin_1}, .fun._1 = fun_name}; \ const mp_obj_property_t obj_name = { \ @@ -313,7 +329,7 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; .is_ordered = 1, \ .used = MP_ARRAY_SIZE(table_name), \ .alloc = MP_ARRAY_SIZE(table_name), \ - .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)table_name, \ + .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)table_name, \ } #define MP_DEFINE_CONST_DICT(dict_name, table_name) \ @@ -325,7 +341,7 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; .is_ordered = 1, \ .used = MP_ARRAY_SIZE(table_name), \ .alloc = MP_ARRAY_SIZE(table_name), \ - .table = (mp_map_elem_t*)(mp_rom_map_elem_t*)table_name, \ + .table = (mp_map_elem_t *)(mp_rom_map_elem_t *)table_name, \ }, \ } @@ -406,7 +422,9 @@ typedef enum _mp_map_lookup_kind_t { extern const mp_map_t mp_const_empty_map; -static inline bool MP_MAP_SLOT_IS_FILLED(const mp_map_t *map, size_t pos) { return ((map)->table[pos].key != MP_OBJ_NULL && (map)->table[pos].key != MP_OBJ_SENTINEL); } +static inline bool MP_MAP_SLOT_IS_FILLED(const mp_map_t *map, size_t pos) { + return (map)->table[pos].key != MP_OBJ_NULL && (map)->table[pos].key != MP_OBJ_SENTINEL; +} void mp_map_init(mp_map_t *map, size_t n); void mp_map_init_fixed_table(mp_map_t *map, size_t n, const mp_obj_t *table); @@ -425,7 +443,9 @@ typedef struct _mp_set_t { mp_obj_t *table; } mp_set_t; -static inline bool MP_SET_SLOT_IS_FILLED(const mp_set_t *set, size_t pos) { return ((set)->table[pos] != MP_OBJ_NULL && (set)->table[pos] != MP_OBJ_SENTINEL); } +static inline bool MP_SET_SLOT_IS_FILLED(const mp_set_t *set, size_t pos) { + return (set)->table[pos] != MP_OBJ_NULL && (set)->table[pos] != MP_OBJ_SENTINEL; +} void mp_set_init(mp_set_t *set, size_t n); mp_obj_t mp_set_lookup(mp_set_t *set, mp_obj_t index, mp_map_lookup_kind_t lookup_kind); @@ -475,7 +495,7 @@ typedef struct _mp_buffer_info_t { // if we'd bother to support various versions of structure // (with different number of fields), we can distinguish // them with ver = sizeof(struct). Cons: overkill for *micro*? - //int ver; // ? + // int ver; // ? void *buf; // can be NULL if len == 0 size_t len; // in bytes @@ -665,17 +685,19 @@ extern const struct _mp_obj_exception_t mp_const_GeneratorExit_obj; // General API for objects mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict); -static inline mp_obj_t mp_obj_new_bool(mp_int_t x) { return x ? mp_const_true : mp_const_false; } +static inline mp_obj_t mp_obj_new_bool(mp_int_t x) { + return x ? mp_const_true : mp_const_false; +} mp_obj_t mp_obj_new_cell(mp_obj_t obj); mp_obj_t mp_obj_new_int(mp_int_t value); mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value); mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base); mp_obj_t mp_obj_new_int_from_ll(long long val); // this must return a multi-precision integer object (or raise an overflow exception) mp_obj_t mp_obj_new_int_from_ull(unsigned long long val); // this must return a multi-precision integer object (or raise an overflow exception) -mp_obj_t mp_obj_new_str(const char* data, size_t len); -mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len); +mp_obj_t mp_obj_new_str(const char *data, size_t len); +mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len); mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr); -mp_obj_t mp_obj_new_bytes(const byte* data, size_t len); +mp_obj_t mp_obj_new_bytes(const byte *data, size_t len); mp_obj_t mp_obj_new_bytes_of_zeros(size_t len); mp_obj_t mp_obj_new_bytearray(size_t n, void *items); mp_obj_t mp_obj_new_bytearray_of_zeros(size_t n); @@ -723,7 +745,9 @@ bool mp_obj_is_true(mp_obj_t arg); bool mp_obj_is_callable(mp_obj_t o_in); bool mp_obj_equal(mp_obj_t o1, mp_obj_t o2); -static inline bool mp_obj_is_integer(mp_const_obj_t o) { return MP_OBJ_IS_INT(o) || MP_OBJ_IS_TYPE(o, &mp_type_bool); } // returns true if o is bool, small int or long int +static inline bool mp_obj_is_integer(mp_const_obj_t o) { + return MP_OBJ_IS_INT(o) || MP_OBJ_IS_TYPE(o, &mp_type_bool); +} // returns true if o is bool, small int or long int mp_int_t mp_obj_get_int(mp_const_obj_t arg); mp_int_t mp_obj_get_int_truncated(mp_const_obj_t arg); bool mp_obj_get_int_maybe(mp_const_obj_t arg, mp_int_t *value); @@ -732,7 +756,7 @@ mp_float_t mp_obj_get_float(mp_obj_t self_in); bool mp_obj_get_float_maybe(mp_obj_t arg, mp_float_t *value); void mp_obj_get_complex(mp_obj_t self_in, mp_float_t *real, mp_float_t *imag); #endif -//qstr mp_obj_get_qstr(mp_obj_t arg); +// qstr mp_obj_get_qstr(mp_obj_t arg); void mp_obj_get_array(mp_obj_t o, size_t *len, mp_obj_t **items); // *items may point inside a GC block void mp_obj_get_array_fixed_n(mp_obj_t o, size_t len, mp_obj_t **items); // *items may point inside a GC block size_t mp_get_index(const mp_obj_type_t *type, size_t len, mp_obj_t index, bool is_slice); @@ -780,7 +804,9 @@ void mp_str_print_quoted(const mp_print_t *print, const byte *str_data, size_t s #if MICROPY_FLOAT_HIGH_QUALITY_HASH mp_int_t mp_float_hash(mp_float_t val); #else -static inline mp_int_t mp_float_hash(mp_float_t val) { return (mp_int_t)val; } +static inline mp_int_t mp_float_hash(mp_float_t val) { + return (mp_int_t)val; +} #endif mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t rhs); // can return MP_OBJ_NULL if op not supported @@ -906,17 +932,17 @@ mp_obj_t mp_seq_index_obj(const mp_obj_t *items, size_t len, size_t n_args, cons mp_obj_t mp_seq_count_obj(const mp_obj_t *items, size_t len, mp_obj_t value); mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t *indexes); // Helper to clear stale pointers from allocated, but unused memory, to preclude GC problems -#define mp_seq_clear(start, len, alloc_len, item_sz) memset((byte*)(start) + (len) * (item_sz), 0, ((alloc_len) - (len)) * (item_sz)) +#define mp_seq_clear(start, len, alloc_len, item_sz) memset((byte *)(start) + (len) * (item_sz), 0, ((alloc_len) - (len)) * (item_sz)) #define mp_seq_replace_slice_no_grow(dest, dest_len, beg, end, slice, slice_len, item_sz) \ /*printf("memcpy(%p, %p, %d)\n", dest + beg, slice, slice_len * (item_sz));*/ \ - memcpy(((char*)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); \ + memcpy(((char *)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); \ /*printf("memmove(%p, %p, %d)\n", dest + (beg + slice_len), dest + end, (dest_len - end) * (item_sz));*/ \ - memmove(((char*)dest) + (beg + slice_len) * (item_sz), ((char*)dest) + (end) * (item_sz), (dest_len - end) * (item_sz)); + memmove(((char *)dest) + (beg + slice_len) * (item_sz), ((char *)dest) + (end) * (item_sz), (dest_len - end) * (item_sz)); // Note: dest and slice regions may overlap #define mp_seq_replace_slice_grow_inplace(dest, dest_len, beg, end, slice, slice_len, len_adj, item_sz) \ /*printf("memmove(%p, %p, %d)\n", dest + beg + len_adj, dest + beg, (dest_len - beg) * (item_sz));*/ \ - memmove(((char*)dest) + (beg + slice_len) * (item_sz), ((char*)dest) + (end) * (item_sz), ((dest_len) + (len_adj) - ((beg) + (slice_len))) * (item_sz)); \ - memmove(((char*)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); + memmove(((char *)dest) + (beg + slice_len) * (item_sz), ((char *)dest) + (end) * (item_sz), ((dest_len) + (len_adj) - ((beg) + (slice_len))) * (item_sz)); \ + memmove(((char *)dest) + (beg) * (item_sz), slice, slice_len * (item_sz)); #endif // MICROPY_INCLUDED_PY_OBJ_H diff --git a/py/objarray.c b/py/objarray.c index 9640f596a3..e6024f720c 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -123,10 +123,10 @@ STATIC mp_obj_t array_construct(char typecode, mp_obj_t initializer) { // other arrays can only be raw-initialised from bytes and bytearray objects mp_buffer_info_t bufinfo; if (((MICROPY_PY_BUILTINS_BYTEARRAY - && typecode == BYTEARRAY_TYPECODE) - || (MICROPY_PY_ARRAY - && (MP_OBJ_IS_TYPE(initializer, &mp_type_bytes) - || (MICROPY_PY_BUILTINS_BYTEARRAY && MP_OBJ_IS_TYPE(initializer, &mp_type_bytearray))))) + && typecode == BYTEARRAY_TYPECODE) + || (MICROPY_PY_ARRAY + && (MP_OBJ_IS_TYPE(initializer, &mp_type_bytes) + || (MICROPY_PY_BUILTINS_BYTEARRAY && MP_OBJ_IS_TYPE(initializer, &mp_type_bytearray))))) && mp_get_buffer(initializer, &bufinfo, MP_BUFFER_READ)) { // construct array from raw bytes size_t sz = mp_binary_get_size('@', typecode, NULL); @@ -263,9 +263,12 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(memoryview_cast_obj, memoryview_cast); STATIC mp_obj_t array_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_obj_array_t *o = MP_OBJ_TO_PTR(o_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(o->len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(o->len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(o->len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -284,22 +287,23 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs mp_obj_array_t *res; byte *ptr; size_t orig_lhs_bufinfo_len = lhs_bufinfo.len; - if(inplace) { + if (inplace) { res = lhs; size_t item_sz = mp_binary_get_size('@', lhs->typecode, NULL); lhs->items = m_renew(byte, lhs->items, (lhs->len + lhs->free) * item_sz, lhs->len * repeat * item_sz); lhs->len = lhs->len * repeat; lhs->free = 0; - if (!repeat) + if (!repeat) { return MP_OBJ_FROM_PTR(res); + } repeat--; - ptr = (byte*)res->items + orig_lhs_bufinfo_len; + ptr = (byte *)res->items + orig_lhs_bufinfo_len; } else { res = array_new(lhs_bufinfo.typecode, lhs->len * repeat); - ptr = (byte*)res->items; + ptr = (byte *)res->items; } - if(orig_lhs_bufinfo_len) { - for(;repeat--; ptr += orig_lhs_bufinfo_len) { + if (orig_lhs_bufinfo_len) { + for (; repeat--; ptr += orig_lhs_bufinfo_len) { memcpy(ptr, lhs_bufinfo.buf, orig_lhs_bufinfo_len); } } @@ -319,7 +323,7 @@ STATIC mp_obj_t array_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs // note: lhs->len is element count of lhs, lhs_bufinfo.len is byte count mp_obj_array_t *res = array_new(lhs_bufinfo.typecode, lhs->len + rhs_len); - mp_seq_cat((byte*)res->items, lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_len * sz, byte); + mp_seq_cat((byte *)res->items, lhs_bufinfo.buf, lhs_bufinfo.len, rhs_bufinfo.buf, rhs_len * sz, byte); return MP_OBJ_FROM_PTR(res); } @@ -417,7 +421,7 @@ STATIC mp_obj_t array_extend(mp_obj_t self_in, mp_obj_t arg_in) { } // extend - mp_seq_copy((byte*)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte); + mp_seq_copy((byte *)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte); self->len += len; return mp_const_none; @@ -441,12 +445,12 @@ STATIC mp_obj_t buffer_finder(size_t n_args, const mp_obj_t *args, int direction } const byte *start = haystack_bufinfo.buf; - const byte *end = ((const byte*)haystack_bufinfo.buf) + haystack_bufinfo.len; + const byte *end = ((const byte *)haystack_bufinfo.buf) + haystack_bufinfo.len; if (n_args >= 3 && args[2] != mp_const_none) { start += mp_get_index(self_type, haystack_bufinfo.len, args[2], true); } if (n_args >= 4 && args[3] != mp_const_none) { - end = ((const byte*)haystack_bufinfo.buf) + mp_get_index(self_type, haystack_bufinfo.len, args[3], true); + end = ((const byte *)haystack_bufinfo.buf) + mp_get_index(self_type, haystack_bufinfo.len, args[3], true); } const byte *p = NULL; @@ -461,7 +465,7 @@ STATIC mp_obj_t buffer_finder(size_t n_args, const mp_obj_t *args, int direction return MP_OBJ_NEW_SMALL_INT(-1); } } - return MP_OBJ_NEW_SMALL_INT(p - (const byte*) haystack_bufinfo.buf); + return MP_OBJ_NEW_SMALL_INT(p - (const byte *)haystack_bufinfo.buf); } STATIC mp_obj_t buffer_find(size_t n_args, const mp_obj_t *args) { @@ -495,7 +499,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value } else { mp_obj_array_t *o = MP_OBJ_TO_PTR(self_in); if (0) { -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE } else if (MP_OBJ_IS_TYPE(index_in, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(o->len, index_in, &slice)) { @@ -507,7 +511,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value size_t src_len; void *src_items; size_t item_sz = mp_binary_get_size('@', o->typecode & TYPECODE_MASK, NULL); - if (MP_OBJ_IS_OBJ(value) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(value))->type->subscr == array_subscr) { + if (MP_OBJ_IS_OBJ(value) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(value))->type->subscr == array_subscr) { // value is array, bytearray or memoryview mp_obj_array_t *src_slice = MP_OBJ_TO_PTR(value); if (item_sz != mp_binary_get_size('@', src_slice->typecode & TYPECODE_MASK, NULL)) { @@ -518,7 +522,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value src_items = src_slice->items; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (MP_OBJ_IS_TYPE(value, &mp_type_memoryview)) { - src_items = (uint8_t*)src_items + (src_slice->free * item_sz); + src_items = (uint8_t *)src_items + (src_slice->free * item_sz); } #endif } else if (MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { @@ -535,7 +539,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value // TODO: check src/dst compat mp_int_t len_adj = src_len - (slice.stop - slice.start); - uint8_t* dest_items = o->items; + uint8_t *dest_items = o->items; #if MICROPY_PY_BUILTINS_MEMORYVIEW if (o->base.type == &mp_type_memoryview) { if (!(o->typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) { @@ -549,7 +553,7 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value } #endif if (len_adj > 0) { - if ((mp_uint_t) len_adj > o->free) { + if ((mp_uint_t)len_adj > o->free) { // TODO: alloc policy; at the moment we go conservative o->items = m_renew(byte, o->items, (o->len + o->free) * item_sz, (o->len + len_adj) * item_sz); o->free = 0; @@ -560,11 +564,11 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value } else { mp_seq_replace_slice_no_grow(dest_items, o->len, slice.start, slice.stop, src_items, src_len, item_sz); -#if MICROPY_NONSTANDARD_TYPECODES + #if MICROPY_NONSTANDARD_TYPECODES // Clear "freed" elements at the end of list // TODO: This is actually only needed for typecode=='O' mp_seq_clear(dest_items, o->len + len_adj, o->len, item_sz); -#endif + #endif // TODO: alloc policy after shrinking } o->len += len_adj; @@ -588,10 +592,10 @@ STATIC mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value #endif } else { res = array_new(o->typecode, slice.stop - slice.start); - memcpy(res->items, (uint8_t*)o->items + slice.start * sz, (slice.stop - slice.start) * sz); + memcpy(res->items, (uint8_t *)o->items + slice.start * sz, (slice.stop - slice.start) * sz); } return MP_OBJ_FROM_PTR(res); -#endif + #endif } else { size_t index = mp_get_index(o->base.type, o->len, index_in, false); #if MICROPY_PY_BUILTINS_MEMORYVIEW @@ -627,7 +631,7 @@ STATIC mp_int_t array_get_buffer(mp_obj_t o_in, mp_buffer_info_t *bufinfo, mp_ui // read-only memoryview return 1; } - bufinfo->buf = (uint8_t*)bufinfo->buf + (size_t)o->free * sz; + bufinfo->buf = (uint8_t *)bufinfo->buf + (size_t)o->free * sz; } #else (void)flags; @@ -666,14 +670,14 @@ STATIC const mp_rom_map_elem_t bytearray_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_append), MP_ROM_PTR(&array_append_obj) }, { MP_ROM_QSTR(MP_QSTR_extend), MP_ROM_PTR(&array_extend_obj) }, -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&buffer_find_obj) }, { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&buffer_rfind_obj) }, { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&buffer_index_obj) }, { MP_ROM_QSTR(MP_QSTR_rindex), MP_ROM_PTR(&buffer_rindex_obj) }, { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&array_decode_obj) }, -#endif + #endif }; STATIC MP_DEFINE_CONST_DICT(bytearray_locals_dict, bytearray_locals_dict_table); @@ -691,7 +695,7 @@ const mp_obj_type_t mp_type_array = { .binary_op = array_binary_op, .subscr = array_subscr, .buffer_p = { .get_buffer = array_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&array_locals_dict, + .locals_dict = (mp_obj_dict_t *)&array_locals_dict, }; #endif @@ -706,7 +710,7 @@ const mp_obj_type_t mp_type_bytearray = { .binary_op = array_binary_op, .subscr = array_subscr, .buffer_p = { .get_buffer = array_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&bytearray_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bytearray_locals_dict, }; #endif @@ -729,9 +733,9 @@ const mp_obj_type_t mp_type_memoryview = { .binary_op = array_binary_op, .subscr = array_subscr, .buffer_p = { .get_buffer = array_get_buffer }, -#if MICROPY_CPYTHON_COMPAT - .locals_dict = (mp_obj_dict_t*)&memoryview_locals_dict, -#endif + #if MICROPY_CPYTHON_COMPAT + .locals_dict = (mp_obj_dict_t *)&memoryview_locals_dict, + #endif }; #endif @@ -795,7 +799,7 @@ STATIC const mp_obj_type_t array_it_type = { STATIC mp_obj_t array_iterator_new(mp_obj_t array_in, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_array_t) <= sizeof(mp_obj_iter_buf_t)); mp_obj_array_t *array = MP_OBJ_TO_PTR(array_in); - mp_obj_array_it_t *o = (mp_obj_array_it_t*)iter_buf; + mp_obj_array_it_t *o = (mp_obj_array_it_t *)iter_buf; o->base.type = &array_it_type; o->array = array; o->offset = 0; diff --git a/py/objattrtuple.c b/py/objattrtuple.c index ac9b808a20..2e75a23af3 100644 --- a/py/objattrtuple.c +++ b/py/objattrtuple.c @@ -51,7 +51,7 @@ void mp_obj_attrtuple_print_helper(const mp_print_t *print, const qstr *fields, STATIC void mp_obj_attrtuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_obj_tuple_t *o = MP_OBJ_TO_PTR(o_in); - const qstr *fields = (const qstr*)MP_OBJ_TO_PTR(o->items[o->len]); + const qstr *fields = (const qstr *)MP_OBJ_TO_PTR(o->items[o->len]); mp_obj_attrtuple_print_helper(print, fields, o); } @@ -60,7 +60,7 @@ STATIC void mp_obj_attrtuple_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { // load attribute mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); size_t len = self->len; - const qstr *fields = (const qstr*)MP_OBJ_TO_PTR(self->items[len]); + const qstr *fields = (const qstr *)MP_OBJ_TO_PTR(self->items[len]); for (size_t i = 0; i < len; i++) { if (fields[i] == attr) { dest[0] = self->items[i]; diff --git a/py/objboundmeth.c b/py/objboundmeth.c index 5bf25567f0..cdb7257973 100644 --- a/py/objboundmeth.c +++ b/py/objboundmeth.c @@ -102,13 +102,13 @@ STATIC void bound_meth_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { STATIC const mp_obj_type_t mp_type_bound_meth = { { &mp_type_type }, .name = MP_QSTR_bound_method, -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED .print = bound_meth_print, -#endif + #endif .call = bound_meth_call, -#if MICROPY_PY_FUNCTION_ATTRS + #if MICROPY_PY_FUNCTION_ATTRS .attr = bound_meth_attr, -#endif + #endif }; mp_obj_t mp_obj_new_bound_meth(mp_obj_t meth, mp_obj_t self) { diff --git a/py/objcell.c b/py/objcell.c index 25fe5232a1..2e15e6825a 100644 --- a/py/objcell.c +++ b/py/objcell.c @@ -58,9 +58,9 @@ STATIC void cell_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t k STATIC const mp_obj_type_t mp_type_cell = { { &mp_type_type }, .name = MP_QSTR_, // cell representation is just value in < > -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED .print = cell_print, -#endif + #endif }; mp_obj_t mp_obj_new_cell(mp_obj_t obj) { diff --git a/py/objclosure.c b/py/objclosure.c index 6f6772ff1c..e4e3b87bbb 100644 --- a/py/objclosure.c +++ b/py/objclosure.c @@ -81,9 +81,9 @@ STATIC void closure_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_ const mp_obj_type_t closure_type = { { &mp_type_type }, .name = MP_QSTR_closure, -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED .print = closure_print, -#endif + #endif .call = closure_call, }; diff --git a/py/objcomplex.c b/py/objcomplex.c index 43e0690d38..5e80826c69 100644 --- a/py/objcomplex.c +++ b/py/objcomplex.c @@ -50,17 +50,17 @@ typedef struct _mp_obj_complex_t { STATIC void complex_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_obj_complex_t *o = MP_OBJ_TO_PTR(o_in); -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT char buf[16]; #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C const int precision = 6; #else const int precision = 7; #endif -#else + #else char buf[32]; const int precision = 16; -#endif + #endif if (o->real == 0) { mp_format_float(o->imag, buf, sizeof(buf), 'g', precision, '\0'); mp_printf(print, "%sj", buf); @@ -122,13 +122,18 @@ STATIC mp_obj_t complex_make_new(const mp_obj_type_t *type_in, size_t n_args, co STATIC mp_obj_t complex_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_obj_complex_t *o = MP_OBJ_TO_PTR(o_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->real != 0 || o->imag != 0); - case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(o->real) ^ mp_float_hash(o->imag)); - case MP_UNARY_OP_POSITIVE: return o_in; - case MP_UNARY_OP_NEGATIVE: return mp_obj_new_complex(-o->real, -o->imag); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(o->real != 0 || o->imag != 0); + case MP_UNARY_OP_HASH: + return MP_OBJ_NEW_SMALL_INT(mp_float_hash(o->real) ^ mp_float_hash(o->imag)); + case MP_UNARY_OP_POSITIVE: + return o_in; + case MP_UNARY_OP_NEGATIVE: + return mp_obj_new_complex(-o->real, -o->imag); case MP_UNARY_OP_ABS: - return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(o->real*o->real + o->imag*o->imag)); - default: return MP_OBJ_NULL; // op not supported + return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(o->real * o->real + o->imag * o->imag)); + default: + return MP_OBJ_NULL; // op not supported } } @@ -192,7 +197,7 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo case MP_BINARY_OP_MULTIPLY: case MP_BINARY_OP_INPLACE_MULTIPLY: { mp_float_t real; - multiply: + multiply: real = lhs_real * rhs_real - lhs_imag * rhs_imag; lhs_imag = lhs_real * rhs_imag + lhs_imag * rhs_real; lhs_real = real; @@ -215,7 +220,7 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo lhs_imag = -lhs_real / rhs_imag; lhs_real = real; } else { - mp_float_t rhs_len_sq = rhs_real*rhs_real + rhs_imag*rhs_imag; + mp_float_t rhs_len_sq = rhs_real * rhs_real + rhs_imag * rhs_imag; rhs_real /= rhs_len_sq; rhs_imag /= -rhs_len_sq; goto multiply; @@ -229,7 +234,7 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo // = exp( (x2*ln1 - y2*arg1) + i*(y2*ln1 + x2*arg1) ) // = exp(x3 + i*y3) // = exp(x3)*(cos(y3) + i*sin(y3)) - mp_float_t abs1 = MICROPY_FLOAT_C_FUN(sqrt)(lhs_real*lhs_real + lhs_imag*lhs_imag); + mp_float_t abs1 = MICROPY_FLOAT_C_FUN(sqrt)(lhs_real * lhs_real + lhs_imag * lhs_imag); if (abs1 == 0) { if (rhs_imag == 0 && rhs_real >= 0) { lhs_real = (rhs_real == 0); @@ -248,7 +253,8 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo break; } - case MP_BINARY_OP_EQUAL: return mp_obj_new_bool(lhs_real == rhs_real && lhs_imag == rhs_imag); + case MP_BINARY_OP_EQUAL: + return mp_obj_new_bool(lhs_real == rhs_real && lhs_imag == rhs_imag); default: return MP_OBJ_NULL; // op not supported diff --git a/py/objdeque.c b/py/objdeque.c index b2785b5b60..d9d8c0415d 100644 --- a/py/objdeque.c +++ b/py/objdeque.c @@ -163,7 +163,7 @@ const mp_obj_type_t mp_type_deque = { .name = MP_QSTR_deque, .make_new = deque_make_new, .unary_op = deque_unary_op, - .locals_dict = (mp_obj_dict_t*)&deque_locals_dict, + .locals_dict = (mp_obj_dict_t *)&deque_locals_dict, }; #endif // MICROPY_PY_COLLECTIONS_DEQUE diff --git a/py/objdict.c b/py/objdict.c index 098aec5d2f..24484566f3 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -34,7 +34,7 @@ #include "supervisor/linker.h" #include "supervisor/shared/translate.h" -#define MP_OBJ_IS_DICT_TYPE(o) (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new) +#define MP_OBJ_IS_DICT_TYPE(o) (MP_OBJ_IS_OBJ(o) && ((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->make_new == dict_make_new) STATIC mp_obj_t dict_update(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs); @@ -104,15 +104,18 @@ STATIC mp_obj_t dict_make_new(const mp_obj_type_t *type, size_t n_args, const mp STATIC mp_obj_t dict_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_dict_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->map.used != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->map.used); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(self->map.used != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(self->map.used); #if MICROPY_PY_SYS_GETSIZEOF case MP_UNARY_OP_SIZEOF: { size_t sz = sizeof(*self) + sizeof(*self->map.table) * self->map.alloc; return MP_OBJ_NEW_SMALL_INT(sz); } #endif - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -340,7 +343,7 @@ STATIC mp_obj_t PLACE_IN_ITCM(dict_update)(size_t n_args, const mp_obj_t *args, if (args[1] != args[0]) { size_t cur = 0; mp_map_elem_t *elem = NULL; - while ((elem = dict_iter_next((mp_obj_dict_t*)MP_OBJ_TO_PTR(args[1]), &cur)) != NULL) { + while ((elem = dict_iter_next((mp_obj_dict_t *)MP_OBJ_TO_PTR(args[1]), &cur)) != NULL) { mp_map_lookup(&self->map, elem->key, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND)->value = elem->value; } } @@ -436,7 +439,7 @@ STATIC mp_obj_t dict_view_getiter(mp_obj_t view_in, mp_obj_iter_buf_t *iter_buf) assert(sizeof(mp_obj_dict_view_it_t) <= sizeof(mp_obj_iter_buf_t)); mp_check_self(MP_OBJ_IS_TYPE(view_in, &dict_view_type)); mp_obj_dict_view_t *view = MP_OBJ_TO_PTR(view_in); - mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t*)iter_buf; + mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t *)iter_buf; o->base.type = &dict_view_it_type; o->kind = view->kind; o->dict = view->dict; @@ -518,7 +521,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(dict_values_obj, dict_values); STATIC mp_obj_t dict_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_dict_view_it_t) <= sizeof(mp_obj_iter_buf_t)); mp_check_self(MP_OBJ_IS_DICT_TYPE(self_in)); - mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t*)iter_buf; + mp_obj_dict_view_it_t *o = (mp_obj_dict_view_it_t *)iter_buf; o->base.type = &dict_view_it_type; o->kind = MP_DICT_VIEW_KEYS; o->dict = self_in; @@ -557,7 +560,7 @@ const mp_obj_type_t mp_type_dict = { .binary_op = dict_binary_op, .subscr = dict_subscr, .getiter = dict_getiter, - .locals_dict = (mp_obj_dict_t*)&dict_locals_dict, + .locals_dict = (mp_obj_dict_t *)&dict_locals_dict, }; #if MICROPY_PY_COLLECTIONS_ORDEREDDICT @@ -571,7 +574,7 @@ const mp_obj_type_t mp_type_ordereddict = { .subscr = dict_subscr, .getiter = dict_getiter, .parent = &mp_type_dict, - .locals_dict = (mp_obj_dict_t*)&dict_locals_dict, + .locals_dict = (mp_obj_dict_t *)&dict_locals_dict, }; #endif diff --git a/py/objenumerate.c b/py/objenumerate.c index dee7fc760d..2c2131ad4f 100644 --- a/py/objenumerate.c +++ b/py/objenumerate.c @@ -40,7 +40,7 @@ typedef struct _mp_obj_enumerate_t { STATIC mp_obj_t enumerate_iternext(mp_obj_t self_in); STATIC mp_obj_t enumerate_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT static const mp_arg_t allowed_args[] = { { MP_QSTR_iterable, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_start, MP_ARG_INT, {.u_int = 0} }, @@ -51,20 +51,20 @@ STATIC mp_obj_t enumerate_make_new(const mp_obj_type_t *type, size_t n_args, con mp_arg_val_t iterable, start; } arg_vals; mp_arg_parse_all(n_args, args, kw_args, - MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&arg_vals); + MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&arg_vals); // create enumerate object mp_obj_enumerate_t *o = m_new_obj(mp_obj_enumerate_t); o->base.type = type; o->iter = mp_getiter(arg_vals.iterable.u_obj, NULL); o->cur = arg_vals.start.u_int; -#else + #else (void)kw_args; mp_obj_enumerate_t *o = m_new_obj(mp_obj_enumerate_t); o->base.type = type; o->iter = mp_getiter(args[0], NULL); o->cur = n_args > 1 ? mp_obj_get_int(args[1]) : 0; -#endif + #endif return MP_OBJ_FROM_PTR(o); } diff --git a/py/objexcept.c b/py/objexcept.c index afefee2caf..fb6424fa48 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -49,7 +49,7 @@ // Optionally allocated buffer for storing the first argument of an exception // allocated when the heap is locked. #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF -# if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0 +#if MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE > 0 #define mp_emergency_exception_buf_size MICROPY_EMERGENCY_EXCEPTION_BUF_SIZE void mp_init_emergency_exception_buf(void) { @@ -94,7 +94,7 @@ mp_obj_t mp_alloc_emergency_exception_buf(mp_obj_t size_in) { // Instance of GeneratorExit exception - needed by generator.close() // This would belong to objgenerator.c, but to keep mp_obj_exception_t // definition module-private so far, have it here. -const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t*)&mp_const_empty_tuple_obj}; +const mp_obj_exception_t mp_const_GeneratorExit_obj = {{&mp_type_GeneratorExit}, 0, 0, NULL, (mp_obj_tuple_t *)&mp_const_empty_tuple_obj}; void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { mp_obj_exception_t *o = MP_OBJ_TO_PTR(o_in); @@ -152,7 +152,7 @@ mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type, size_t n_args, con mp_obj_tuple_t *o_tuple; if (n_args == 0) { // No args, can use the empty tuple straightaway - o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj; + o_tuple = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj; } else { // Try to allocate memory for the tuple containing the args o_tuple = m_new_obj_var_maybe(mp_obj_tuple_t, mp_obj_t, n_args); @@ -163,14 +163,14 @@ mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type, size_t n_args, con // Otherwise we are free to use the whole buffer after the traceback data. if (o_tuple == NULL && mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + n_args * sizeof(mp_obj_t)) { - o_tuple = (mp_obj_tuple_t*) - ((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + EMG_TRACEBACK_ALLOC * sizeof(size_t)); + o_tuple = (mp_obj_tuple_t *) + ((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_TRACEBACK_ALLOC * sizeof(size_t)); } #endif if (o_tuple == NULL) { // No memory for a tuple, fallback to an empty tuple - o_tuple = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj; + o_tuple = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj; } else { // Have memory for a tuple so populate it o_tuple->base.type = &mp_type_tuple; @@ -235,7 +235,7 @@ void mp_obj_exception_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } } else if (attr == MP_QSTR_filename) { dest[0] = self->args->len > 2 ? self->args->items[2] : mp_const_none; - // skip winerror + // skip winerror } else if (attr == MP_QSTR_filename2) { dest[0] = self->args->len > 4 ? self->args->items[4] : mp_const_none; } @@ -259,38 +259,38 @@ MP_DEFINE_EXCEPTION(ReloadException, BaseException) MP_DEFINE_EXCEPTION(GeneratorExit, BaseException) MP_DEFINE_EXCEPTION(Exception, BaseException) #if MICROPY_PY_ASYNC_AWAIT - MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception) +MP_DEFINE_EXCEPTION(StopAsyncIteration, Exception) #endif - MP_DEFINE_EXCEPTION(StopIteration, Exception) - MP_DEFINE_EXCEPTION(ArithmeticError, Exception) - //MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError) - MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError) - MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError) - MP_DEFINE_EXCEPTION(AssertionError, Exception) - MP_DEFINE_EXCEPTION(AttributeError, Exception) - //MP_DEFINE_EXCEPTION(BufferError, Exception) - //MP_DEFINE_EXCEPTION(EnvironmentError, Exception) use OSError instead - MP_DEFINE_EXCEPTION(EOFError, Exception) - MP_DEFINE_EXCEPTION(ImportError, Exception) - //MP_DEFINE_EXCEPTION(IOError, Exception) use OSError instead - MP_DEFINE_EXCEPTION(LookupError, Exception) - MP_DEFINE_EXCEPTION(IndexError, LookupError) - MP_DEFINE_EXCEPTION(KeyError, LookupError) - MP_DEFINE_EXCEPTION(MemoryError, Exception) - MP_DEFINE_EXCEPTION(NameError, Exception) - /* +MP_DEFINE_EXCEPTION(StopIteration, Exception) +MP_DEFINE_EXCEPTION(ArithmeticError, Exception) +// MP_DEFINE_EXCEPTION(FloatingPointError, ArithmeticError) +MP_DEFINE_EXCEPTION(OverflowError, ArithmeticError) +MP_DEFINE_EXCEPTION(ZeroDivisionError, ArithmeticError) +MP_DEFINE_EXCEPTION(AssertionError, Exception) +MP_DEFINE_EXCEPTION(AttributeError, Exception) +// MP_DEFINE_EXCEPTION(BufferError, Exception) +// MP_DEFINE_EXCEPTION(EnvironmentError, Exception) use OSError instead +MP_DEFINE_EXCEPTION(EOFError, Exception) +MP_DEFINE_EXCEPTION(ImportError, Exception) +// MP_DEFINE_EXCEPTION(IOError, Exception) use OSError instead +MP_DEFINE_EXCEPTION(LookupError, Exception) +MP_DEFINE_EXCEPTION(IndexError, LookupError) +MP_DEFINE_EXCEPTION(KeyError, LookupError) +MP_DEFINE_EXCEPTION(MemoryError, Exception) +MP_DEFINE_EXCEPTION(NameError, Exception) +/* MP_DEFINE_EXCEPTION(UnboundLocalError, NameError) */ - MP_DEFINE_EXCEPTION(OSError, Exception) - MP_DEFINE_EXCEPTION(TimeoutError, OSError) - MP_DEFINE_EXCEPTION(ConnectionError, OSError) - MP_DEFINE_EXCEPTION(BrokenPipeError, ConnectionError) - /* +MP_DEFINE_EXCEPTION(OSError, Exception) +MP_DEFINE_EXCEPTION(TimeoutError, OSError) +MP_DEFINE_EXCEPTION(ConnectionError, OSError) +MP_DEFINE_EXCEPTION(BrokenPipeError, ConnectionError) +/* MP_DEFINE_EXCEPTION(ConnectionAbortedError, ConnectionError) MP_DEFINE_EXCEPTION(ConnectionRefusedError, ConnectionError) MP_DEFINE_EXCEPTION(ConnectionResetError, ConnectionError) */ - /* +/* MP_DEFINE_EXCEPTION(BlockingIOError, OSError) MP_DEFINE_EXCEPTION(ChildProcessError, OSError) MP_DEFINE_EXCEPTION(InterruptedError, OSError) @@ -302,28 +302,28 @@ MP_DEFINE_EXCEPTION(Exception, BaseException) MP_DEFINE_EXCEPTION(FileNotFoundError, OSError) MP_DEFINE_EXCEPTION(ReferenceError, Exception) */ - MP_DEFINE_EXCEPTION(RuntimeError, Exception) - MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError) - MP_DEFINE_EXCEPTION(SyntaxError, Exception) - MP_DEFINE_EXCEPTION(IndentationError, SyntaxError) - /* +MP_DEFINE_EXCEPTION(RuntimeError, Exception) +MP_DEFINE_EXCEPTION(NotImplementedError, RuntimeError) +MP_DEFINE_EXCEPTION(SyntaxError, Exception) +MP_DEFINE_EXCEPTION(IndentationError, SyntaxError) +/* MP_DEFINE_EXCEPTION(TabError, IndentationError) */ - //MP_DEFINE_EXCEPTION(SystemError, Exception) - MP_DEFINE_EXCEPTION(TypeError, Exception) +// MP_DEFINE_EXCEPTION(SystemError, Exception) +MP_DEFINE_EXCEPTION(TypeError, Exception) #if MICROPY_EMIT_NATIVE - MP_DEFINE_EXCEPTION(ViperTypeError, TypeError) +MP_DEFINE_EXCEPTION(ViperTypeError, TypeError) #endif - MP_DEFINE_EXCEPTION(ValueError, Exception) +MP_DEFINE_EXCEPTION(ValueError, Exception) #if MICROPY_PY_BUILTINS_STR_UNICODE - MP_DEFINE_EXCEPTION(UnicodeError, ValueError) - //TODO: Implement more UnicodeError subclasses which take arguments +MP_DEFINE_EXCEPTION(UnicodeError, ValueError) +// TODO: Implement more UnicodeError subclasses which take arguments #endif #if CIRCUITPY_ALARM - MP_DEFINE_EXCEPTION(DeepSleepRequest, BaseException) +MP_DEFINE_EXCEPTION(DeepSleepRequest, BaseException) #endif - MP_DEFINE_EXCEPTION(MpyError, ValueError) - /* +MP_DEFINE_EXCEPTION(MpyError, ValueError) +/* MP_DEFINE_EXCEPTION(Warning, Exception) MP_DEFINE_EXCEPTION(DeprecationWarning, Warning) MP_DEFINE_EXCEPTION(PendingDeprecationWarning, Warning) @@ -415,12 +415,12 @@ mp_obj_t mp_obj_new_exception_msg_vlist(const mp_obj_type_t *exc_type, const com // the string data), reserving room at the start for the traceback and 1-tuple. if ((o_str == NULL || o_str_buf == NULL) && mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t) - + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t) + sizeof(mp_obj_str_t) + 16) { + + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t) + sizeof(mp_obj_str_t) + 16) { used_emg_buf = true; - o_str = (mp_obj_str_t*)((uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + o_str = (mp_obj_str_t *)((uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + EMG_TRACEBACK_ALLOC * sizeof(size_t) + sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t)); - o_str_buf = (byte*)&o_str[1]; - o_str_alloc = (uint8_t*)MP_STATE_VM(mp_emergency_exception_buf) + o_str_buf = (byte *)&o_str[1]; + o_str_alloc = (uint8_t *)MP_STATE_VM(mp_emergency_exception_buf) + mp_emergency_exception_buf_size - o_str_buf; } #endif @@ -490,7 +490,7 @@ bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type) { if (mp_obj_is_native_exception_instance(self_in)) { \ self = MP_OBJ_TO_PTR(self_in); \ } else { \ - self = MP_OBJ_TO_PTR(((mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in))->subobj[0]); \ + self = MP_OBJ_TO_PTR(((mp_obj_instance_t *)MP_OBJ_TO_PTR(self_in))->subobj[0]); \ } void mp_obj_exception_clear_traceback(mp_obj_t self_in) { @@ -512,7 +512,7 @@ void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qs #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF if (mp_emergency_exception_buf_size >= EMG_TRACEBACK_ALLOC * sizeof(size_t)) { // There is room in the emergency buffer for traceback data - size_t *tb = (size_t*)MP_STATE_VM(mp_emergency_exception_buf); + size_t *tb = (size_t *)MP_STATE_VM(mp_emergency_exception_buf); self->traceback_data = tb; self->traceback_alloc = EMG_TRACEBACK_ALLOC; } else { @@ -530,7 +530,7 @@ void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qs self->traceback_len = 0; } else if (self->traceback_len + TRACEBACK_ENTRY_LEN > self->traceback_alloc) { #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF - if (self->traceback_data == (size_t*)MP_STATE_VM(mp_emergency_exception_buf)) { + if (self->traceback_data == (size_t *)MP_STATE_VM(mp_emergency_exception_buf)) { // Can't resize the emergency buffer return; } @@ -619,7 +619,7 @@ STATIC mp_obj_t code_make_new(qstr file, qstr block) { mp_obj_new_bytearray(0, NULL), // co_lnotab }; - return namedtuple_make_new((const mp_obj_type_t*)&code_type_obj, 15, elems, NULL); + return namedtuple_make_new((const mp_obj_type_t *)&code_type_obj, 15, elems, NULL); } STATIC const mp_obj_namedtuple_type_t frame_type_obj = { @@ -662,7 +662,7 @@ STATIC mp_obj_t frame_make_new(mp_obj_t f_code, int f_lineno) { mp_const_none, // f_trace }; - return namedtuple_make_new((const mp_obj_type_t*)&frame_type_obj, 8, elems, NULL); + return namedtuple_make_new((const mp_obj_type_t *)&frame_type_obj, 8, elems, NULL); } STATIC const mp_obj_namedtuple_type_t traceback_type_obj = { @@ -699,7 +699,7 @@ STATIC mp_obj_t traceback_from_values(size_t *values, mp_obj_t tb_next) { tb_next, }; - return namedtuple_make_new((const mp_obj_type_t*)&traceback_type_obj, 4, elems, NULL); + return namedtuple_make_new((const mp_obj_type_t *)&traceback_type_obj, 4, elems, NULL); }; mp_obj_t mp_obj_exception_get_traceback_obj(mp_obj_t self_in) { diff --git a/py/objexcept.h b/py/objexcept.h index c19658427a..d7b39add87 100644 --- a/py/objexcept.h +++ b/py/objexcept.h @@ -41,13 +41,13 @@ void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kin void mp_obj_exception_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest); #define MP_DEFINE_EXCEPTION(exc_name, base_name) \ -const mp_obj_type_t mp_type_ ## exc_name = { \ - { &mp_type_type }, \ - .name = MP_QSTR_ ## exc_name, \ - .print = mp_obj_exception_print, \ - .make_new = mp_obj_exception_make_new, \ - .attr = mp_obj_exception_attr, \ - .parent = &mp_type_ ## base_name, \ -}; + const mp_obj_type_t mp_type_##exc_name = { \ + { &mp_type_type }, \ + .name = MP_QSTR_##exc_name, \ + .print = mp_obj_exception_print, \ + .make_new = mp_obj_exception_make_new, \ + .attr = mp_obj_exception_attr, \ + .parent = &mp_type_##base_name, \ + }; #endif // MICROPY_INCLUDED_PY_OBJEXCEPT_H diff --git a/py/objfloat.c b/py/objfloat.c index 329a8b90e0..5c0a87ea3d 100644 --- a/py/objfloat.c +++ b/py/objfloat.c @@ -65,17 +65,19 @@ const mp_obj_float_t mp_const_float_pi_obj = {{&mp_type_float}, M_PI}; #if MICROPY_FLOAT_HIGH_QUALITY_HASH // must return actual integer value if it fits in mp_int_t mp_int_t mp_float_hash(mp_float_t src) { -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE -typedef uint64_t mp_float_uint_t; -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT -typedef uint32_t mp_float_uint_t; -#endif + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + typedef uint64_t mp_float_uint_t; + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + typedef uint32_t mp_float_uint_t; + #endif union { mp_float_t f; #if MP_ENDIANNESS_LITTLE - struct { mp_float_uint_t frc:MP_FLOAT_FRAC_BITS, exp:MP_FLOAT_EXP_BITS, sgn:1; } p; + struct { mp_float_uint_t frc : MP_FLOAT_FRAC_BITS, exp : MP_FLOAT_EXP_BITS, sgn : 1; + } p; #else - struct { mp_float_uint_t sgn:1, exp:MP_FLOAT_EXP_BITS, frc:MP_FLOAT_FRAC_BITS; } p; + struct { mp_float_uint_t sgn : 1, exp : MP_FLOAT_EXP_BITS, frc : MP_FLOAT_FRAC_BITS; + } p; #endif mp_float_uint_t i; } u = {.f = src}; @@ -114,17 +116,17 @@ typedef uint32_t mp_float_uint_t; STATIC void float_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_float_t o_val = mp_obj_float_get(o_in); -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT char buf[16]; #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C const int precision = 6; #else const int precision = 7; #endif -#else + #else char buf[32]; const int precision = 16; -#endif + #endif mp_format_float(o_val, buf, sizeof(buf), 'g', precision, '\0'); mp_print_str(print, buf); if (strchr(buf, '.') == NULL && strchr(buf, 'e') == NULL && strchr(buf, 'n') == NULL) { @@ -161,10 +163,14 @@ STATIC mp_obj_t float_make_new(const mp_obj_type_t *type_in, size_t n_args, cons STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_float_t val = mp_obj_float_get(o_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(val != 0); - case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mp_float_hash(val)); - case MP_UNARY_OP_POSITIVE: return o_in; - case MP_UNARY_OP_NEGATIVE: return mp_obj_new_float(-val); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(val != 0); + case MP_UNARY_OP_HASH: + return MP_OBJ_NEW_SMALL_INT(mp_float_hash(val)); + case MP_UNARY_OP_POSITIVE: + return o_in; + case MP_UNARY_OP_NEGATIVE: + return mp_obj_new_float(-val); case MP_UNARY_OP_ABS: { // TODO check for NaN etc if (val < 0) { @@ -173,17 +179,18 @@ STATIC mp_obj_t float_unary_op(mp_unary_op_t op, mp_obj_t o_in) { return o_in; } } - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } STATIC mp_obj_t float_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { mp_float_t lhs_val = mp_obj_float_get(lhs_in); -#if MICROPY_PY_BUILTINS_COMPLEX + #if MICROPY_PY_BUILTINS_COMPLEX if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_complex)) { return mp_obj_complex_binary_op(op, lhs_val, 0, rhs_in); } else -#endif + #endif { return mp_obj_float_binary_op(op, lhs_val, rhs_in); } @@ -258,15 +265,21 @@ mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t switch (op) { case MP_BINARY_OP_ADD: - case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break; + case MP_BINARY_OP_INPLACE_ADD: + lhs_val += rhs_val; + break; case MP_BINARY_OP_SUBTRACT: - case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break; + case MP_BINARY_OP_INPLACE_SUBTRACT: + lhs_val -= rhs_val; + break; case MP_BINARY_OP_MULTIPLY: - case MP_BINARY_OP_INPLACE_MULTIPLY: lhs_val *= rhs_val; break; + case MP_BINARY_OP_INPLACE_MULTIPLY: + lhs_val *= rhs_val; + break; case MP_BINARY_OP_FLOOR_DIVIDE: case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: if (rhs_val == 0) { - zero_division_error: + zero_division_error: mp_raise_msg(&mp_type_ZeroDivisionError, translate("division by zero")); } // Python specs require that x == (x//y)*y + (x%y) so we must @@ -321,11 +334,16 @@ mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t }; return mp_obj_new_tuple(2, tuple); } - case MP_BINARY_OP_LESS: return mp_obj_new_bool(lhs_val < rhs_val); - case MP_BINARY_OP_MORE: return mp_obj_new_bool(lhs_val > rhs_val); - case MP_BINARY_OP_EQUAL: return mp_obj_new_bool(lhs_val == rhs_val); - case MP_BINARY_OP_LESS_EQUAL: return mp_obj_new_bool(lhs_val <= rhs_val); - case MP_BINARY_OP_MORE_EQUAL: return mp_obj_new_bool(lhs_val >= rhs_val); + case MP_BINARY_OP_LESS: + return mp_obj_new_bool(lhs_val < rhs_val); + case MP_BINARY_OP_MORE: + return mp_obj_new_bool(lhs_val > rhs_val); + case MP_BINARY_OP_EQUAL: + return mp_obj_new_bool(lhs_val == rhs_val); + case MP_BINARY_OP_LESS_EQUAL: + return mp_obj_new_bool(lhs_val <= rhs_val); + case MP_BINARY_OP_MORE_EQUAL: + return mp_obj_new_bool(lhs_val >= rhs_val); default: return MP_OBJ_NULL; // op not supported @@ -337,7 +355,7 @@ mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t // which are large. mp_float_t uint64_to_float(uint64_t ui64) { // 4294967296 = 2^32 - return (mp_float_t) ((uint32_t) (ui64 >> 32) * 4294967296.0f + (uint32_t) (ui64 & 0xffffffff)); + return (mp_float_t)((uint32_t)(ui64 >> 32) * 4294967296.0f + (uint32_t)(ui64 & 0xffffffff)); } // Convert a uint64_t to a 32-bit float to a uint64_t without invoking extra math routines. @@ -345,9 +363,9 @@ mp_float_t uint64_to_float(uint64_t ui64) { // Assume f >= 0. uint64_t float_to_uint64(float f) { // 4294967296 = 2^32 - const uint32_t upper_half = (uint32_t) (f / 4294967296.0f); - const uint32_t lower_half = (uint32_t) f; - return (((uint64_t) upper_half) << 32) + lower_half; + const uint32_t upper_half = (uint32_t)(f / 4294967296.0f); + const uint32_t lower_half = (uint32_t)f; + return (((uint64_t)upper_half) << 32) + lower_half; } #pragma GCC diagnostic pop diff --git a/py/objfun.c b/py/objfun.c index 933044ef71..69045c6323 100644 --- a/py/objfun.c +++ b/py/objfun.c @@ -210,7 +210,7 @@ STATIC void dump_args(const mp_obj_t *a, size_t sz) { \ /* state size in bytes */ \ state_size_out_var = n_state_out_var * sizeof(mp_obj_t) \ - + n_exc_stack * sizeof(mp_exc_stack_t); \ + + n_exc_stack * sizeof(mp_exc_stack_t); \ } #define INIT_CODESTATE(code_state, _fun_bc, n_args, n_kw, args) \ @@ -286,7 +286,7 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size mp_vm_return_kind_t vm_return_kind = mp_execute_bytecode(code_state, MP_OBJ_NULL); mp_globals_set(code_state->old_globals); -#if VM_DETECT_STACK_OVERFLOW + #if VM_DETECT_STACK_OVERFLOW if (vm_return_kind == MP_VM_RETURN_NORMAL) { if (code_state->sp < code_state->state) { printf("VM stack underflow: " INT_FMT "\n", code_state->sp - code_state->state); @@ -310,7 +310,7 @@ STATIC mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size assert(0); } } -#endif + #endif mp_obj_t result; if (vm_return_kind == MP_VM_RETURN_NORMAL) { @@ -354,14 +354,14 @@ STATIC void fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { const mp_obj_type_t mp_type_fun_bc = { { &mp_type_type }, .name = MP_QSTR_function, -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT .print = fun_bc_print, -#endif + #endif .call = fun_bc_call, .unary_op = mp_generic_unary_op, -#if MICROPY_PY_FUNCTION_ATTRS + #if MICROPY_PY_FUNCTION_ATTRS .attr = fun_bc_attr, -#endif + #endif }; mp_obj_t mp_obj_new_fun_bc(mp_obj_t def_args_in, mp_obj_t def_kw_args, const byte *code, const mp_uint_t *const_table) { @@ -398,7 +398,7 @@ mp_obj_t mp_obj_new_fun_bc(mp_obj_t def_args_in, mp_obj_t def_kw_args, const byt STATIC mp_obj_t fun_native_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { MP_STACK_CHECK(); mp_obj_fun_bc_t *self = self_in; - mp_call_fun_t fun = MICROPY_MAKE_POINTER_CALLABLE((void*)self->bytecode); + mp_call_fun_t fun = MICROPY_MAKE_POINTER_CALLABLE((void *)self->bytecode); return fun(self_in, n_args, n_kw, args); } @@ -410,7 +410,7 @@ STATIC const mp_obj_type_t mp_type_fun_native = { }; mp_obj_t mp_obj_new_fun_native(mp_obj_t def_args_in, mp_obj_t def_kw_args, const void *fun_data, const mp_uint_t *const_table) { - mp_obj_fun_bc_t *o = mp_obj_new_fun_bc(def_args_in, def_kw_args, (const byte*)fun_data, const_table); + mp_obj_fun_bc_t *o = mp_obj_new_fun_bc(def_args_in, def_kw_args, (const byte *)fun_data, const_table); o->base.type = &mp_type_fun_native; return o; } @@ -459,7 +459,7 @@ STATIC mp_obj_t fun_viper_call(mp_obj_t self_in, size_t n_args, size_t n_kw, con mp_convert_obj_to_native(args[1], self->type_sig >> 8), mp_convert_obj_to_native(args[2], self->type_sig >> 12), mp_convert_obj_to_native(args[3], self->type_sig >> 16) - ); + ); } return mp_convert_native_to_obj(ret, self->type_sig); @@ -521,11 +521,11 @@ STATIC mp_uint_t convert_obj_for_inline_asm(mp_obj_t obj) { } else { mp_obj_type_t *type = mp_obj_get_type(obj); if (0) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT } else if (type == &mp_type_float) { // convert float to int (could also pass in float registers) return (mp_int_t)mp_obj_float_get(obj); -#endif + #endif } else if (type == &mp_type_tuple || type == &mp_type_list) { // pointer to start of tuple (could pass length, but then could use len(x) for that) size_t len; @@ -569,7 +569,7 @@ STATIC mp_obj_t fun_asm_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const convert_obj_for_inline_asm(args[1]), convert_obj_for_inline_asm(args[2]), convert_obj_for_inline_asm(args[3]) - ); + ); } return mp_convert_native_to_obj(ret, self->type_sig); diff --git a/py/objgenerator.c b/py/objgenerator.c index 5e651ac269..9ca5812d84 100644 --- a/py/objgenerator.c +++ b/py/objgenerator.c @@ -54,7 +54,7 @@ typedef struct _mp_obj_gen_instance_t { STATIC mp_obj_t gen_wrap_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { mp_obj_gen_wrap_t *self = MP_OBJ_TO_PTR(self_in); - mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t*)self->fun; + mp_obj_fun_bc_t *self_fun = (mp_obj_fun_bc_t *)self->fun; assert(self_fun->base.type == &mp_type_fun_bc); // bytecode prelude: get state size and exception stack size @@ -95,12 +95,12 @@ mp_obj_t mp_obj_new_gen_wrap(mp_obj_t fun, bool is_coroutine) { STATIC void gen_instance_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in); -#if MICROPY_PY_ASYNC_AWAIT + #if MICROPY_PY_ASYNC_AWAIT if (self->coroutine_generator) { mp_printf(print, "", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self); return; } -#endif + #endif mp_printf(print, "", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self); } @@ -204,13 +204,13 @@ STATIC mp_obj_t gen_resume_and_raise(mp_obj_t self_in, mp_obj_t send_value, mp_o } STATIC mp_obj_t gen_instance_iternext(mp_obj_t self_in) { -#if MICROPY_PY_ASYNC_AWAIT + #if MICROPY_PY_ASYNC_AWAIT // This translate is literally too much for m0 boards mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in); if (self->coroutine_generator) { mp_raise_TypeError(translate("'coroutine' object is not an iterator")); } -#endif + #endif return gen_resume_and_raise(self_in, mp_const_none, MP_OBJ_NULL); } @@ -228,7 +228,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(gen_instance_send_obj, gen_instance_send); #if MICROPY_PY_ASYNC_AWAIT STATIC mp_obj_t gen_instance_await(mp_obj_t self_in) { mp_obj_gen_instance_t *self = MP_OBJ_TO_PTR(self_in); - if ( !self->coroutine_generator ) { + if (!self->coroutine_generator) { // Pretend like a generator does not have this coroutine behavior. // Pay no attention to the dir() behind the curtain nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, @@ -309,5 +309,5 @@ const mp_obj_type_t mp_type_gen_instance = { .unary_op = mp_generic_unary_op, .getiter = mp_identity_getiter, .iternext = gen_instance_iternext, - .locals_dict = (mp_obj_dict_t*)&gen_instance_locals_dict, + .locals_dict = (mp_obj_dict_t *)&gen_instance_locals_dict, }; diff --git a/py/objgetitemiter.c b/py/objgetitemiter.c index 44e8fe8894..26ff9ad1d0 100644 --- a/py/objgetitemiter.c +++ b/py/objgetitemiter.c @@ -46,7 +46,7 @@ STATIC mp_obj_t it_iternext(mp_obj_t self_in) { return value; } else { // an exception was raised - mp_obj_type_t *t = (mp_obj_type_t*)((mp_obj_base_t*)nlr.ret_val)->type; + mp_obj_type_t *t = (mp_obj_type_t *)((mp_obj_base_t *)nlr.ret_val)->type; if (t == &mp_type_StopIteration || t == &mp_type_IndexError) { // return MP_OBJ_STOP_ITERATION instead of raising return MP_OBJ_STOP_ITERATION; @@ -67,7 +67,7 @@ STATIC const mp_obj_type_t it_type = { // args are those returned from mp_load_method_maybe (ie either an attribute or a method) mp_obj_t mp_obj_new_getitem_iter(mp_obj_t *args, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_getitem_iter_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_getitem_iter_t *o = (mp_obj_getitem_iter_t*)iter_buf; + mp_obj_getitem_iter_t *o = (mp_obj_getitem_iter_t *)iter_buf; o->base.type = &it_type; o->args[0] = args[0]; o->args[1] = args[1]; diff --git a/py/objint.c b/py/objint.c index 5a33ccbc04..50062351e6 100644 --- a/py/objint.c +++ b/py/objint.c @@ -59,10 +59,10 @@ STATIC mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t l; const char *s = mp_obj_str_get_data(args[0], &l); return mp_parse_num_integer(s, l, 0, NULL); -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(args[0])) { return mp_obj_new_int_from_float(mp_obj_float_get(args[0])); -#endif + #endif } else { // try to convert to small int (eg from bool) return MP_OBJ_NEW_SMALL_INT(mp_obj_get_int(args[0])); @@ -90,26 +90,26 @@ typedef enum { STATIC mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) { union { mp_float_t f; -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT uint32_t i; -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE uint32_t i[2]; -#endif + #endif } u = {val}; uint32_t e; -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT e = u.i; -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE e = u.i[MP_ENDIANNESS_LITTLE]; -#endif + #endif #define MP_FLOAT_SIGN_SHIFT_I32 ((MP_FLOAT_FRAC_BITS + MP_FLOAT_EXP_BITS) % 32) #define MP_FLOAT_EXP_SHIFT_I32 (MP_FLOAT_FRAC_BITS % 32) if (e & (1U << MP_FLOAT_SIGN_SHIFT_I32)) { -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE e |= u.i[MP_ENDIANNESS_BIG] != 0; -#endif + #endif if ((e & ~(1 << MP_FLOAT_SIGN_SHIFT_I32)) == 0) { // handle case of -0 (when sign is set but rest of bits are zero) e = 0; @@ -124,16 +124,16 @@ STATIC mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) { if (e <= ((8 * sizeof(uintptr_t) + MP_FLOAT_EXP_BIAS - 3) << MP_FLOAT_EXP_SHIFT_I32)) { return MP_FP_CLASS_FIT_SMALLINT; } -#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG + #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG if (e <= (((sizeof(long long) * BITS_PER_BYTE) + MP_FLOAT_EXP_BIAS - 2) << MP_FLOAT_EXP_SHIFT_I32)) { return MP_FP_CLASS_FIT_LONGINT; } -#endif -#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ + #endif + #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ return MP_FP_CLASS_FIT_LONGINT; -#else + #else return MP_FP_CLASS_OVERFLOW; -#endif + #endif } #undef MP_FLOAT_SIGN_SHIFT_I32 #undef MP_FLOAT_EXP_SHIFT_I32 @@ -222,7 +222,7 @@ size_t mp_int_format_size(size_t num_bits, int base, const char *prefix, char co // The resulting formatted string will be returned from this function and the // formatted size will be in *fmt_size. char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in, - int base, const char *prefix, char base_char, char comma) { + int base, const char *prefix, char base_char, char comma) { fmt_int_t num; #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE // Only have small ints; get the integer value to format. @@ -302,13 +302,12 @@ char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_co #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE -void mp_obj_int_buffer_overflow_check(mp_obj_t self_in, size_t nbytes, bool is_signed) -{ +void mp_obj_int_buffer_overflow_check(mp_obj_t self_in, size_t nbytes, bool is_signed) { if (is_signed) { // self must be < 2**(bits - 1) mp_obj_t edge = mp_binary_op(MP_BINARY_OP_INPLACE_LSHIFT, - mp_obj_new_int(1), - mp_obj_new_int(nbytes * 8 - 1)); + mp_obj_new_int(1), + mp_obj_new_int(nbytes * 8 - 1)); if (mp_binary_op(MP_BINARY_OP_LESS, self_in, edge) == mp_const_true) { // and >= -2**(bits - 1) @@ -322,8 +321,8 @@ void mp_obj_int_buffer_overflow_check(mp_obj_t self_in, size_t nbytes, bool is_s if (mp_obj_int_sign(self_in) >= 0) { // and < 2**(bits) mp_obj_t edge = mp_binary_op(MP_BINARY_OP_INPLACE_LSHIFT, - mp_obj_new_int(1), - mp_obj_new_int(nbytes * 8)); + mp_obj_new_int(1), + mp_obj_new_int(nbytes * 8)); if (mp_binary_op(MP_BINARY_OP_LESS, self_in, edge) == mp_const_true) { return; @@ -462,8 +461,7 @@ STATIC mp_obj_t int_bit_length(mp_obj_t self_in) { #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE if (!MP_OBJ_IS_SMALL_INT(self_in)) { return mp_obj_int_bit_length_impl(self_in); - } - else + } else #endif { mp_int_t int_val = MP_OBJ_SMALL_INT_VALUE(self_in); @@ -471,7 +469,7 @@ STATIC mp_obj_t int_bit_length(mp_obj_t self_in) { (int_val == 0) ? 0 : (int_val == MP_SMALL_INT_MIN) ? 8 * sizeof(mp_int_t) : (int_val < 0) ? 8 * sizeof(long) - __builtin_clzl(-int_val) : - 8 * sizeof(long) - __builtin_clzl(int_val); + 8 * sizeof(long) - __builtin_clzl(int_val); return mp_obj_new_int_from_uint(value); } @@ -488,7 +486,7 @@ STATIC mp_obj_t int_from_bytes(size_t n_args, const mp_obj_t *args) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); - const byte* buf = (const byte*)bufinfo.buf; + const byte *buf = (const byte *)bufinfo.buf; int delta = 1; if (args[2] == MP_OBJ_NEW_QSTR(MP_QSTR_little)) { buf += bufinfo.len - 1; @@ -533,7 +531,7 @@ STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *pos_args, mp_map_t * vstr_t vstr; vstr_init_len(&vstr, len); - byte *data = (byte*)vstr.buf; + byte *data = (byte *)vstr.buf; memset(data, 0, len); #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE @@ -559,9 +557,9 @@ STATIC mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *pos_args, mp_map_t * STATIC MP_DEFINE_CONST_FUN_OBJ_KW(int_to_bytes_obj, 3, int_to_bytes); STATIC const mp_rom_map_elem_t int_locals_dict_table[] = { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT { MP_ROM_QSTR(MP_QSTR_bit_length), MP_ROM_PTR(&int_bit_length_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_from_bytes), MP_ROM_PTR(&int_from_bytes_obj) }, { MP_ROM_QSTR(MP_QSTR_to_bytes), MP_ROM_PTR(&int_to_bytes_obj) }, }; @@ -575,5 +573,5 @@ const mp_obj_type_t mp_type_int = { .make_new = mp_obj_int_make_new, .unary_op = mp_obj_int_unary_op, .binary_op = mp_obj_int_binary_op, - .locals_dict = (mp_obj_dict_t*)&int_locals_dict, + .locals_dict = (mp_obj_dict_t *)&int_locals_dict, }; diff --git a/py/objint.h b/py/objint.h index 68997ced27..9595c1b3a7 100644 --- a/py/objint.h +++ b/py/objint.h @@ -31,11 +31,11 @@ typedef struct _mp_obj_int_t { mp_obj_base_t base; -#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG + #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG mp_longint_impl_t val; -#elif MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ + #elif MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ mpz_t mpz; -#endif + #endif } mp_obj_int_t; extern const mp_obj_int_t mp_maxsize_obj; @@ -50,9 +50,9 @@ mp_obj_int_t *mp_obj_int_new_mpz(void); void mp_obj_int_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind); char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in, - int base, const char *prefix, char base_char, char comma); + int base, const char *prefix, char base_char, char comma); char *mp_obj_int_formatted_impl(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in, - int base, const char *prefix, char base_char, char comma); + int base, const char *prefix, char base_char, char comma); #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE void mp_obj_int_buffer_overflow_check(mp_obj_t self_in, size_t nbytes, bool is_signed); #endif diff --git a/py/objint_longlong.c b/py/objint_longlong.c index 0a65098c78..63e3464a1a 100644 --- a/py/objint_longlong.c +++ b/py/objint_longlong.c @@ -53,7 +53,7 @@ mp_obj_t mp_obj_int_bit_length_impl(mp_obj_t self_in) { (val == 0) ? 0 : (val == MP_SMALL_INT_MIN) ? 8 * sizeof(long long) : (val < 0) ? 8 * sizeof(long long) - __builtin_clzll(-val) : - 8 * sizeof(long long) - __builtin_clzll(val)); + 8 * sizeof(long long) - __builtin_clzll(val)); } mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf) { @@ -108,15 +108,20 @@ int mp_obj_int_sign(mp_obj_t self_in) { mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_obj_int_t *o = o_in; switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(o->val != 0); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(o->val != 0); // truncate value to fit in mp_int_t, which gives the same hash as // small int if the value fits without truncation - case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT((mp_int_t)o->val); + case MP_UNARY_OP_HASH: + return MP_OBJ_NEW_SMALL_INT((mp_int_t)o->val); - case MP_UNARY_OP_POSITIVE: return o_in; - case MP_UNARY_OP_NEGATIVE: return mp_obj_new_int_from_ll(-o->val); - case MP_UNARY_OP_INVERT: return mp_obj_new_int_from_ll(~o->val); + case MP_UNARY_OP_POSITIVE: + return o_in; + case MP_UNARY_OP_NEGATIVE: + return mp_obj_new_int_from_ll(-o->val); + case MP_UNARY_OP_INVERT: + return mp_obj_new_int_from_ll(~o->val); case MP_UNARY_OP_ABS: { mp_obj_int_t *self = MP_OBJ_TO_PTR(o_in); if (self->val >= 0) { @@ -127,7 +132,8 @@ mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) { self->val = -self->val; return MP_OBJ_FROM_PTR(self); } - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -139,13 +145,13 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs_in); } else { assert(MP_OBJ_IS_TYPE(lhs_in, &mp_type_int)); - lhs_val = ((mp_obj_int_t*)lhs_in)->val; + lhs_val = ((mp_obj_int_t *)lhs_in)->val; } if (MP_OBJ_IS_SMALL_INT(rhs_in)) { rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs_in); } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_int)) { - rhs_val = ((mp_obj_int_t*)rhs_in)->val; + rhs_val = ((mp_obj_int_t *)rhs_in)->val; } else { // delegate to generic function to check for extra cases return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in); diff --git a/py/objint_mpz.c b/py/objint_mpz.c index d32fdfbe8d..3d8de47985 100644 --- a/py/objint_mpz.c +++ b/py/objint_mpz.c @@ -48,27 +48,27 @@ STATIC const mpz_dig_t maxsize_dig[] = { #define NUM_DIG 1 (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 0) & DIG_MASK, #if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 0) > DIG_MASK - #undef NUM_DIG +#undef NUM_DIG #define NUM_DIG 2 - (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 1) & DIG_MASK, - #if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 1) > DIG_MASK - #undef NUM_DIG + (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 1) & DIG_MASK, + #if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 1) > DIG_MASK +#undef NUM_DIG #define NUM_DIG 3 - (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 2) & DIG_MASK, - #if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 2) > DIG_MASK - #undef NUM_DIG + (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 2) & DIG_MASK, + #if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 2) > DIG_MASK +#undef NUM_DIG #define NUM_DIG 4 - (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 3) & DIG_MASK, - #if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 3) > DIG_MASK - #error cannot encode MP_SSIZE_MAX as mpz - #endif - #endif - #endif + (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 3) & DIG_MASK, + #if (MP_SSIZE_MAX >> MPZ_DIG_SIZE * 3) > DIG_MASK + #error cannot encode MP_SSIZE_MAX as mpz + #endif + #endif + #endif #endif }; const mp_obj_int_t mp_maxsize_obj = { {&mp_type_int}, - {.fixed_dig = 1, .len = NUM_DIG, .alloc = NUM_DIG, .dig = (mpz_dig_t*)maxsize_dig} + {.fixed_dig = 1, .len = NUM_DIG, .alloc = NUM_DIG, .dig = (mpz_dig_t *)maxsize_dig} }; #undef DIG_MASK #undef NUM_DIG @@ -91,7 +91,7 @@ mp_obj_int_t *mp_obj_int_new_mpz(void) { // // This particular routine should only be called for the mpz representation of the int. char *mp_obj_int_formatted_impl(char **buf, size_t *buf_size, size_t *fmt_size, mp_const_obj_t self_in, - int base, const char *prefix, char base_char, char comma) { + int base, const char *prefix, char base_char, char comma) { assert(MP_OBJ_IS_TYPE(self_in, &mp_type_int)); const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); @@ -150,11 +150,20 @@ int mp_obj_int_sign(mp_obj_t self_in) { mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_obj_int_t *o = MP_OBJ_TO_PTR(o_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(!mpz_is_zero(&o->mpz)); - case MP_UNARY_OP_HASH: return MP_OBJ_NEW_SMALL_INT(mpz_hash(&o->mpz)); - case MP_UNARY_OP_POSITIVE: return o_in; - case MP_UNARY_OP_NEGATIVE: { mp_obj_int_t *o2 = mp_obj_int_new_mpz(); mpz_neg_inpl(&o2->mpz, &o->mpz); return MP_OBJ_FROM_PTR(o2); } - case MP_UNARY_OP_INVERT: { mp_obj_int_t *o2 = mp_obj_int_new_mpz(); mpz_not_inpl(&o2->mpz, &o->mpz); return MP_OBJ_FROM_PTR(o2); } + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(!mpz_is_zero(&o->mpz)); + case MP_UNARY_OP_HASH: + return MP_OBJ_NEW_SMALL_INT(mpz_hash(&o->mpz)); + case MP_UNARY_OP_POSITIVE: + return o_in; + case MP_UNARY_OP_NEGATIVE: { mp_obj_int_t *o2 = mp_obj_int_new_mpz(); + mpz_neg_inpl(&o2->mpz, &o->mpz); + return MP_OBJ_FROM_PTR(o2); + } + case MP_UNARY_OP_INVERT: { mp_obj_int_t *o2 = mp_obj_int_new_mpz(); + mpz_not_inpl(&o2->mpz, &o->mpz); + return MP_OBJ_FROM_PTR(o2); + } case MP_UNARY_OP_ABS: { mp_obj_int_t *self = MP_OBJ_TO_PTR(o_in); if (self->mpz.neg == 0) { @@ -164,7 +173,8 @@ mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mpz_abs_inpl(&self2->mpz, &self->mpz); return MP_OBJ_FROM_PTR(self2); } - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -180,7 +190,7 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i zlhs = &z_int; } else { assert(MP_OBJ_IS_TYPE(lhs_in, &mp_type_int)); - zlhs = &((mp_obj_int_t*)MP_OBJ_TO_PTR(lhs_in))->mpz; + zlhs = &((mp_obj_int_t *)MP_OBJ_TO_PTR(lhs_in))->mpz; } // if rhs is small int, then lhs was not (otherwise mp_binary_op handles it) @@ -188,22 +198,22 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i mpz_init_fixed_from_int(&z_int, z_int_dig, MPZ_NUM_DIG_FOR_INT, MP_OBJ_SMALL_INT_VALUE(rhs_in)); zrhs = &z_int; } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_int)) { - zrhs = &((mp_obj_int_t*)MP_OBJ_TO_PTR(rhs_in))->mpz; -#if MICROPY_PY_BUILTINS_FLOAT + zrhs = &((mp_obj_int_t *)MP_OBJ_TO_PTR(rhs_in))->mpz; + #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(rhs_in)) { return mp_obj_float_binary_op(op, mpz_as_float(zlhs), rhs_in); -#if MICROPY_PY_BUILTINS_COMPLEX + #if MICROPY_PY_BUILTINS_COMPLEX } else if (MP_OBJ_IS_TYPE(rhs_in, &mp_type_complex)) { return mp_obj_complex_binary_op(op, mpz_as_float(zlhs), 0, rhs_in); -#endif -#endif + #endif + #endif } else { // delegate to generic function to check for extra cases return mp_obj_int_binary_op_extra_cases(op, lhs_in, rhs_in); } if (0) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT } else if (op == MP_BINARY_OP_TRUE_DIVIDE || op == MP_BINARY_OP_INPLACE_TRUE_DIVIDE) { if (mpz_is_zero(zrhs)) { goto zero_division_error; @@ -211,7 +221,7 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i mp_float_t flhs = mpz_as_float(zlhs); mp_float_t frhs = mpz_as_float(zrhs); return mp_obj_new_float(flhs / frhs); -#endif + #endif } else if (op >= MP_BINARY_OP_INPLACE_OR && op < MP_BINARY_OP_CONTAINS) { mp_obj_int_t *res = mp_obj_int_new_mpz(); @@ -232,10 +242,11 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i case MP_BINARY_OP_FLOOR_DIVIDE: case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: { if (mpz_is_zero(zrhs)) { - zero_division_error: + zero_division_error: mp_raise_msg(&mp_type_ZeroDivisionError, translate("division by zero")); } - mpz_t rem; mpz_init_zero(&rem); + mpz_t rem; + mpz_init_zero(&rem); mpz_divmod_inpl(&res->mpz, &rem, zlhs, zrhs); mpz_deinit(&rem); break; @@ -245,7 +256,8 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i if (mpz_is_zero(zrhs)) { goto zero_division_error; } - mpz_t quo; mpz_init_zero(&quo); + mpz_t quo; + mpz_init_zero(&quo); mpz_divmod_inpl(&quo, &res->mpz, zlhs, zrhs); mpz_deinit(&quo); break; @@ -342,7 +354,7 @@ mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) { mp_raise_TypeError(translate("pow() with 3 arguments requires integers")); } else { mp_obj_t result = mp_obj_new_int_from_ull(0); // Use the _from_ull version as this forces an mpz int - mp_obj_int_t *res_p = (mp_obj_int_t *) MP_OBJ_TO_PTR(result); + mp_obj_int_t *res_p = (mp_obj_int_t *)MP_OBJ_TO_PTR(result); mpz_t l_temp, r_temp, m_temp; mpz_t *lhs = mp_mpz_for_int(base, &l_temp); @@ -355,9 +367,15 @@ mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) { mpz_pow3_inpl(&(res_p->mpz), lhs, rhs, mod); - if (lhs == &l_temp) { mpz_deinit(lhs); } - if (rhs == &r_temp) { mpz_deinit(rhs); } - if (mod == &m_temp) { mpz_deinit(mod); } + if (lhs == &l_temp) { + mpz_deinit(lhs); + } + if (rhs == &r_temp) { + mpz_deinit(rhs); + } + if (mod == &m_temp) { + mpz_deinit(mod); + } return result; } } diff --git a/py/objlist.c b/py/objlist.c index 7aa4ee89c9..d8b0870e57 100644 --- a/py/objlist.c +++ b/py/objlist.c @@ -95,15 +95,18 @@ STATIC mp_obj_t list_make_new(const mp_obj_type_t *type_in, size_t n_args, const STATIC mp_obj_t list_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_list_t *self = mp_instance_cast_to_native_base(self_in, &mp_type_list); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(self->len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(self->len); #if MICROPY_PY_SYS_GETSIZEOF case MP_UNARY_OP_SIZEOF: { size_t sz = sizeof(*self) + sizeof(mp_obj_t) * self->alloc; return MP_OBJ_NEW_SMALL_INT(sz); } #endif - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -162,7 +165,7 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_obj_list_t *self = mp_instance_cast_to_native_base(self_in, &mp_type_list); if (value == MP_OBJ_NULL) { // delete -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) { @@ -170,21 +173,21 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } mp_int_t len_adj = slice.start - slice.stop; - //printf("Len adj: %d\n", len_adj); + // printf("Len adj: %d\n", len_adj); assert(len_adj <= 0); - mp_seq_replace_slice_no_grow(self->items, self->len, slice.start, slice.stop, self->items/*NULL*/, 0, sizeof(*self->items)); + mp_seq_replace_slice_no_grow(self->items, self->len, slice.start, slice.stop, self->items /*NULL*/, 0, sizeof(*self->items)); // Clear "freed" elements at the end of list mp_seq_clear(self->items, self->len + len_adj, self->len, sizeof(*self->items)); self->len += len_adj; return mp_const_none; } -#endif + #endif mp_obj_t args[2] = {self, index}; list_pop(2, args); return mp_const_none; } else if (value == MP_OBJ_SENTINEL) { // load -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) { @@ -194,20 +197,21 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t); return MP_OBJ_FROM_PTR(res); } -#endif + #endif size_t index_val = mp_get_index(self->base.type, self->len, index, false); return self->items[index_val]; } else { -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { - size_t value_len; mp_obj_t *value_items; + size_t value_len; + mp_obj_t *value_items; mp_obj_get_array(value, &value_len, &value_items); mp_bound_slice_t slice_out; if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice_out)) { mp_raise_NotImplementedError(NULL); } mp_int_t len_adj = value_len - (slice_out.stop - slice_out.start); - //printf("Len adj: %d\n", len_adj); + // printf("Len adj: %d\n", len_adj); if (len_adj > 0) { if (self->len + len_adj > self->alloc) { // TODO: Might optimize memory copies here by checking if block can @@ -227,7 +231,7 @@ STATIC mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { self->len += len_adj; return mp_const_none; } -#endif + #endif mp_obj_list_store(self, index, value); return mp_const_none; } @@ -280,7 +284,7 @@ inline mp_obj_t mp_obj_list_pop(mp_obj_list_t *self, size_t index) { // Clear stale pointer from slot which just got freed to prevent GC issues self->items[self->len] = MP_OBJ_NULL; if (self->alloc > LIST_MIN_ALLOC && self->alloc > 2 * self->len) { - self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc/2); + self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc / 2); self->alloc /= 2; } return ret; @@ -300,9 +304,13 @@ STATIC void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn, mp_obj mp_obj_t *t = tail; mp_obj_t v = key_fn == MP_OBJ_NULL ? tail[0] : mp_call_function_1(key_fn, tail[0]); // get pivot using key_fn for (;;) { - do ++h; while (h < t && mp_binary_op(MP_BINARY_OP_LESS, key_fn == MP_OBJ_NULL ? h[0] : mp_call_function_1(key_fn, h[0]), v) == binop_less_result); - do --t; while (h < t && mp_binary_op(MP_BINARY_OP_LESS, v, key_fn == MP_OBJ_NULL ? t[0] : mp_call_function_1(key_fn, t[0])) == binop_less_result); - if (h >= t) break; + do {++h; + } while (h < t && mp_binary_op(MP_BINARY_OP_LESS, key_fn == MP_OBJ_NULL ? h[0] : mp_call_function_1(key_fn, h[0]), v) == binop_less_result); + do {--t; + } while (h < t && mp_binary_op(MP_BINARY_OP_LESS, v, key_fn == MP_OBJ_NULL ? t[0] : mp_call_function_1(key_fn, t[0])) == binop_less_result); + if (h >= t) { + break; + } mp_obj_t x = h[0]; h[0] = t[0]; t[0] = x; @@ -333,15 +341,15 @@ mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_ mp_arg_val_t key, reverse; } args; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, - MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t*)&args); + MP_ARRAY_SIZE(allowed_args), allowed_args, (mp_arg_val_t *)&args); mp_check_self(MP_OBJ_IS_TYPE(pos_args[0], &mp_type_list)); mp_obj_list_t *self = mp_instance_cast_to_native_base(pos_args[0], &mp_type_list); if (self->len > 1) { mp_quicksort(self->items, self->items + self->len - 1, - args.key.u_obj == mp_const_none ? MP_OBJ_NULL : args.key.u_obj, - args.reverse.u_bool ? mp_const_false : mp_const_true); + args.key.u_obj == mp_const_none ? MP_OBJ_NULL : args.key.u_obj, + args.reverse.u_bool ? mp_const_false : mp_const_true); } return mp_const_none; @@ -379,7 +387,7 @@ inline void mp_obj_list_insert(mp_obj_list_t *self, size_t index, mp_obj_t obj) mp_obj_list_append(MP_OBJ_FROM_PTR(self), mp_const_none); for (size_t i = self->len - 1; i > index; --i) { - self->items[i] = self->items[i - 1]; + self->items[i] = self->items[i - 1]; } self->items[index] = obj; } @@ -390,13 +398,13 @@ STATIC mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) { // insert has its own strange index logic mp_int_t index = MP_OBJ_SMALL_INT_VALUE(idx); if (index < 0) { - index += self->len; + index += self->len; } if (index < 0) { - index = 0; + index = 0; } if ((size_t)index > self->len) { - index = self->len; + index = self->len; } mp_obj_list_insert(self, index, obj); return mp_const_none; @@ -416,10 +424,10 @@ STATIC mp_obj_t list_reverse(mp_obj_t self_in) { mp_obj_list_t *self = mp_instance_cast_to_native_base(self_in, &mp_type_list); mp_int_t len = self->len; - for (mp_int_t i = 0; i < len/2; i++) { - mp_obj_t a = self->items[i]; - self->items[i] = self->items[len-i-1]; - self->items[len-i-1] = a; + for (mp_int_t i = 0; i < len / 2; i++) { + mp_obj_t a = self->items[i]; + self->items[i] = self->items[len - i - 1]; + self->items[len - i - 1] = a; } return mp_const_none; @@ -462,7 +470,7 @@ const mp_obj_type_t mp_type_list = { .binary_op = list_binary_op, .subscr = list_subscr, .getiter = list_getiter, - .locals_dict = (mp_obj_dict_t*)&list_locals_dict, + .locals_dict = (mp_obj_dict_t *)&list_locals_dict, }; void mp_obj_list_init(mp_obj_list_t *o, size_t n) { @@ -532,7 +540,7 @@ STATIC mp_obj_t list_it_iternext(mp_obj_t self_in) { mp_obj_t mp_obj_new_list_iterator(mp_obj_t list, size_t cur, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_list_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_list_it_t *o = (mp_obj_list_it_t*)iter_buf; + mp_obj_list_it_t *o = (mp_obj_list_it_t *)iter_buf; o->base.type = &mp_type_polymorph_iter; o->iternext = list_it_iternext; o->list = list; diff --git a/py/objmodule.c b/py/objmodule.c index 90796c5357..0ac40229d4 100644 --- a/py/objmodule.c +++ b/py/objmodule.c @@ -44,7 +44,7 @@ STATIC void module_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin module_name = mp_obj_str_get_str(elem->value); } -#if MICROPY_PY___FILE__ + #if MICROPY_PY___FILE__ // If we store __file__ to imported modules then try to lookup this // symbol to give more information about the module. elem = mp_map_lookup(&self->globals->map, MP_OBJ_NEW_QSTR(MP_QSTR___file__), MP_MAP_LOOKUP); @@ -52,7 +52,7 @@ STATIC void module_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kin mp_printf(print, "", module_name, mp_obj_str_get_str(elem->value)); return; } -#endif + #endif mp_printf(print, "", module_name); } @@ -153,123 +153,123 @@ STATIC const mp_rom_map_elem_t mp_builtin_module_table[] = { { MP_ROM_QSTR(MP_QSTR_builtins), MP_ROM_PTR(&mp_module_builtins) }, { MP_ROM_QSTR(MP_QSTR_micropython), MP_ROM_PTR(&mp_module_micropython) }, -#if MICROPY_PY_ARRAY + #if MICROPY_PY_ARRAY { MP_ROM_QSTR(MP_QSTR_array), MP_ROM_PTR(&mp_module_array) }, -#endif -#if MICROPY_PY_IO -#if CIRCUITPY + #endif + #if MICROPY_PY_IO + #if CIRCUITPY { MP_ROM_QSTR(MP_QSTR_io), MP_ROM_PTR(&mp_module_io) }, -#else + #else { MP_ROM_QSTR(MP_QSTR_uio), MP_ROM_PTR(&mp_module_io) }, -#endif -#endif -#if MICROPY_PY_COLLECTIONS + #endif + #endif + #if MICROPY_PY_COLLECTIONS { MP_ROM_QSTR(MP_QSTR_collections), MP_ROM_PTR(&mp_module_collections) }, -#endif + #endif // CircuitPython: Now in shared-bindings/, so not defined here. -#if MICROPY_PY_STRUCT + #if MICROPY_PY_STRUCT { MP_ROM_QSTR(MP_QSTR_ustruct), MP_ROM_PTR(&mp_module_ustruct) }, -#endif + #endif -#if MICROPY_PY_BUILTINS_FLOAT -#if MICROPY_PY_MATH + #if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_MATH { MP_ROM_QSTR(MP_QSTR_math), MP_ROM_PTR(&mp_module_math) }, -#endif -#if MICROPY_PY_BUILTINS_COMPLEX && MICROPY_PY_CMATH + #endif + #if MICROPY_PY_BUILTINS_COMPLEX && MICROPY_PY_CMATH { MP_ROM_QSTR(MP_QSTR_cmath), MP_ROM_PTR(&mp_module_cmath) }, -#endif -#endif -#if MICROPY_PY_SYS + #endif + #endif + #if MICROPY_PY_SYS { MP_ROM_QSTR(MP_QSTR_sys), MP_ROM_PTR(&mp_module_sys) }, -#endif -#if MICROPY_PY_GC && MICROPY_ENABLE_GC + #endif + #if MICROPY_PY_GC && MICROPY_ENABLE_GC { MP_ROM_QSTR(MP_QSTR_gc), MP_ROM_PTR(&mp_module_gc) }, -#endif -#if MICROPY_PY_THREAD + #endif + #if MICROPY_PY_THREAD { MP_ROM_QSTR(MP_QSTR__thread), MP_ROM_PTR(&mp_module_thread) }, -#endif + #endif // extmod modules -#if MICROPY_PY_UERRNO -#if CIRCUITPY + #if MICROPY_PY_UERRNO + #if CIRCUITPY // CircuitPython: Defined in MICROPY_PORT_BUILTIN_MODULES, so not defined here. // TODO: move to shared-bindings/ -#else + #else { MP_ROM_QSTR(MP_QSTR_uerrno), MP_ROM_PTR(&mp_module_uerrno) }, -#endif -#endif -#if MICROPY_PY_UCTYPES + #endif + #endif + #if MICROPY_PY_UCTYPES { MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) }, -#endif -#if MICROPY_PY_UZLIB + #endif + #if MICROPY_PY_UZLIB { MP_ROM_QSTR(MP_QSTR_uzlib), MP_ROM_PTR(&mp_module_uzlib) }, -#endif -#if MICROPY_PY_UJSON -#if CIRCUITPY + #endif + #if MICROPY_PY_UJSON + #if CIRCUITPY // CircuitPython: Defined in MICROPY_PORT_BUILTIN_MODULES, so not defined here. // TODO: move to shared-bindings/ -#else + #else { MP_ROM_QSTR(MP_QSTR_ujson), MP_ROM_PTR(&mp_module_ujson) }, -#endif -#endif -#if CIRCUITPY_ULAB -#if CIRCUITPY + #endif + #endif + #if CIRCUITPY_ULAB + #if CIRCUITPY // CircuitPython: Defined in MICROPY_PORT_BUILTIN_MODULES, so not defined here. // TODO: move to shared-bindings/ -#else + #else { MP_ROM_QSTR(MP_QSTR_ulab), MP_ROM_PTR(&ulab_user_cmodule) }, -#endif -#endif -#if MICROPY_PY_URE -#if CIRCUITPY + #endif + #endif + #if MICROPY_PY_URE + #if CIRCUITPY // CircuitPython: Defined in MICROPY_PORT_BUILTIN_MODULES, so not defined here. // TODO: move to shared-bindings/ -#else + #else { MP_ROM_QSTR(MP_QSTR_ure), MP_ROM_PTR(&mp_module_ure) }, -#endif -#endif -#if MICROPY_PY_UHEAPQ + #endif + #endif + #if MICROPY_PY_UHEAPQ { MP_ROM_QSTR(MP_QSTR_uheapq), MP_ROM_PTR(&mp_module_uheapq) }, -#endif -#if MICROPY_PY_UTIMEQ + #endif + #if MICROPY_PY_UTIMEQ { MP_ROM_QSTR(MP_QSTR_utimeq), MP_ROM_PTR(&mp_module_utimeq) }, -#endif -#if MICROPY_PY_UHASHLIB + #endif + #if MICROPY_PY_UHASHLIB { MP_ROM_QSTR(MP_QSTR_hashlib), MP_ROM_PTR(&mp_module_uhashlib) }, -#endif -#if MICROPY_PY_UBINASCII -#if CIRCUITPY + #endif + #if MICROPY_PY_UBINASCII + #if CIRCUITPY // CircuitPython: Defined in MICROPY_PORT_BUILTIN_MODULES, so not defined here. // TODO: move to shared-bindings/ -#else + #else { MP_ROM_QSTR(MP_QSTR_ubinascii), MP_ROM_PTR(&mp_module_ubinascii) }, -#endif -#endif -#if MICROPY_PY_URANDOM + #endif + #endif + #if MICROPY_PY_URANDOM { MP_ROM_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&mp_module_urandom) }, -#endif -#if MICROPY_PY_USELECT + #endif + #if MICROPY_PY_USELECT { MP_ROM_QSTR(MP_QSTR_uselect), MP_ROM_PTR(&mp_module_uselect) }, -#endif -#if MICROPY_PY_USSL + #endif + #if MICROPY_PY_USSL { MP_ROM_QSTR(MP_QSTR_ussl), MP_ROM_PTR(&mp_module_ussl) }, -#endif -#if MICROPY_PY_LWIP + #endif + #if MICROPY_PY_LWIP { MP_ROM_QSTR(MP_QSTR_lwip), MP_ROM_PTR(&mp_module_lwip) }, -#endif -#if MICROPY_PY_WEBSOCKET + #endif + #if MICROPY_PY_WEBSOCKET { MP_ROM_QSTR(MP_QSTR_websocket), MP_ROM_PTR(&mp_module_websocket) }, -#endif -#if MICROPY_PY_WEBREPL + #endif + #if MICROPY_PY_WEBREPL { MP_ROM_QSTR(MP_QSTR__webrepl), MP_ROM_PTR(&mp_module_webrepl) }, -#endif -#if MICROPY_PY_FRAMEBUF + #endif + #if MICROPY_PY_FRAMEBUF { MP_ROM_QSTR(MP_QSTR_framebuf), MP_ROM_PTR(&mp_module_framebuf) }, -#endif -#if MICROPY_PY_BTREE + #endif + #if MICROPY_PY_BTREE { MP_ROM_QSTR(MP_QSTR_btree), MP_ROM_PTR(&mp_module_btree) }, -#endif + #endif // extra builtin modules as defined by a port MICROPY_PORT_BUILTIN_MODULES @@ -279,9 +279,9 @@ STATIC const mp_rom_map_elem_t mp_builtin_module_table[] = { MICROPY_REGISTERED_MODULES #endif -#if defined(MICROPY_DEBUG_MODULES) && defined(MICROPY_PORT_BUILTIN_DEBUG_MODULES) + #if defined(MICROPY_DEBUG_MODULES) && defined(MICROPY_PORT_BUILTIN_DEBUG_MODULES) , MICROPY_PORT_BUILTIN_DEBUG_MODULES -#endif + #endif }; MP_DEFINE_CONST_MAP(mp_builtin_module_map, mp_builtin_module_table); @@ -302,7 +302,7 @@ mp_obj_t mp_module_get(qstr module_name) { if (el == NULL) { // module not found, look for builtin module names - el = mp_map_lookup((mp_map_t*)&mp_builtin_module_map, MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP); + el = mp_map_lookup((mp_map_t *)&mp_builtin_module_map, MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP); if (el == NULL) { return MP_OBJ_NULL; } diff --git a/py/objnamedtuple.c b/py/objnamedtuple.c index 8b595da571..15b50c2d19 100644 --- a/py/objnamedtuple.c +++ b/py/objnamedtuple.c @@ -49,9 +49,9 @@ size_t mp_obj_namedtuple_find_field(const mp_obj_namedtuple_type_t *type, qstr n #if MICROPY_PY_COLLECTIONS_ORDEREDDICT STATIC mp_obj_t namedtuple_asdict(mp_obj_t self_in) { mp_obj_namedtuple_t *self = MP_OBJ_TO_PTR(self_in); - const qstr *fields = ((mp_obj_namedtuple_type_t*)self->tuple.base.type)->fields; + const qstr *fields = ((mp_obj_namedtuple_type_t *)self->tuple.base.type)->fields; mp_obj_t dict = mp_obj_new_dict(self->tuple.len); - //make it an OrderedDict + // make it an OrderedDict mp_obj_dict_t *dictObj = MP_OBJ_TO_PTR(dict); dictObj->base.type = &mp_type_ordereddict; dictObj->map.is_ordered = 1; @@ -67,7 +67,7 @@ void namedtuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t ki (void)kind; mp_obj_namedtuple_t *o = MP_OBJ_TO_PTR(o_in); mp_printf(print, "%q", o->tuple.base.type->name); - const qstr *fields = ((mp_obj_namedtuple_type_t*)o->tuple.base.type)->fields; + const qstr *fields = ((mp_obj_namedtuple_type_t *)o->tuple.base.type)->fields; mp_obj_attrtuple_print_helper(print, fields, &o->tuple); } @@ -82,7 +82,7 @@ void namedtuple_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { return; } #endif - size_t id = mp_obj_namedtuple_find_field((mp_obj_namedtuple_type_t*)self->tuple.base.type, attr); + size_t id = mp_obj_namedtuple_find_field((mp_obj_namedtuple_type_t *)self->tuple.base.type, attr); if (id == (size_t)-1) { return; } @@ -95,7 +95,7 @@ void namedtuple_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } mp_obj_t namedtuple_make_new(const mp_obj_type_t *type_in, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { - const mp_obj_namedtuple_type_t *type = (const mp_obj_namedtuple_type_t*)type_in; + const mp_obj_namedtuple_type_t *type = (const mp_obj_namedtuple_type_t *)type_in; size_t num_fields = type->n_fields; size_t n_kw = 0; if (kw_args != NULL) { @@ -103,15 +103,15 @@ mp_obj_t namedtuple_make_new(const mp_obj_type_t *type_in, size_t n_args, const } if (n_args + n_kw != num_fields) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL - mp_raise_TypeError_varg( - translate("function takes %d positional arguments but %d were given"), - num_fields, n_args + n_kw); + mp_raise_TypeError_varg( + translate("function takes %d positional arguments but %d were given"), + num_fields, n_args + n_kw); #else - mp_raise_TypeError_varg( - translate("%q() takes %d positional arguments but %d were given"), - type->base.name, num_fields, n_args + n_kw); + mp_raise_TypeError_varg( + translate("%q() takes %d positional arguments but %d were given"), + type->base.name, num_fields, n_args + n_kw); #endif } @@ -129,18 +129,18 @@ mp_obj_t namedtuple_make_new(const mp_obj_type_t *type_in, size_t n_args, const size_t id = mp_obj_namedtuple_find_field(type, kw); if (id == (size_t)-1) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #else - mp_raise_TypeError_varg( - translate("unexpected keyword argument '%q'"), kw); + mp_raise_TypeError_varg( + translate("unexpected keyword argument '%q'"), kw); #endif } if (tuple->items[id] != MP_OBJ_NULL) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_arg_error_terse_mismatch(); + mp_arg_error_terse_mismatch(); #else - mp_raise_TypeError_varg( - translate("function got multiple values for argument '%q'"), kw); + mp_raise_TypeError_varg( + translate("function got multiple values for argument '%q'"), kw); #endif } tuple->items[id] = kw_args->table[i].value; diff --git a/py/objobject.c b/py/objobject.c index 8983cd9ad3..b3a6a171a0 100644 --- a/py/objobject.c +++ b/py/objobject.c @@ -51,7 +51,7 @@ STATIC mp_obj_t object___init__(mp_obj_t self) { STATIC MP_DEFINE_CONST_FUN_OBJ_1(object___init___obj, object___init__); STATIC mp_obj_t object___new__(mp_obj_t cls) { - if (!MP_OBJ_IS_TYPE(cls, &mp_type_type) || !mp_obj_is_instance_type((mp_obj_type_t*)MP_OBJ_TO_PTR(cls))) { + if (!MP_OBJ_IS_TYPE(cls, &mp_type_type) || !mp_obj_is_instance_type((mp_obj_type_t *)MP_OBJ_TO_PTR(cls))) { mp_raise_TypeError(translate("__new__ arg must be a user-type")); } // This executes only "__new__" part of instance creation. @@ -81,6 +81,6 @@ const mp_obj_type_t mp_type_object = { .name = MP_QSTR_object, .make_new = object_make_new, #if MICROPY_CPYTHON_COMPAT - .locals_dict = (mp_obj_dict_t*)&object_locals_dict, + .locals_dict = (mp_obj_dict_t *)&object_locals_dict, #endif }; diff --git a/py/objproperty.c b/py/objproperty.c index e909533c45..f249d79a1d 100644 --- a/py/objproperty.c +++ b/py/objproperty.c @@ -55,7 +55,7 @@ STATIC mp_obj_t property_make_new(const mp_obj_type_t *type, size_t n_args, cons STATIC mp_obj_t property_getter(mp_obj_t self_in, mp_obj_t getter) { mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t); - *p2 = *(mp_obj_property_t*)MP_OBJ_TO_PTR(self_in); + *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[0] = getter; return MP_OBJ_FROM_PTR(p2); } @@ -64,7 +64,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(property_getter_obj, property_getter); STATIC mp_obj_t property_setter(mp_obj_t self_in, mp_obj_t setter) { mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t); - *p2 = *(mp_obj_property_t*)MP_OBJ_TO_PTR(self_in); + *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[1] = setter; return MP_OBJ_FROM_PTR(p2); } @@ -73,7 +73,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(property_setter_obj, property_setter); STATIC mp_obj_t property_deleter(mp_obj_t self_in, mp_obj_t deleter) { mp_obj_property_t *p2 = m_new_obj(mp_obj_property_t); - *p2 = *(mp_obj_property_t*)MP_OBJ_TO_PTR(self_in); + *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[2] = deleter; return MP_OBJ_FROM_PTR(p2); } @@ -92,7 +92,7 @@ const mp_obj_type_t mp_type_property = { { &mp_type_type }, .name = MP_QSTR_property, .make_new = property_make_new, - .locals_dict = (mp_obj_dict_t*)&property_locals_dict, + .locals_dict = (mp_obj_dict_t *)&property_locals_dict, }; const mp_obj_t *mp_obj_property_get(mp_obj_t self_in) { diff --git a/py/objrange.c b/py/objrange.c index 7af9f37a11..fcc0ede98b 100644 --- a/py/objrange.c +++ b/py/objrange.c @@ -61,7 +61,7 @@ STATIC const mp_obj_type_t range_it_type = { STATIC mp_obj_t mp_obj_new_range_iterator(mp_int_t cur, mp_int_t stop, mp_int_t step, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_range_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_range_it_t *o = (mp_obj_range_it_t*)iter_buf; + mp_obj_range_it_t *o = (mp_obj_range_it_t *)iter_buf; o->base.type = &range_it_type; o->cur = cur; o->stop = stop; @@ -134,9 +134,12 @@ STATIC mp_obj_t range_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_range_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t len = range_len(self); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len > 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(len > 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -154,7 +157,7 @@ STATIC mp_obj_t range_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs && (lhs_len == 0 || (lhs->start == rhs->start && (lhs_len == 1 || lhs->step == rhs->step))) - ); + ); } #endif @@ -163,7 +166,7 @@ STATIC mp_obj_t range_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { // load mp_obj_range_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t len = range_len(self); -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { mp_bound_slice_t slice; mp_seq_get_fast_slice_indexes(len, index, &slice); @@ -178,7 +181,7 @@ STATIC mp_obj_t range_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } return MP_OBJ_FROM_PTR(o); } -#endif + #endif size_t index_val = mp_get_index(self->base.type, len, index, false); return MP_OBJ_NEW_SMALL_INT(self->start + index_val * self->step); } else { @@ -220,7 +223,7 @@ const mp_obj_type_t mp_type_range = { #endif .subscr = range_subscr, .getiter = range_getiter, -#if MICROPY_PY_BUILTINS_RANGE_ATTRS + #if MICROPY_PY_BUILTINS_RANGE_ATTRS .attr = range_attr, -#endif + #endif }; diff --git a/py/objset.c b/py/objset.c index c5d54aede5..6089f91814 100644 --- a/py/objset.c +++ b/py/objset.c @@ -51,9 +51,9 @@ STATIC mp_obj_t set_it_iternext(mp_obj_t self_in); STATIC bool is_set_or_frozenset(mp_obj_t o) { return MP_OBJ_IS_TYPE(o, &mp_type_set) -#if MICROPY_PY_BUILTINS_FROZENSET - || MP_OBJ_IS_TYPE(o, &mp_type_frozenset) -#endif + #if MICROPY_PY_BUILTINS_FROZENSET + || MP_OBJ_IS_TYPE(o, &mp_type_frozenset) + #endif ; } @@ -125,7 +125,7 @@ STATIC mp_obj_t set_make_new(const mp_obj_type_t *type, size_t n_args, const mp_ mp_obj_set_store(set, item); } // Set actual set/frozenset type - ((mp_obj_set_t*)MP_OBJ_TO_PTR(set))->base.type = type; + ((mp_obj_set_t *)MP_OBJ_TO_PTR(set))->base.type = type; return set; } } @@ -148,7 +148,7 @@ STATIC mp_obj_t set_it_iternext(mp_obj_t self_in) { STATIC mp_obj_t set_getiter(mp_obj_t set_in, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_set_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_set_it_t *o = (mp_obj_set_it_t*)iter_buf; + mp_obj_set_it_t *o = (mp_obj_set_it_t *)iter_buf; o->base.type = &mp_type_polymorph_iter; o->iternext = set_it_iternext; o->set = (mp_obj_set_t *)MP_OBJ_TO_PTR(set_in); @@ -212,7 +212,7 @@ STATIC mp_obj_t set_diff_int(size_t n_args, const mp_obj_t *args, bool update) { if (self == other) { set_clear(self); } else { - mp_set_t *self_set = &((mp_obj_set_t*)MP_OBJ_TO_PTR(self))->set; + mp_set_t *self_set = &((mp_obj_set_t *)MP_OBJ_TO_PTR(self))->set; mp_obj_t iter = mp_getiter(other, NULL); mp_obj_t next; while ((next = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) { @@ -432,9 +432,11 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(set_union_obj, set_union); STATIC mp_obj_t set_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_set_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->set.used != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->set.used); -#if MICROPY_PY_BUILTINS_FROZENSET + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(self->set.used != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(self->set.used); + #if MICROPY_PY_BUILTINS_FROZENSET case MP_UNARY_OP_HASH: if (MP_OBJ_IS_TYPE(self_in, &mp_type_frozenset)) { // start hash with unique value @@ -449,9 +451,10 @@ STATIC mp_obj_t set_unary_op(mp_unary_op_t op, mp_obj_t self_in) { } return MP_OBJ_NEW_SMALL_INT(hash); } -#endif - /* FALLTHROUGH */ - default: return MP_OBJ_NULL; // op not supported + #endif + /* FALLTHROUGH */ + default: + return MP_OBJ_NULL; // op not supported } } @@ -553,7 +556,7 @@ const mp_obj_type_t mp_type_set = { .unary_op = set_unary_op, .binary_op = set_binary_op, .getiter = set_getiter, - .locals_dict = (mp_obj_dict_t*)&set_locals_dict, + .locals_dict = (mp_obj_dict_t *)&set_locals_dict, }; #if MICROPY_PY_BUILTINS_FROZENSET @@ -578,7 +581,7 @@ const mp_obj_type_t mp_type_frozenset = { .unary_op = set_unary_op, .binary_op = set_binary_op, .getiter = set_getiter, - .locals_dict = (mp_obj_dict_t*)&frozenset_locals_dict, + .locals_dict = (mp_obj_dict_t *)&frozenset_locals_dict, }; #endif diff --git a/py/objslice.c b/py/objslice.c index 40d4d3c760..a2beb7dd21 100644 --- a/py/objslice.c +++ b/py/objslice.c @@ -125,22 +125,22 @@ STATIC void slice_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } else if (attr == MP_QSTR_step) { dest[0] = self->step; } else if (attr == MP_QSTR_indices) { - mp_convert_member_lookup(self_in, self->base.type, (mp_obj_t) &slice_indices_obj, dest); + mp_convert_member_lookup(self_in, self->base.type, (mp_obj_t)&slice_indices_obj, dest); } } STATIC mp_obj_t slice_make_new(const mp_obj_type_t *type, - size_t n_args, const mp_obj_t *args, mp_map_t *kw_args); + size_t n_args, const mp_obj_t *args, mp_map_t *kw_args); #endif const mp_obj_type_t mp_type_slice = { { &mp_type_type }, .name = MP_QSTR_slice, .print = slice_print, -#if MICROPY_PY_BUILTINS_SLICE_ATTRS + #if MICROPY_PY_BUILTINS_SLICE_ATTRS .make_new = slice_make_new, .attr = slice_attr, -#endif + #endif }; mp_obj_t mp_obj_new_slice(mp_obj_t ostart, mp_obj_t ostop, mp_obj_t ostep) { @@ -219,7 +219,7 @@ void mp_obj_slice_indices(mp_obj_t self_in, mp_int_t length, mp_bound_slice_t *r #if MICROPY_PY_BUILTINS_SLICE_ATTRS STATIC mp_obj_t slice_make_new(const mp_obj_type_t *type, - size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { + size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { if (type != &mp_type_slice) { mp_raise_NotImplementedError(translate("Cannot subclass slice")); } diff --git a/py/objstr.c b/py/objstr.c index 1a59aeaecd..e3c0e78e31 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -140,11 +140,11 @@ STATIC void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t } mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT if (kw_args != NULL && kw_args->used != 0) { mp_arg_error_unimpl_kw(); } -#endif + #endif mp_arg_check_num(n_args, kw_args, 0, 3, false); @@ -175,7 +175,7 @@ mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, const mp_ #endif // Check if a qstr with this data already exists - qstr q = qstr_find_strn((const char*)str_data, str_len); + qstr q = qstr_find_strn((const char *)str_data, str_len); if (q != MP_QSTR_NULL) { return MP_OBJ_NEW_QSTR(q); } @@ -298,11 +298,11 @@ const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, } for (;;) { if (memcmp(&haystack[str_index], needle, nlen) == 0) { - //found + // found return haystack + str_index; } if (str_index == str_index_end) { - //not found + // not found break; } str_index += direction; @@ -407,7 +407,7 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i case MP_BINARY_OP_CONTAINS: return mp_obj_new_bool(find_subbytes(lhs_data, lhs_len, rhs_data, rhs_len, 1) != NULL); - //case MP_BINARY_OP_NOT_EQUAL: // This is never passed here + // case MP_BINARY_OP_NOT_EQUAL: // This is never passed here case MP_BINARY_OP_EQUAL: // This will be passed only for bytes, str is dealt with in mp_obj_equal() case MP_BINARY_OP_LESS: case MP_BINARY_OP_LESS_EQUAL: @@ -423,7 +423,7 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i #if !MICROPY_PY_BUILTINS_STR_UNICODE // objstrunicode defines own version size_t str_offset_to_index(const mp_obj_type_t *type, const byte *self_data, size_t self_len, - size_t offset) { + size_t offset) { if (offset > self_len) { mp_raise_ValueError(translate("offset out of bounds")); } @@ -432,7 +432,7 @@ size_t str_offset_to_index(const mp_obj_type_t *type, const byte *self_data, siz } const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len, - mp_obj_t index, bool is_slice) { + mp_obj_t index, bool is_slice) { size_t index_val = mp_get_index(type, self_len, index, is_slice); return self_data + index_val; } @@ -444,7 +444,7 @@ STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { GET_STR_DATA_LEN(self_in, self_data, self_len); if (value == MP_OBJ_SENTINEL) { // load -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self_len, index, &slice)) { @@ -452,13 +452,13 @@ STATIC mp_obj_t bytes_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } return mp_obj_new_str_of_type(type, self_data + slice.start, slice.stop - slice.start); } -#endif + #endif size_t index_val = mp_get_index(type, self_len, index, false); // If we have unicode enabled the type will always be bytes, so take the short cut. if (MICROPY_PY_BUILTINS_STR_UNICODE || type == &mp_type_bytes) { return MP_OBJ_NEW_SMALL_INT(self_data[index_val]); } else { - return mp_obj_new_str_via_qstr((char*)&self_data[index_val], 1); + return mp_obj_new_str_via_qstr((char *)&self_data[index_val], 1); } } else { return MP_OBJ_NULL; // op not supported @@ -500,7 +500,7 @@ STATIC mp_obj_t str_join(mp_obj_t self_in, mp_obj_t arg) { // make joined string vstr_t vstr; vstr_init_len(&vstr, required_len); - byte *data = (byte*)vstr.buf; + byte *data = (byte *)vstr.buf; for (size_t i = 0; i < seq_len; i++) { if (i > 0) { memcpy(data, sep_str, sep_len); @@ -535,15 +535,21 @@ mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args) { // sep not given, so separate on whitespace // Initial whitespace is not counted as split, so we pre-do it - while (s < top && unichar_isspace(*s)) s++; + while (s < top && unichar_isspace(*s)) { + s++; + } while (s < top && splits != 0) { const byte *start = s; - while (s < top && !unichar_isspace(*s)) s++; + while (s < top && !unichar_isspace(*s)) { + s++; + } mp_obj_list_append(res, mp_obj_new_str_of_type(self_type, start, s - start)); if (s >= top) { break; } - while (s < top && unichar_isspace(*s)) s++; + while (s < top && unichar_isspace(*s)) { + s++; + } if (splits > 0) { splits--; } @@ -863,7 +869,7 @@ STATIC mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) { } assert(last_good_char_pos >= first_good_char_pos); - //+1 to accommodate the last character + // +1 to accommodate the last character size_t stripped_len = last_good_char_pos - first_good_char_pos + 1; if (stripped_len == orig_str_len) { // If nothing was stripped, don't bother to dup original string @@ -935,18 +941,18 @@ STATIC bool arg_looks_integer(mp_obj_t arg) { STATIC bool arg_looks_numeric(mp_obj_t arg) { return arg_looks_integer(arg) -#if MICROPY_PY_BUILTINS_FLOAT - || mp_obj_is_float(arg) -#endif + #if MICROPY_PY_BUILTINS_FLOAT + || mp_obj_is_float(arg) + #endif ; } STATIC mp_obj_t arg_as_int(mp_obj_t arg) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT if (mp_obj_is_float(arg)) { return mp_obj_new_int_from_float(mp_obj_float_get(arg)); } -#endif + #endif return arg; } @@ -972,9 +978,9 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar continue; } #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError(translate("single '}' encountered in format string")); + mp_raise_ValueError(translate("single '}' encountered in format string")); #endif } if (*str != '{') { @@ -1011,16 +1017,16 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar conversion = *str++; } else { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL - mp_raise_ValueError(translate("bad conversion specifier")); + mp_raise_ValueError(translate("bad conversion specifier")); #else - if (str >= top) { - mp_raise_ValueError( - translate("end of format while looking for conversion specifier")); - } else { - mp_raise_ValueError_varg(translate("unknown conversion specifier %c"), *str); - } + if (str >= top) { + mp_raise_ValueError( + translate("end of format while looking for conversion specifier")); + } else { + mp_raise_ValueError_varg(translate("unknown conversion specifier %c"), *str); + } #endif } } @@ -1048,16 +1054,16 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } if (str >= top) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError(translate("unmatched '{' in format")); + mp_raise_ValueError(translate("unmatched '{' in format")); #endif } if (*str != '}') { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE -:w + : w #else - mp_raise_ValueError(translate("expected ':' after format specifier")); + mp_raise_ValueError(translate("expected ':' after format specifier")); #endif } @@ -1068,10 +1074,10 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar if (MP_LIKELY(unichar_isdigit(*field_name))) { if (*arg_i > 0) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError( - translate("can't switch from automatic field numbering to manual field specification")); + mp_raise_ValueError( + translate("can't switch from automatic field numbering to manual field specification")); #endif } field_name = str_to_int(field_name, field_name_top, &index); @@ -1082,7 +1088,8 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar *arg_i = -1; } else { const char *lookup; - for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++); + for (lookup = field_name; lookup < field_name_top && *lookup != '.' && *lookup != '['; lookup++) {; + } mp_obj_t field_q = mp_obj_new_str_via_qstr(field_name, lookup - field_name); // should it be via qstr? field_name = lookup; mp_map_elem_t *key_elem = mp_map_lookup(kwargs, field_q, MP_MAP_LOOKUP); @@ -1097,10 +1104,10 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } else { if (*arg_i < 0) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError( - translate("can't switch from manual field specification to automatic field numbering")); + mp_raise_ValueError( + translate("can't switch from manual field specification to automatic field numbering")); #endif } if ((uint)*arg_i >= n_args - 1) { @@ -1190,9 +1197,9 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } if (*s) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError(translate("invalid format specifier")); + mp_raise_ValueError(translate("invalid format specifier")); #endif } vstr_clear(&format_spec_vstr); @@ -1211,25 +1218,31 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar if (flags & (PF_FLAG_SHOW_SIGN | PF_FLAG_SPACE_SIGN)) { if (type == 's') { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError(translate("sign not allowed in string format specifier")); + mp_raise_ValueError(translate("sign not allowed in string format specifier")); #endif } if (type == 'c') { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError( - translate("sign not allowed with integer format specifier 'c'")); + mp_raise_ValueError( + translate("sign not allowed with integer format specifier 'c'")); #endif } } switch (align) { - case '<': flags |= PF_FLAG_LEFT_ADJUST; break; - case '=': flags |= PF_FLAG_PAD_AFTER_SIGN; break; - case '^': flags |= PF_FLAG_CENTER_ADJUST; break; + case '<': + flags |= PF_FLAG_LEFT_ADJUST; + break; + case '=': + flags |= PF_FLAG_PAD_AFTER_SIGN; + break; + case '^': + flags |= PF_FLAG_CENTER_ADJUST; + break; } if (arg_looks_integer(arg)) { @@ -1238,8 +1251,7 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar mp_print_mp_int(&print, arg, 2, 'a', flags, fill, width, 0); continue; - case 'c': - { + case 'c': { char ch = mp_obj_get_int(arg); mp_print_strn(&print, &ch, 1, flags, fill, width); continue; @@ -1277,11 +1289,11 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar default: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError_varg( - translate("unknown format code '%c' for object of type '%q'"), - type, mp_obj_get_type_qstr(arg)); + mp_raise_ValueError_varg( + translate("unknown format code '%c' for object of type '%q'"), + type, mp_obj_get_type_qstr(arg)); #endif } } @@ -1325,7 +1337,7 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } switch (type) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'e': case 'E': case 'f': @@ -1343,17 +1355,17 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar #define F100 100.0 #endif mp_print_float(&print, mp_obj_get_float(arg) * F100, 'f', flags, fill, width, precision); - #undef F100 +#undef F100 break; -#endif + #endif default: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError_varg( - translate("unknown format code '%c' for object of type '%q'"), - type, mp_obj_get_type_qstr(arg)); + mp_raise_ValueError_varg( + translate("unknown format code '%c' for object of type '%q'"), + type, mp_obj_get_type_qstr(arg)); #endif } } else { @@ -1361,10 +1373,10 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar if (align == '=') { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError( - translate("'=' alignment not allowed in string format specifier")); + mp_raise_ValueError( + translate("'=' alignment not allowed in string format specifier")); #endif } @@ -1385,11 +1397,11 @@ STATIC vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar default: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError_varg( - translate("unknown format code '%c' for object of type '%q'"), - type, mp_obj_get_type_qstr(arg)); + mp_raise_ValueError_varg( + translate("unknown format code '%c' for object of type '%q'"), + type, mp_obj_get_type_qstr(arg)); #endif } } @@ -1403,7 +1415,7 @@ mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs GET_STR_DATA_LEN(args[0], str, len); int arg_i = 0; - vstr_t vstr = mp_obj_str_format_helper((const char*)str, (const char*)str + len, &arg_i, n_args, args, kwargs); + vstr_t vstr = mp_obj_str_format_helper((const char *)str, (const char *)str + len, &arg_i, n_args, args, kwargs); return mp_obj_new_str_from_vstr(&mp_type_str, &vstr); } MP_DEFINE_CONST_FUN_OBJ_KW(str_format_obj, 1, mp_obj_str_format); @@ -1443,14 +1455,14 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ while (*str != ')') { if (str >= top) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError(translate("incomplete format key")); + mp_raise_ValueError(translate("incomplete format key")); #endif } ++str; } - mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char*)key, str - key); + mp_obj_t k_obj = mp_obj_new_str_via_qstr((const char *)key, str - key); arg = mp_obj_dict_get(dict, k_obj); str++; } @@ -1459,14 +1471,20 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ char fill = ' '; int alt = 0; while (str < top) { - if (*str == '-') flags |= PF_FLAG_LEFT_ADJUST; - else if (*str == '+') flags |= PF_FLAG_SHOW_SIGN; - else if (*str == ' ') flags |= PF_FLAG_SPACE_SIGN; - else if (*str == '#') alt = PF_FLAG_SHOW_PREFIX; - else if (*str == '0') { + if (*str == '-') { + flags |= PF_FLAG_LEFT_ADJUST; + } else if (*str == '+') { + flags |= PF_FLAG_SHOW_SIGN; + } else if (*str == ' ') { + flags |= PF_FLAG_SPACE_SIGN; + } else if (*str == '#') { + alt = PF_FLAG_SHOW_PREFIX; + } else if (*str == '0') { flags |= PF_FLAG_PAD_AFTER_SIGN; fill = '0'; - } else break; + } else { + break; + } str++; } // parse width, if it exists @@ -1479,7 +1497,7 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ width = mp_obj_get_int(args[arg_i++]); str++; } else { - str = (const byte*)str_to_int((const char*)str, (const char*)top, &width); + str = (const byte *)str_to_int((const char *)str, (const char *)top, &width); } } int prec = -1; @@ -1493,24 +1511,24 @@ STATIC mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ str++; } else { prec = 0; - str = (const byte*)str_to_int((const char*)str, (const char*)top, &prec); + str = (const byte *)str_to_int((const char *)str, (const char *)top, &prec); } } } if (str >= top) { -incomplete_format: + incomplete_format: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError(translate("incomplete format")); + mp_raise_ValueError(translate("incomplete format")); #endif } // Tuple value lookup if (arg == MP_OBJ_NULL) { if (arg_i >= n_args) { -not_enough_args: + not_enough_args: mp_raise_TypeError(translate("not enough arguments for format string")); } arg = args[arg_i++]; @@ -1538,7 +1556,7 @@ not_enough_args: mp_print_mp_int(&print, arg_as_int(arg), 10, 'a', flags, fill, width, prec); break; -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT case 'e': case 'E': case 'f': @@ -1547,7 +1565,7 @@ not_enough_args: case 'G': mp_print_float(&print, mp_obj_get_float(arg), *str, flags, fill, width, prec); break; -#endif + #endif case 'o': if (alt) { @@ -1557,8 +1575,7 @@ not_enough_args: break; case 'r': - case 's': - { + case 's': { vstr_t arg_vstr; mp_print_t arg_print; vstr_init_print(&arg_vstr, 16, &arg_print); @@ -1588,11 +1605,11 @@ not_enough_args: default: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - terse_str_format_value_error(); + terse_str_format_value_error(); #else - mp_raise_ValueError_varg( - translate("unsupported format character '%c' (0x%x) at index %d"), - *str, *str, str - start_str); + mp_raise_ValueError_varg( + translate("unsupported format character '%c' (0x%x) at index %d"), + *str, *str, str - start_str); #endif } } @@ -1699,7 +1716,7 @@ STATIC mp_obj_t str_replace(size_t n_args, const mp_obj_t *args) { } else { // substr found, allocate new string vstr_init_len(&vstr, replaced_str_index); - data = (byte*)vstr.buf; + data = (byte *)vstr.buf; assert(data != NULL); } } else { @@ -1812,7 +1829,7 @@ STATIC mp_obj_t str_caseconv(unichar (*op)(unichar), mp_obj_t self_in) { GET_STR_DATA_LEN(self_in, self_data, self_len); vstr_t vstr; vstr_init_len(&vstr, self_len); - byte *data = (byte*)vstr.buf; + byte *data = (byte *)vstr.buf; for (size_t i = 0; i < self_len; i++) { *data++ = op(*self_data++); } @@ -1920,7 +1937,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_encode_obj, 1, 3, str_encode); mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { if (flags == MP_BUFFER_READ) { GET_STR_DATA_LEN(self_in, str_data, str_len); - bufinfo->buf = (void*)str_data; + bufinfo->buf = (void *)str_data; bufinfo->len = str_len; bufinfo->typecode = 'B'; // bytes should be unsigned, so should unicode byte-access return 0; @@ -1934,7 +1951,7 @@ mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_u } STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&bytes_decode_obj) }, #if !MICROPY_PY_BUILTINS_STR_UNICODE // If we have separate unicode type, then here we have methods only @@ -1944,7 +1961,7 @@ STATIC const mp_rom_map_elem_t str8_locals_dict_table[] = { // methods (which should do type checking at runtime). { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) }, #endif -#endif + #endif { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) }, { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) }, { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) }, @@ -1993,7 +2010,7 @@ const mp_obj_type_t mp_type_str = { .subscr = bytes_subscr, .getiter = mp_obj_new_str_iterator, .buffer_p = { .get_buffer = mp_obj_str_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&str8_locals_dict, + .locals_dict = (mp_obj_dict_t *)&str8_locals_dict, }; #endif @@ -2007,16 +2024,16 @@ const mp_obj_type_t mp_type_bytes = { .subscr = bytes_subscr, .getiter = mp_obj_new_bytes_iterator, .buffer_p = { .get_buffer = mp_obj_str_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&str8_locals_dict, + .locals_dict = (mp_obj_dict_t *)&str8_locals_dict, }; // The zero-length bytes object, with data that includes a null-terminating byte -const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte*)""}; +const mp_obj_str_t mp_const_empty_bytes_obj = {{&mp_type_bytes}, 0, 0, (const byte *)""}; // Create a str/bytes object using the given data. New memory is allocated and // the data is copied across. This function should only be used if the type is bytes, // or if the type is str and the string data is known to be not interned. -mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t len) { +mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte *data, size_t len) { mp_obj_str_t *o = m_new_obj(mp_obj_str_t); o->base.type = type; o->len = len; @@ -2033,16 +2050,16 @@ mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t // Create a str/bytes object using the given data. If the type is str and the string // data is already interned, then a qstr object is returned. Otherwise new memory is // allocated for the object and the data is copied across. -mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len) { +mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte *data, size_t len) { if (type == &mp_type_str) { - return mp_obj_new_str((const char*)data, len); + return mp_obj_new_str((const char *)data, len); } else { return mp_obj_new_bytes(data, len); } } // Create a str using a qstr to store the data; may use existing or new qstr. -mp_obj_t mp_obj_new_str_via_qstr(const char* data, size_t len) { +mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len) { return MP_OBJ_NEW_QSTR(qstr_from_strn(data, len)); } @@ -2064,41 +2081,41 @@ mp_obj_t mp_obj_new_str_from_vstr(const mp_obj_type_t *type, vstr_t *vstr) { mp_obj_str_t *o = m_new_obj(mp_obj_str_t); o->base.type = type; o->len = vstr->len; - o->hash = qstr_compute_hash((byte*)vstr->buf, vstr->len); + o->hash = qstr_compute_hash((byte *)vstr->buf, vstr->len); if (vstr->len + 1 == vstr->alloc) { - o->data = (byte*)vstr->buf; + o->data = (byte *)vstr->buf; } else { - o->data = (byte*)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1); + o->data = (byte *)m_renew(char, vstr->buf, vstr->alloc, vstr->len + 1); } - ((byte*)o->data)[o->len] = '\0'; // add null byte + ((byte *)o->data)[o->len] = '\0'; // add null byte vstr->buf = NULL; vstr->alloc = 0; return MP_OBJ_FROM_PTR(o); } -mp_obj_t mp_obj_new_str(const char* data, size_t len) { +mp_obj_t mp_obj_new_str(const char *data, size_t len) { qstr q = qstr_find_strn(data, len); if (q != MP_QSTR_NULL) { // qstr with this data already exists return MP_OBJ_NEW_QSTR(q); } else { // no existing qstr, don't make one - return mp_obj_new_str_copy(&mp_type_str, (const byte*)data, len); + return mp_obj_new_str_copy(&mp_type_str, (const byte *)data, len); } } mp_obj_t mp_obj_str_intern(mp_obj_t str) { GET_STR_DATA_LEN(str, data, len); - return mp_obj_new_str_via_qstr((const char*)data, len); + return mp_obj_new_str_via_qstr((const char *)data, len); } mp_obj_t mp_obj_str_intern_checked(mp_obj_t obj) { size_t len; const char *data = mp_obj_str_get_data(obj, &len); - return mp_obj_new_str_via_qstr((const char*)data, len); + return mp_obj_new_str_via_qstr((const char *)data, len); } -mp_obj_t mp_obj_new_bytes(const byte* data, size_t len) { +mp_obj_t mp_obj_new_bytes(const byte *data, size_t len) { return mp_obj_new_str_copy(&mp_type_bytes, data, len); } @@ -2131,11 +2148,11 @@ bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) { STATIC NORETURN void bad_implicit_conversion(mp_obj_t self_in) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("can't convert to str implicitly")); + mp_raise_TypeError(translate("can't convert to str implicitly")); #else - const qstr src_name = mp_obj_get_type_qstr(self_in); - mp_raise_TypeError_varg(translate("can't convert '%q' object to %q implicitly"), - src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str); + const qstr src_name = mp_obj_get_type_qstr(self_in); + mp_raise_TypeError_varg(translate("can't convert '%q' object to %q implicitly"), + src_name, src_name == MP_QSTR_str ? MP_QSTR_bytes : MP_QSTR_str); #endif } @@ -2146,7 +2163,7 @@ qstr mp_obj_str_get_qstr(mp_obj_t self_in) { return MP_OBJ_QSTR_VALUE(self_in); } else if (MP_OBJ_IS_TYPE(self_in, &mp_type_str)) { mp_obj_str_t *self = MP_OBJ_TO_PTR(self_in); - return qstr_from_strn((char*)self->data, self->len); + return qstr_from_strn((char *)self->data, self->len); } else { bad_implicit_conversion(self_in); } @@ -2158,7 +2175,7 @@ const char *mp_obj_str_get_str(mp_obj_t self_in) { if (MP_OBJ_IS_STR_OR_BYTES(self_in)) { GET_STR_DATA_LEN(self_in, s, l); (void)l; // len unused - return (const char*)s; + return (const char *)s; } else { bad_implicit_conversion(self_in); } @@ -2168,7 +2185,7 @@ const char *mp_obj_str_get_data(mp_obj_t self_in, size_t *len) { if (MP_OBJ_IS_STR_OR_BYTES(self_in)) { GET_STR_DATA_LEN(self_in, s, l); *len = l; - return (const char*)s; + return (const char *)s; } else { bad_implicit_conversion(self_in); } @@ -2179,8 +2196,8 @@ const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len) { if (MP_OBJ_IS_QSTR(self_in)) { return qstr_data(MP_OBJ_QSTR_VALUE(self_in), len); } else { - *len = ((mp_obj_str_t*)self_in)->len; - return ((mp_obj_str_t*)self_in)->data; + *len = ((mp_obj_str_t *)self_in)->len; + return ((mp_obj_str_t *)self_in)->data; } } #endif @@ -2200,7 +2217,7 @@ STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) { mp_obj_str8_it_t *self = MP_OBJ_TO_PTR(self_in); GET_STR_DATA_LEN(self->str, str, len); if (self->cur < len) { - mp_obj_t o_out = mp_obj_new_str_via_qstr((const char*)str + self->cur, 1); + mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)str + self->cur, 1); self->cur += 1; return o_out; } else { @@ -2210,7 +2227,7 @@ STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) { STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf; + mp_obj_str8_it_t *o = (mp_obj_str8_it_t *)iter_buf; o->base.type = &mp_type_polymorph_iter; o->iternext = str_it_iternext; o->str = str; @@ -2233,7 +2250,7 @@ STATIC mp_obj_t bytes_it_iternext(mp_obj_t self_in) { mp_obj_t mp_obj_new_bytes_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_str8_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_str8_it_t *o = (mp_obj_str8_it_t*)iter_buf; + mp_obj_str8_it_t *o = (mp_obj_str8_it_t *)iter_buf; o->base.type = &mp_type_polymorph_iter; o->iternext = bytes_it_iternext; o->str = str; diff --git a/py/objstr.h b/py/objstr.h index cddc6a83a1..e1698ca592 100644 --- a/py/objstr.h +++ b/py/objstr.h @@ -36,18 +36,18 @@ typedef struct _mp_obj_str_t { const byte *data; } mp_obj_str_t; -#define MP_DEFINE_STR_OBJ(obj_name, str) mp_obj_str_t obj_name = {{&mp_type_str}, 0, sizeof(str) - 1, (const byte*)str} +#define MP_DEFINE_STR_OBJ(obj_name, str) mp_obj_str_t obj_name = {{&mp_type_str}, 0, sizeof(str) - 1, (const byte *)str} // use this macro to extract the string hash // warning: the hash can be 0, meaning invalid, and must then be explicitly computed from the data #define GET_STR_HASH(str_obj_in, str_hash) \ mp_uint_t str_hash; if (MP_OBJ_IS_QSTR(str_obj_in)) \ - { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->hash; } + { str_hash = qstr_hash(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_hash = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->hash; } // use this macro to extract the string length #define GET_STR_LEN(str_obj_in, str_len) \ size_t str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) \ - { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->len; } + { str_len = qstr_len(MP_OBJ_QSTR_VALUE(str_obj_in)); } else { str_len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->len; } // use this macro to extract the string data and length #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C @@ -58,23 +58,23 @@ const byte *mp_obj_str_get_data_no_check(mp_obj_t self_in, size_t *len); #define GET_STR_DATA_LEN(str_obj_in, str_data, str_len) \ const byte *str_data; size_t str_len; if (MP_OBJ_IS_QSTR(str_obj_in)) \ { str_data = qstr_data(MP_OBJ_QSTR_VALUE(str_obj_in), &str_len); } \ - else { str_len = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->len; str_data = ((mp_obj_str_t*)MP_OBJ_TO_PTR(str_obj_in))->data; } + else { str_len = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->len; str_data = ((mp_obj_str_t *)MP_OBJ_TO_PTR(str_obj_in))->data; } #endif mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type_in, size_t n_args, const mp_obj_t *args, mp_map_t *kw_args); void mp_str_print_json(const mp_print_t *print, const byte *str_data, size_t str_len); mp_obj_t mp_obj_str_format(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs); mp_obj_t mp_obj_str_split(size_t n_args, const mp_obj_t *args); -mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte* data, size_t len); -mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte* data, size_t len); +mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte *data, size_t len); +mp_obj_t mp_obj_new_str_of_type(const mp_obj_type_t *type, const byte *data, size_t len); mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in); mp_int_t mp_obj_str_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags); size_t str_offset_to_index(const mp_obj_type_t *type, const byte *self_data, size_t self_len, - size_t offset); + size_t offset); const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len, - mp_obj_t index, bool is_slice); + mp_obj_t index, bool is_slice); const byte *find_subbytes(const byte *haystack, size_t hlen, const byte *needle, size_t nlen, int direction); extern const char nibble_to_hex_upper[16]; diff --git a/py/objstringio.c b/py/objstringio.c index eb40e51543..cc853aba6d 100644 --- a/py/objstringio.c +++ b/py/objstringio.c @@ -116,7 +116,7 @@ STATIC mp_uint_t stringio_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, mp_obj_stringio_t *o = MP_OBJ_TO_PTR(o_in); switch (request) { case MP_STREAM_SEEK: { - struct mp_stream_seek_t *s = (struct mp_stream_seek_t*)arg; + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; mp_uint_t ref = 0; switch (s->whence) { case MP_SEEK_CUR: @@ -168,7 +168,7 @@ STATIC mp_obj_t stringio_getvalue(mp_obj_t self_in) { mp_obj_stringio_t *self = MP_OBJ_TO_PTR(self_in); check_stringio_is_open(self); // TODO: Try to avoid copying string - return mp_obj_new_str_of_type(STREAM_TO_CONTENT_TYPE(self), (byte*)self->vstr->buf, self->vstr->len); + return mp_obj_new_str_of_type(STREAM_TO_CONTENT_TYPE(self), (byte *)self->vstr->buf, self->vstr->len); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(stringio_getvalue_obj, stringio_getvalue); @@ -262,7 +262,7 @@ const mp_obj_type_t mp_type_stringio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &stringio_stream_p, - .locals_dict = (mp_obj_dict_t*)&stringio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stringio_locals_dict, }; #if MICROPY_PY_IO_BYTESIO @@ -274,7 +274,7 @@ const mp_obj_type_t mp_type_bytesio = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &bytesio_stream_p, - .locals_dict = (mp_obj_dict_t*)&stringio_locals_dict, + .locals_dict = (mp_obj_dict_t *)&stringio_locals_dict, }; #endif diff --git a/py/objstrunicode.c b/py/objstrunicode.c index 50250abfa9..c86d48e63c 100644 --- a/py/objstrunicode.c +++ b/py/objstrunicode.c @@ -113,7 +113,7 @@ STATIC mp_obj_t uni_unary_op(mp_unary_op_t op, mp_obj_t self_in) { } size_t str_offset_to_index(const mp_obj_type_t *type, const byte *self_data, size_t self_len, - size_t offset) { + size_t offset) { if (offset > self_len) { mp_raise_ValueError(translate("offset out of bounds")); } @@ -135,7 +135,7 @@ size_t str_offset_to_index(const mp_obj_type_t *type, const byte *self_data, siz // Convert an index into a pointer to its lead byte. Out of bounds indexing will raise IndexError or // be capped to the first/last character of the string, depending on is_slice. const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, size_t self_len, - mp_obj_t index, bool is_slice) { + mp_obj_t index, bool is_slice) { // All str functions also handle bytes objects, and they call str_index_to_ptr(), // so it must handle bytes. if (type == &mp_type_bytes) { @@ -154,8 +154,7 @@ const byte *str_index_to_ptr(const mp_obj_type_t *type, const byte *self_data, s mp_raise_TypeError_varg(translate("string indices must be integers, not %q"), mp_obj_get_type_qstr(index)); } const byte *s, *top = self_data + self_len; - if (i < 0) - { + if (i < 0) { // Negative indexing is performed by counting from the end of the string. for (s = top - 1; i; --s) { if (s < self_data) { @@ -203,7 +202,7 @@ STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { GET_STR_DATA_LEN(self_in, self_data, self_len); if (value == MP_OBJ_SENTINEL) { // load -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { mp_obj_t ostart, ostop, ostep; mp_obj_slice_get(index, &ostart, &ostop, &ostep); @@ -229,7 +228,7 @@ STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { } return mp_obj_new_str_of_type(type, (const byte *)pstart, pstop - pstart); } -#endif + #endif const byte *s = str_index_to_ptr(type, self_data, self_len, index, false); int len = 1; if (UTF8_IS_NONASCII(*s)) { @@ -238,16 +237,16 @@ STATIC mp_obj_t str_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { ++len; } } - return mp_obj_new_str_via_qstr((const char*)s, len); // This will create a one-character string + return mp_obj_new_str_via_qstr((const char *)s, len); // This will create a one-character string } else { return MP_OBJ_NULL; // op not supported } } STATIC const mp_rom_map_elem_t struni_locals_dict_table[] = { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT { MP_ROM_QSTR(MP_QSTR_encode), MP_ROM_PTR(&str_encode_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_find), MP_ROM_PTR(&str_find_obj) }, { MP_ROM_QSTR(MP_QSTR_rfind), MP_ROM_PTR(&str_rfind_obj) }, { MP_ROM_QSTR(MP_QSTR_index), MP_ROM_PTR(&str_index_obj) }, @@ -294,7 +293,7 @@ const mp_obj_type_t mp_type_str = { .subscr = str_subscr, .getiter = mp_obj_new_str_iterator, .buffer_p = { .get_buffer = mp_obj_str_get_buffer }, - .locals_dict = (mp_obj_dict_t*)&struni_locals_dict, + .locals_dict = (mp_obj_dict_t *)&struni_locals_dict, }; /******************************************************************************/ @@ -313,7 +312,7 @@ STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) { if (self->cur < len) { const byte *cur = str + self->cur; const byte *end = utf8_next_char(str + self->cur); - mp_obj_t o_out = mp_obj_new_str_via_qstr((const char*)cur, end - cur); + mp_obj_t o_out = mp_obj_new_str_via_qstr((const char *)cur, end - cur); self->cur += end - cur; return o_out; } else { @@ -323,7 +322,7 @@ STATIC mp_obj_t str_it_iternext(mp_obj_t self_in) { STATIC mp_obj_t mp_obj_new_str_iterator(mp_obj_t str, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_str_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_str_it_t *o = (mp_obj_str_it_t*)iter_buf; + mp_obj_str_it_t *o = (mp_obj_str_it_t *)iter_buf; o->base.type = &mp_type_polymorph_iter; o->iternext = str_it_iternext; o->str = str; diff --git a/py/objtuple.c b/py/objtuple.c index d34a7f7624..fea4728230 100644 --- a/py/objtuple.c +++ b/py/objtuple.c @@ -125,7 +125,8 @@ STATIC mp_obj_t tuple_cmp_helper(mp_uint_t op, mp_obj_t self_in, mp_obj_t anothe mp_obj_t mp_obj_tuple_unary_op(mp_unary_op_t op, mp_obj_t self_in) { mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->len != 0); + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(self->len != 0); case MP_UNARY_OP_HASH: { // start hash with pointer to empty tuple, to make it fairly unique mp_int_t hash = (mp_int_t)mp_const_empty_tuple; @@ -134,8 +135,10 @@ mp_obj_t mp_obj_tuple_unary_op(mp_unary_op_t op, mp_obj_t self_in) { } return MP_OBJ_NEW_SMALL_INT(hash); } - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(self->len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(self->len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -187,7 +190,7 @@ mp_obj_t mp_obj_tuple_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { self = mp_instance_cast_to_native_base(self_in, &mp_type_tuple); } -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE if (MP_OBJ_IS_TYPE(index, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(self->len, index, &slice)) { @@ -197,7 +200,7 @@ mp_obj_t mp_obj_tuple_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t); return MP_OBJ_FROM_PTR(res); } -#endif + #endif size_t index_value = mp_get_index(self->base.type, self->len, index, false); return self->items[index_value]; } else { @@ -235,7 +238,7 @@ const mp_obj_type_t mp_type_tuple = { .binary_op = mp_obj_tuple_binary_op, .subscr = mp_obj_tuple_subscr, .getiter = mp_obj_tuple_getiter, - .locals_dict = (mp_obj_dict_t*)&tuple_locals_dict, + .locals_dict = (mp_obj_dict_t *)&tuple_locals_dict, }; // the zero-length tuple @@ -293,7 +296,7 @@ STATIC mp_obj_t tuple_it_iternext(mp_obj_t self_in) { mp_obj_t mp_obj_tuple_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) { assert(sizeof(mp_obj_tuple_it_t) <= sizeof(mp_obj_iter_buf_t)); - mp_obj_tuple_it_t *o = (mp_obj_tuple_it_t*)iter_buf; + mp_obj_tuple_it_t *o = (mp_obj_tuple_it_t *)iter_buf; o->base.type = &mp_type_polymorph_iter; o->iternext = tuple_it_iternext; o->tuple = MP_OBJ_TO_PTR(o_in); diff --git a/py/objtuple.h b/py/objtuple.h index d2e87e9949..7bfb447fa4 100644 --- a/py/objtuple.h +++ b/py/objtuple.h @@ -54,7 +54,7 @@ extern const mp_obj_type_t mp_type_attrtuple; const mp_rom_obj_tuple_t tuple_obj_name = { \ .base = {&mp_type_attrtuple}, \ .len = nitems, \ - .items = { __VA_ARGS__ , MP_ROM_PTR((void*)fields) } \ + .items = { __VA_ARGS__, MP_ROM_PTR((void *)fields) } \ } #if MICROPY_PY_COLLECTIONS diff --git a/py/objtype.c b/py/objtype.c index 1254b015c9..b7b2d156b2 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -46,7 +46,7 @@ #endif #define ENABLE_SPECIAL_ACCESSORS \ - (MICROPY_PY_DESCRIPTORS || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY) + (MICROPY_PY_DESCRIPTORS || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY) #define TYPE_FLAG_IS_SUBCLASSED (0x0001) #define TYPE_FLAG_HAS_SPECIAL_ACCESSORS (0x0002) @@ -70,7 +70,7 @@ STATIC int instance_count_native_bases(const mp_obj_type_t *type, const mp_obj_t // No parents so end search here. return count; #if MICROPY_MULTIPLE_INHERITANCE - } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) { + } else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) { // Multiple parents, search through them all recursively. const mp_obj_tuple_t *parent_tuple = type->parent; const mp_obj_t *item = parent_tuple->items; @@ -150,7 +150,7 @@ struct class_lookup_data { bool is_type; }; -STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_type_t *type) { +STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_type_t *type) { assert(lookup->dest[0] == MP_OBJ_NULL); assert(lookup->dest[1] == MP_OBJ_NULL); for (;;) { @@ -160,10 +160,10 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ // this should not be applied to class types, as will result in extra // lookup either. if (lookup->meth_offset != 0 && mp_obj_is_native_type(type)) { -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wcast-align" - if (*(void**)((char*)type + lookup->meth_offset) != NULL) { -#pragma GCC diagnostic pop + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + if (*(void **)((char *)type + lookup->meth_offset) != NULL) { + #pragma GCC diagnostic pop DEBUG_printf("mp_obj_class_lookup: Matched special meth slot (off=%d) for %s\n", lookup->meth_offset, qstr_str(lookup->attr)); lookup->dest[0] = MP_OBJ_SENTINEL; @@ -180,7 +180,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ if (lookup->is_type) { // If we look up a class method, we need to return original type for which we // do a lookup, not a (base) type in which we found the class method. - const mp_obj_type_t *org_type = (const mp_obj_type_t*)lookup->obj; + const mp_obj_type_t *org_type = (const mp_obj_type_t *)lookup->obj; mp_convert_member_lookup(MP_OBJ_NULL, org_type, elem->value, lookup->dest); } else if (MP_OBJ_IS_TYPE(elem->value, &mp_type_property)) { lookup->dest[0] = elem->value; @@ -189,12 +189,13 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ mp_obj_instance_t *obj = lookup->obj; mp_convert_member_lookup(MP_OBJ_FROM_PTR(obj), type, elem->value, lookup->dest); } -#if DEBUG_PRINT + #if DEBUG_PRINT printf("mp_obj_class_lookup: Returning: "); - mp_obj_print(lookup->dest[0], PRINT_REPR); printf(" "); + mp_obj_print(lookup->dest[0], PRINT_REPR); + printf(" "); // Don't try to repr() lookup->dest[1], as we can be called recursively printf("<%q @%p>\n", mp_obj_get_type_qstr(lookup->dest[1]), lookup->dest[1]); -#endif + #endif return; } } @@ -215,13 +216,13 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ DEBUG_printf("mp_obj_class_lookup: No more parents\n"); return; #if MICROPY_MULTIPLE_INHERITANCE - } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) { + } else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) { const mp_obj_tuple_t *parent_tuple = type->parent; const mp_obj_t *item = parent_tuple->items; const mp_obj_t *top = item + parent_tuple->len - 1; for (; item < top; ++item) { assert(MP_OBJ_IS_TYPE(*item, &mp_type_type)); - mp_obj_type_t *bt = (mp_obj_type_t*)MP_OBJ_TO_PTR(*item); + mp_obj_type_t *bt = (mp_obj_type_t *)MP_OBJ_TO_PTR(*item); if (bt == &mp_type_object) { // Not a "real" type continue; @@ -234,7 +235,7 @@ STATIC void mp_obj_class_lookup(struct class_lookup_data *lookup, const mp_obj_ // search last base (simple tail recursion elimination) assert(MP_OBJ_IS_TYPE(*item, &mp_type_type)); - type = (mp_obj_type_t*)MP_OBJ_TO_PTR(*item); + type = (mp_obj_type_t *)MP_OBJ_TO_PTR(*item); #endif } else { type = type->parent; @@ -374,10 +375,10 @@ mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self, size_t n_args, cons } if (init_ret != mp_const_none) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("__init__() should return None")); + mp_raise_TypeError(translate("__init__() should return None")); #else - mp_raise_TypeError_varg(translate("__init__() should return None, not '%q'"), - mp_obj_get_type_qstr(init_ret)); + mp_raise_TypeError_varg(translate("__init__() should return None, not '%q'"), + mp_obj_get_type_qstr(init_ret)); #endif } @@ -596,7 +597,7 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des dest[0] = elem->value; return; } -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT if (attr == MP_QSTR___dict__) { // Create a new dict with a copy of the instance's map items. // This creates, unlike CPython, a 'read-only' __dict__: modifying @@ -611,7 +612,7 @@ STATIC void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des dest[0] = attr_dict; return; } -#endif + #endif struct class_lookup_data lookup = { .obj = self, .attr = attr, @@ -889,10 +890,10 @@ mp_obj_t mp_obj_instance_call(mp_obj_t self_in, size_t n_args, size_t n_kw, cons mp_obj_t call = mp_obj_instance_get_call(self_in, member); if (call == MP_OBJ_NULL) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object not callable")); + mp_raise_TypeError(translate("object not callable")); #else - mp_raise_TypeError_varg(translate("'%q' object is not callable"), - mp_obj_get_type_qstr(self_in)); + mp_raise_TypeError_varg(translate("'%q' object is not callable"), + mp_obj_get_type_qstr(self_in)); #endif } mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in); @@ -1025,9 +1026,9 @@ STATIC mp_obj_t type_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp if (self->make_new == NULL) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("cannot create instance")); + mp_raise_TypeError(translate("cannot create instance")); #else - mp_raise_TypeError_varg(translate("cannot create '%q' instances"), self->name); + mp_raise_TypeError_varg(translate("cannot create '%q' instances"), self->name); #endif } @@ -1053,7 +1054,7 @@ STATIC void type_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { } #endif struct class_lookup_data lookup = { - .obj = (mp_obj_instance_t*)self, + .obj = (mp_obj_instance_t *)self, .attr = attr, .meth_offset = 0, .dest = dest, @@ -1135,10 +1136,10 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) // TODO: Verify with CPy, tested on function type if (t->make_new == NULL) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("type is not an acceptable base type")); + mp_raise_TypeError(translate("type is not an acceptable base type")); #else - mp_raise_TypeError_varg( - translate("type '%q' is not an acceptable base type"), t->name); + mp_raise_TypeError_varg( + translate("type '%q' is not an acceptable base type"), t->name); #endif } #if ENABLE_SPECIAL_ACCESSORS @@ -1161,7 +1162,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) o->attr = mp_obj_instance_attr; o->subscr = instance_subscr; o->getiter = instance_getiter; - //o->iternext = ; not implemented + // o->iternext = ; not implemented o->buffer_p.get_buffer = instance_get_buffer; if (bases_len > 0) { @@ -1169,7 +1170,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) // abstract base class which would translate C-level protocol to // Python method calls, and any subclass inheriting from it will // support this feature. - o->protocol = ((mp_obj_type_t*)MP_OBJ_TO_PTR(bases_items[0]))->protocol; + o->protocol = ((mp_obj_type_t *)MP_OBJ_TO_PTR(bases_items[0]))->protocol; if (bases_len >= 2) { #if MICROPY_MULTIPLE_INHERITANCE @@ -1195,10 +1196,10 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) #if ENABLE_SPECIAL_ACCESSORS // Check if the class has any special accessor methods if (!(o->flags & TYPE_FLAG_HAS_SPECIAL_ACCESSORS) && - (map_has_special_accessors(locals_map) || - (num_native_bases == 1 && - native_base->locals_dict != NULL && - map_has_special_accessors(&native_base->locals_dict->map)))) { + (map_has_special_accessors(locals_map) || + (num_native_bases == 1 && + native_base->locals_dict != NULL && + map_has_special_accessors(&native_base->locals_dict->map)))) { o->flags |= TYPE_FLAG_HAS_SPECIAL_ACCESSORS; } #endif @@ -1239,11 +1240,11 @@ STATIC mp_obj_t super_make_new(const mp_obj_type_t *type_in, size_t n_args, cons // 0 arguments are turned into 2 in the compiler // 1 argument is not yet implemented mp_arg_check_num(n_args, kw_args, 2, 2, false); - if(!MP_OBJ_IS_TYPE(args[0], &mp_type_type)) { + if (!MP_OBJ_IS_TYPE(args[0], &mp_type_type)) { mp_raise_TypeError(translate("first argument to super() must be type")); } mp_obj_super_t *o = m_new_obj(mp_obj_super_t); - *o = (mp_obj_super_t){{type_in}, args[0], args[1]}; + *o = (mp_obj_super_t) {{type_in}, args[0], args[1]}; return MP_OBJ_FROM_PTR(o); } @@ -1276,7 +1277,7 @@ STATIC void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { if (type->parent == NULL) { // no parents, do nothing #if MICROPY_MULTIPLE_INHERITANCE - } else if (((mp_obj_base_t*)type->parent)->type == &mp_type_tuple) { + } else if (((mp_obj_base_t *)type->parent)->type == &mp_type_tuple) { const mp_obj_tuple_t *parent_tuple = type->parent; size_t len = parent_tuple->len; const mp_obj_t *items = parent_tuple->items; @@ -1287,7 +1288,7 @@ STATIC void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { // and we don't want to lookup native methods in object. continue; } - mp_obj_class_lookup(&lookup, (mp_obj_type_t*)MP_OBJ_TO_PTR(items[i])); + mp_obj_class_lookup(&lookup, (mp_obj_type_t *)MP_OBJ_TO_PTR(items[i])); if (dest[0] != MP_OBJ_NULL) { break; } @@ -1373,7 +1374,7 @@ bool mp_obj_is_subclass_fast(mp_const_obj_t object, mp_const_obj_t classinfo) { // type has no parents return false; #if MICROPY_MULTIPLE_INHERITANCE - } else if (((mp_obj_base_t*)self->parent)->type == &mp_type_tuple) { + } else if (((mp_obj_base_t *)self->parent)->type == &mp_type_tuple) { // get the base objects (they should be type objects) const mp_obj_tuple_t *parent_tuple = self->parent; const mp_obj_t *item = parent_tuple->items; @@ -1440,7 +1441,7 @@ mp_obj_t mp_instance_cast_to_native_base(mp_obj_t self_in, mp_const_obj_t native if (MP_OBJ_FROM_PTR(self_type) == native_type) { return self_in; } - mp_obj_instance_t *self = (mp_obj_instance_t*)MP_OBJ_TO_PTR(self_in); + mp_obj_instance_t *self = (mp_obj_instance_t *)MP_OBJ_TO_PTR(self_in); return self->subobj[0]; } @@ -1453,7 +1454,7 @@ STATIC mp_obj_t static_class_method_make_new(const mp_obj_type_t *self, size_t n mp_arg_check_num(n_args, kw_args, 1, 1, false); mp_obj_static_class_method_t *o = m_new_obj(mp_obj_static_class_method_t); - *o = (mp_obj_static_class_method_t){{self}, args[0]}; + *o = (mp_obj_static_class_method_t) {{self}, args[0]}; return MP_OBJ_FROM_PTR(o); } diff --git a/py/parse.c b/py/parse.c index 28621cf898..c8a975e0d2 100644 --- a/py/parse.c +++ b/py/parse.c @@ -58,13 +58,13 @@ #define RULE_ARG_OPT_RULE (0x3000) // (un)comment to use rule names; for debugging -//#define USE_RULE_NAME (1) +// #define USE_RULE_NAME (1) enum { // define rules with a compile function #define DEF_RULE(rule, comp, kind, ...) RULE_##rule, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC RULE_const_object, // special node for a constant, generic Python object @@ -72,7 +72,7 @@ enum { // define rules without a compile function #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) RULE_##rule, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC }; @@ -89,7 +89,7 @@ STATIC const uint8_t rule_act_table[] = { #define DEF_RULE(rule, comp, kind, ...) kind, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC @@ -97,7 +97,7 @@ STATIC const uint8_t rule_act_table[] = { #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) kind, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC @@ -118,13 +118,13 @@ STATIC const uint16_t rule_arg_combined_table[] = { #define DEF_RULE(rule, comp, kind, ...) __VA_ARGS__, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) __VA_ARGS__, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC @@ -144,12 +144,12 @@ STATIC const uint16_t rule_arg_combined_table[] = { enum { #define DEF_RULE(rule, comp, kind, ...) RULE_PADDING(rule, __VA_ARGS__) #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) RULE_PADDING(rule, __VA_ARGS__) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC }; @@ -167,13 +167,13 @@ enum { STATIC const uint8_t rule_arg_offset_table[] = { #define DEF_RULE(rule, comp, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) & 0xff, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC 0, // RULE_const_object #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) RULE_ARG_OFFSET(rule, __VA_ARGS__) & 0xff, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC }; @@ -190,20 +190,20 @@ static const size_t FIRST_RULE_WITH_OFFSET_ABOVE_255 = #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC -0; + 0; #if defined(USE_RULE_NAME) && USE_RULE_NAME // Define an array of rule names corresponding to each rule STATIC const char *const rule_name_table[] = { #define DEF_RULE(rule, comp, kind, ...) #rule, #define DEF_RULE_NC(rule, kind, ...) -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC "", // RULE_const_object #define DEF_RULE(rule, comp, kind, ...) #define DEF_RULE_NC(rule, kind, ...) #rule, -#include "py/grammar.h" + #include "py/grammar.h" #undef DEF_RULE #undef DEF_RULE_NC }; @@ -261,7 +261,7 @@ STATIC void *parser_alloc(parser_t *parser, size_t num_bytes) { if (chunk != NULL && chunk->union_.used + num_bytes > chunk->alloc) { // not enough room at end of previously allocated chunk so try to grow - mp_parse_chunk_t *new_data = (mp_parse_chunk_t*)m_renew_maybe(byte, chunk, + mp_parse_chunk_t *new_data = (mp_parse_chunk_t *)m_renew_maybe(byte, chunk, sizeof(mp_parse_chunk_t) + chunk->alloc, sizeof(mp_parse_chunk_t) + chunk->alloc + num_bytes, false); if (new_data == NULL) { @@ -284,7 +284,7 @@ STATIC void *parser_alloc(parser_t *parser, size_t num_bytes) { if (alloc < num_bytes) { alloc = num_bytes; } - chunk = (mp_parse_chunk_t*)m_new(byte, sizeof(mp_parse_chunk_t) + alloc); + chunk = (mp_parse_chunk_t *)m_new(byte, sizeof(mp_parse_chunk_t) + alloc); chunk->alloc = alloc; chunk->union_.used = 0; parser->cur_chunk = chunk; @@ -324,12 +324,12 @@ STATIC uint8_t pop_rule(parser_t *parser, size_t *arg_i, size_t *src_line) { bool mp_parse_node_is_const_false(mp_parse_node_t pn) { return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_FALSE) - || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0); + || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) == 0); } bool mp_parse_node_is_const_true(mp_parse_node_t pn) { return MP_PARSE_NODE_IS_TOKEN_KIND(pn, MP_TOKEN_KW_TRUE) - || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) != 0); + || (MP_PARSE_NODE_IS_SMALL_INT(pn) && MP_PARSE_NODE_LEAF_SMALL_INT(pn) != 0); } bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) { @@ -337,7 +337,7 @@ bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) { *o = MP_OBJ_NEW_SMALL_INT(MP_PARSE_NODE_LEAF_SMALL_INT(pn)); return true; } else if (MP_PARSE_NODE_IS_STRUCT_KIND(pn, RULE_const_object)) { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D // nodes are 32-bit pointers, but need to extract 64-bit object *o = (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32); @@ -358,7 +358,7 @@ int mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_nod *nodes = pn; return 1; } else { - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)(*pn); + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)(*pn); if (MP_PARSE_NODE_STRUCT_KIND(pns) != pn_kind) { *nodes = pn; return 1; @@ -372,7 +372,7 @@ int mp_parse_node_extract_list(mp_parse_node_t *pn, size_t pn_kind, mp_parse_nod #if MICROPY_DEBUG_PRINTERS void mp_parse_node_print(mp_parse_node_t pn, size_t indent) { if (MP_PARSE_NODE_IS_STRUCT(pn)) { - printf("[% 4d] ", (int)((mp_parse_node_struct_t*)pn)->source_line); + printf("[% 4d] ", (int)((mp_parse_node_struct_t *)pn)->source_line); } else { printf(" "); } @@ -387,16 +387,23 @@ void mp_parse_node_print(mp_parse_node_t pn, size_t indent) { } else if (MP_PARSE_NODE_IS_LEAF(pn)) { uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn); switch (MP_PARSE_NODE_LEAF_KIND(pn)) { - case MP_PARSE_NODE_ID: printf("id(%s)\n", qstr_str(arg)); break; - case MP_PARSE_NODE_STRING: printf("str(%s)\n", qstr_str(arg)); break; - case MP_PARSE_NODE_BYTES: printf("bytes(%s)\n", qstr_str(arg)); break; + case MP_PARSE_NODE_ID: + printf("id(%s)\n", qstr_str(arg)); + break; + case MP_PARSE_NODE_STRING: + printf("str(%s)\n", qstr_str(arg)); + break; + case MP_PARSE_NODE_BYTES: + printf("bytes(%s)\n", qstr_str(arg)); + break; default: assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN); - printf("tok(%u)\n", (uint)arg); break; + printf("tok(%u)\n", (uint)arg); + break; } } else { // node must be a mp_parse_node_struct_t - mp_parse_node_struct_t *pns = (mp_parse_node_struct_t*)pn; + mp_parse_node_struct_t *pns = (mp_parse_node_struct_t *)pn; if (MP_PARSE_NODE_STRUCT_KIND(pns) == RULE_const_object) { #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D printf("literal const(%016llx)\n", (uint64_t)pns->nodes[0] | ((uint64_t)pns->nodes[1] << 32)); @@ -477,7 +484,7 @@ STATIC void push_result_token(parser_t *parser, uint8_t rule_id) { mp_parse_node_t pn; mp_lexer_t *lex = parser->lexer; if (lex->tok_kind == MP_TOKEN_NAME) { - if(lex->vstr.len >= (1 << (8 * MICROPY_QSTR_BYTES_IN_LEN))) { + if (lex->vstr.len >= (1 << (8 * MICROPY_QSTR_BYTES_IN_LEN))) { mp_raise_msg(&mp_type_SyntaxError, translate("Name too long")); } qstr id = qstr_from_strn(lex->vstr.buf, lex->vstr.len); @@ -526,7 +533,7 @@ STATIC void push_result_token(parser_t *parser, uint8_t rule_id) { // not interned, make a node holding a pointer to the string/bytes object mp_obj_t o = mp_obj_new_str_copy( lex->tok_kind == MP_TOKEN_STRING ? &mp_type_str : &mp_type_bytes, - (const byte*)lex->vstr.buf, lex->vstr.len); + (const byte *)lex->vstr.buf, lex->vstr.len); pn = make_node_const_object(parser, lex->tok_line, o); } } else { @@ -639,8 +646,8 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { arg0 = mp_binary_op(op, arg0, arg1); } } else if (rule_id == RULE_shift_expr - || rule_id == RULE_arith_expr - || rule_id == RULE_term) { + || rule_id == RULE_arith_expr + || rule_id == RULE_term) { // folding for binary ops: << >> + - * / % // mp_parse_node_t pn = peek_result(parser, num_args - 1); if (!mp_parse_node_get_int_maybe(pn, &arg0)) { @@ -657,13 +664,13 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { MP_BINARY_OP_ADD, MP_BINARY_OP_SUBTRACT, MP_BINARY_OP_MULTIPLY, - 255,//MP_BINARY_OP_POWER, - 255,//MP_BINARY_OP_TRUE_DIVIDE, + 255,// MP_BINARY_OP_POWER, + 255,// MP_BINARY_OP_TRUE_DIVIDE, MP_BINARY_OP_FLOOR_DIVIDE, MP_BINARY_OP_MODULO, - 255,//MP_BINARY_OP_LESS + 255,// MP_BINARY_OP_LESS MP_BINARY_OP_LSHIFT, - 255,//MP_BINARY_OP_MORE + 255,// MP_BINARY_OP_MORE MP_BINARY_OP_RSHIFT, }; mp_binary_op_t op = token_to_op[tok - MP_TOKEN_OP_PLUS]; @@ -707,14 +714,14 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { mp_parse_node_t pn1 = peek_result(parser, 0); if (!MP_PARSE_NODE_IS_NULL(pn1) && !(MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_augassign) - || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) { + || MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_expr_stmt_assign_list))) { // this node is of the form = mp_parse_node_t pn0 = peek_result(parser, 1); if (MP_PARSE_NODE_IS_ID(pn0) && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_atom_expr_normal) - && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t*)pn1)->nodes[0]) - && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t*)pn1)->nodes[0]) == MP_QSTR_const - && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t*)pn1)->nodes[1], RULE_trailer_paren) + && MP_PARSE_NODE_IS_ID(((mp_parse_node_struct_t *)pn1)->nodes[0]) + && MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t *)pn1)->nodes[0]) == MP_QSTR_const + && MP_PARSE_NODE_IS_STRUCT_KIND(((mp_parse_node_struct_t *)pn1)->nodes[1], RULE_trailer_paren) ) { // code to assign dynamic constants: id = const(value) @@ -722,13 +729,13 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { qstr id = MP_PARSE_NODE_LEAF_ARG(pn0); // get the value - mp_parse_node_t pn_value = ((mp_parse_node_struct_t*)((mp_parse_node_struct_t*)pn1)->nodes[1])->nodes[0]; + mp_parse_node_t pn_value = ((mp_parse_node_struct_t *)((mp_parse_node_struct_t *)pn1)->nodes[1])->nodes[0]; mp_obj_t value; if (!mp_parse_node_get_int_maybe(pn_value, &value)) { mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, translate("constant must be an integer")); mp_obj_exception_add_traceback(exc, parser->lexer->source_name, - ((mp_parse_node_struct_t*)pn1)->source_line, MP_QSTR_NULL); + ((mp_parse_node_struct_t *)pn1)->source_line, MP_QSTR_NULL); nlr_raise(exc); } @@ -762,16 +769,16 @@ STATIC bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { mp_parse_node_t pn0 = peek_result(parser, 1); mp_parse_node_t pn1 = peek_result(parser, 0); if (!(MP_PARSE_NODE_IS_ID(pn0) - && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) { + && MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_trailer_period))) { return false; } // id1.id2 // look it up in constant table, see if it can be replaced with an integer - mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t*)pn1; + mp_parse_node_struct_t *pns1 = (mp_parse_node_struct_t *)pn1; assert(MP_PARSE_NODE_IS_ID(pns1->nodes[0])); qstr q_base = MP_PARSE_NODE_LEAF_ARG(pn0); qstr q_attr = MP_PARSE_NODE_LEAF_ARG(pns1->nodes[0]); - mp_map_elem_t *elem = mp_map_lookup((mp_map_t*)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP); + mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)&mp_constants_map, MP_OBJ_NEW_QSTR(q_base), MP_MAP_LOOKUP); if (elem == NULL) { return false; } @@ -883,9 +890,14 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { // work out the top-level rule to use, and push it on the stack size_t top_level_rule; switch (input_kind) { - case MP_PARSE_SINGLE_INPUT: top_level_rule = RULE_single_input; break; - case MP_PARSE_EVAL_INPUT: top_level_rule = RULE_eval_input; break; - default: top_level_rule = RULE_file_input; + case MP_PARSE_SINGLE_INPUT: + top_level_rule = RULE_single_input; + break; + case MP_PARSE_EVAL_INPUT: + top_level_rule = RULE_eval_input; + break; + default: + top_level_rule = RULE_file_input; } push_rule(&parser, lex->tok_line, top_level_rule, 0); @@ -894,7 +906,7 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { bool backtrack = false; for (;;) { - next_rule: + next_rule: if (parser.rule_stack_top == 0) { break; } @@ -924,7 +936,7 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { backtrack = false; } for (; i < n; ++i) { - //printf("--> inside for @L924\n"); + // printf("--> inside for @L924\n"); uint16_t kind = rule_arg[i] & RULE_ARG_KIND_MASK; if (kind == RULE_ARG_TOK) { if (lex->tok_kind == (rule_arg[i] & RULE_ARG_ARG_MASK)) { @@ -1067,7 +1079,7 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { // n=3 is: item (sep item)* [sep] bool had_trailing_sep; if (backtrack) { - list_backtrack: + list_backtrack: had_trailing_sep = false; if (n == 2) { if (i == 1) { @@ -1169,7 +1181,7 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { ) { syntax_error:; mp_obj_t exc; - switch(lex->tok_kind) { + switch (lex->tok_kind) { case MP_TOKEN_INDENT: exc = mp_obj_new_exception_msg(&mp_type_IndentationError, translate("unexpected indent")); @@ -1178,8 +1190,8 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { exc = mp_obj_new_exception_msg(&mp_type_IndentationError, translate("unindent does not match any outer indentation level")); break; -#if MICROPY_COMP_FSTRING_LITERAL -#if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED + #if MICROPY_COMP_FSTRING_LITERAL + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED case MP_TOKEN_FSTRING_BACKSLASH: exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, translate("f-string expression part cannot include a backslash")); @@ -1204,7 +1216,7 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { exc = mp_obj_new_exception_msg(&mp_type_NotImplementedError, translate("raw f-strings are not implemented")); break; -#else + #else case MP_TOKEN_FSTRING_BACKSLASH: case MP_TOKEN_FSTRING_COMMENT: case MP_TOKEN_FSTRING_UNCLOSED: @@ -1214,8 +1226,8 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, translate("malformed f-string")); break; -#endif -#endif + #endif + #endif default: exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, translate("invalid syntax")); diff --git a/py/parse.h b/py/parse.h index 946b41eac3..1e6a5888eb 100644 --- a/py/parse.h +++ b/py/parse.h @@ -63,7 +63,7 @@ typedef struct _mp_parse_node_struct_t { #define MP_PARSE_NODE_IS_NULL(pn) ((pn) == MP_PARSE_NODE_NULL) #define MP_PARSE_NODE_IS_LEAF(pn) ((pn) & 3) #define MP_PARSE_NODE_IS_STRUCT(pn) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0) -#define MP_PARSE_NODE_IS_STRUCT_KIND(pn, k) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0 && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t*)(pn)) == (k)) +#define MP_PARSE_NODE_IS_STRUCT_KIND(pn, k) ((pn) != MP_PARSE_NODE_NULL && ((pn) & 3) == 0 && MP_PARSE_NODE_STRUCT_KIND((mp_parse_node_struct_t *)(pn)) == (k)) #define MP_PARSE_NODE_IS_SMALL_INT(pn) (((pn) & 0x1) == MP_PARSE_NODE_SMALL_INT) #define MP_PARSE_NODE_IS_ID(pn) (((pn) & 0x0f) == MP_PARSE_NODE_ID) diff --git a/py/parsenum.c b/py/parsenum.c index a72829b203..96f05ff82e 100644 --- a/py/parsenum.c +++ b/py/parsenum.c @@ -42,7 +42,7 @@ STATIC NORETURN void raise_exc(mp_obj_t exc, mp_lexer_t *lex) { // if lex!=NULL then the parser called us and we need to convert the // exception's type from ValueError to SyntaxError and add traceback info if (lex != NULL) { - ((mp_obj_base_t*)MP_OBJ_TO_PTR(exc))->type = &mp_type_SyntaxError; + ((mp_obj_base_t *)MP_OBJ_TO_PTR(exc))->type = &mp_type_SyntaxError; mp_obj_exception_add_traceback(exc, lex->source_name, lex->tok_line, MP_QSTR_NULL); } nlr_raise(exc); @@ -75,7 +75,7 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m } // parse optional base prefix - str += mp_parse_num_base((const char*)str, top - str, &base); + str += mp_parse_num_base((const char *)str, top - str, &base); // string should be an integer number mp_int_t int_val = 0; @@ -139,30 +139,30 @@ have_ret_val: overflow: // reparse using long int { - const char *s2 = (const char*)str_val_start; + const char *s2 = (const char *)str_val_start; ret_val = mp_obj_new_int_from_str_len(&s2, top - str_val_start, neg, base); - str = (const byte*)s2; + str = (const byte *)s2; goto have_ret_val; } -value_error: ; +value_error:; #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_ValueError, - translate("invalid syntax for integer")); - raise_exc(exc, lex); + mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_ValueError, + translate("invalid syntax for integer")); + raise_exc(exc, lex); #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NORMAL - mp_obj_t exc = mp_obj_new_exception_msg_varg(&mp_type_ValueError, - translate("invalid syntax for integer with base %d"), base); - raise_exc(exc, lex); + mp_obj_t exc = mp_obj_new_exception_msg_varg(&mp_type_ValueError, + translate("invalid syntax for integer with base %d"), base); + raise_exc(exc, lex); #else - vstr_t vstr; - mp_print_t print; - vstr_init_print(&vstr, 50, &print); - mp_printf(&print, "invalid syntax for integer with base %d: ", base); - mp_str_print_quoted(&print, str_val_start, top - str_val_start, true); - mp_obj_t exc = mp_obj_new_exception_arg1(&mp_type_ValueError, - mp_obj_new_str_from_vstr(&mp_type_str, &vstr)); - raise_exc(exc, lex); + vstr_t vstr; + mp_print_t print; + vstr_init_print(&vstr, 50, &print); + mp_printf(&print, "invalid syntax for integer with base %d: ", base); + mp_str_print_quoted(&print, str_val_start, top - str_val_start, true); + mp_obj_t exc = mp_obj_new_exception_arg1(&mp_type_ValueError, + mp_obj_new_str_from_vstr(&mp_type_str, &vstr)); + raise_exc(exc, lex); #endif } @@ -173,19 +173,19 @@ typedef enum { } parse_dec_in_t; mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex) { -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT // DEC_VAL_MAX only needs to be rough and is used to retain precision while not overflowing // SMALL_NORMAL_VAL is the smallest power of 10 that is still a normal float -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT #define DEC_VAL_MAX 1e20F #define SMALL_NORMAL_VAL (1e-37F) #define SMALL_NORMAL_EXP (-37) -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE #define DEC_VAL_MAX 1e200 #define SMALL_NORMAL_VAL (1e-307) #define SMALL_NORMAL_EXP (-307) -#endif + #endif const char *top = str + len; mp_float_t dec_val = 0; @@ -214,7 +214,7 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool if (str + 2 < top && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'f') { // inf str += 3; - dec_val = (mp_float_t) INFINITY; + dec_val = (mp_float_t)INFINITY; if (str + 4 < top && (str[0] | 0x20) == 'i' && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'i' && (str[3] | 0x20) == 't' && (str[4] | 0x20) == 'y') { // infinity str += 5; @@ -320,17 +320,17 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool } // return the object -#if MICROPY_PY_BUILTINS_COMPLEX + #if MICROPY_PY_BUILTINS_COMPLEX if (imag) { return mp_obj_new_complex(0, dec_val); } else if (force_complex) { return mp_obj_new_complex(dec_val, 0); } -#else + #else if (imag || force_complex) { raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, translate("complex values not supported")), lex); } -#endif + #endif else { return mp_obj_new_float(dec_val); } @@ -338,7 +338,7 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool value_error: raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, translate("invalid syntax for number")), lex); -#else + #else raise_exc(mp_obj_new_exception_msg(&mp_type_ValueError, translate("decimal numbers not supported")), lex); -#endif + #endif } diff --git a/py/parsenumbase.c b/py/parsenumbase.c index e4ac6d00ed..0802b435f0 100644 --- a/py/parsenumbase.c +++ b/py/parsenumbase.c @@ -31,7 +31,7 @@ // find real radix base, and strip preceding '0x', '0o' and '0b' // puts base in *base, and returns number of bytes to skip the prefix size_t mp_parse_num_base(const char *str, size_t len, int *base) { - const byte *p = (const byte*)str; + const byte *p = (const byte *)str; if (len <= 1) { goto no_prefix; } @@ -67,5 +67,5 @@ size_t mp_parse_num_base(const char *str, size_t len, int *base) { *base = 10; } } - return p - (const byte*)str; + return p - (const byte *)str; } diff --git a/py/persistentcode.c b/py/persistentcode.c index 9b438453ad..4e352ce7a4 100644 --- a/py/persistentcode.c +++ b/py/persistentcode.c @@ -116,7 +116,7 @@ STATIC int read_byte(mp_reader_t *reader) { STATIC void read_bytes(mp_reader_t *reader, byte *buf, size_t len) { while (len-- > 0) { - mp_uint_t b =reader->readbyte(reader->data); + mp_uint_t b = reader->readbyte(reader->data); if (b == MP_READER_EOF) { raise_corrupt_mpy(); } @@ -142,7 +142,7 @@ STATIC size_t read_uint(mp_reader_t *reader) { STATIC qstr load_qstr(mp_reader_t *reader) { size_t len = read_uint(reader); char str[len]; - read_bytes(reader, (byte*)str, len); + read_bytes(reader, (byte *)str, len); qstr qst = qstr_from_strn(str, len); return qst; } @@ -155,7 +155,7 @@ STATIC mp_obj_t load_obj(mp_reader_t *reader) { size_t len = read_uint(reader); vstr_t vstr; vstr_init_len(&vstr, len); - read_bytes(reader, (byte*)vstr.buf, len); + read_bytes(reader, (byte *)vstr.buf, len); if (obj_type == 's' || obj_type == 'b') { return mp_obj_new_str_from_vstr(obj_type == 's' ? &mp_type_str : &mp_type_bytes, &vstr); } else if (obj_type == 'i') { @@ -196,9 +196,11 @@ STATIC mp_raw_code_t *load_raw_code(mp_reader_t *reader) { // load qstrs and link global qstr ids into bytecode qstr simple_name = load_qstr(reader); qstr source_file = load_qstr(reader); - ((byte*)ip2)[0] = simple_name; ((byte*)ip2)[1] = simple_name >> 8; - ((byte*)ip2)[2] = source_file; ((byte*)ip2)[3] = source_file >> 8; - load_bytecode_qstrs(reader, (byte*)ip, bytecode + bc_len); + ((byte *)ip2)[0] = simple_name; + ((byte *)ip2)[1] = simple_name >> 8; + ((byte *)ip2)[2] = source_file; + ((byte *)ip2)[3] = source_file >> 8; + load_bytecode_qstrs(reader, (byte *)ip, bytecode + bc_len); // load constant table size_t n_obj = read_uint(reader); @@ -262,7 +264,7 @@ mp_raw_code_t *mp_raw_code_load_file(const char *filename) { #include "py/objstr.h" STATIC void mp_print_bytes(mp_print_t *print, const byte *data, size_t len) { - print->print_strn(print->data, (const char*)data, len); + print->print_strn(print->data, (const char *)data, len); } #define BYTES_FOR_INT ((BYTES_PER_WORD * 8 + 6) / 7) @@ -274,7 +276,7 @@ STATIC void mp_print_uint(mp_print_t *print, size_t n) { for (; n != 0; n >>= 7) { *--p = 0x80 | (n & 0x7f); } - print->print_strn(print->data, (char*)p, buf + sizeof(buf) - p); + print->print_strn(print->data, (char *)p, buf + sizeof(buf) - p); } STATIC void save_qstr(mp_print_t *print, qstr qst) { @@ -296,7 +298,7 @@ STATIC void save_obj(mp_print_t *print, mp_obj_t o) { const char *str = mp_obj_str_get_data(o, &len); mp_print_bytes(print, &obj_type, 1); mp_print_uint(print, len); - mp_print_bytes(print, (const byte*)str, len); + mp_print_bytes(print, (const byte *)str, len); } else if (MP_OBJ_TO_PTR(o) == &mp_const_ellipsis_obj) { byte obj_type = 'e'; mp_print_bytes(print, &obj_type, 1); @@ -320,7 +322,7 @@ STATIC void save_obj(mp_print_t *print, mp_obj_t o) { mp_obj_print_helper(&pr, o, PRINT_REPR); mp_print_bytes(print, &obj_type, 1); mp_print_uint(print, vstr.len); - mp_print_bytes(print, (const byte*)vstr.buf, vstr.len); + mp_print_bytes(print, (const byte *)vstr.buf, vstr.len); vstr_clear(&vstr); } } @@ -369,7 +371,7 @@ STATIC void save_raw_code(mp_print_t *print, mp_raw_code_t *rc) { save_obj(print, (mp_obj_t)*const_table++); } for (uint i = 0; i < rc->data.u_byte.n_raw_code; ++i) { - save_raw_code(print, (mp_raw_code_t*)(uintptr_t)*const_table++); + save_raw_code(print, (mp_raw_code_t *)(uintptr_t)*const_table++); } } @@ -380,11 +382,11 @@ void mp_raw_code_save(mp_raw_code_t *rc, mp_print_t *print) { // byte feature flags // byte number of bits in a small int byte header[4] = {'M', MPY_VERSION, MPY_FEATURE_FLAGS_DYNAMIC, - #if MICROPY_DYNAMIC_COMPILER - mp_dynamic_compiler.small_int_bits, - #else - mp_small_int_bits(), - #endif + #if MICROPY_DYNAMIC_COMPILER + mp_dynamic_compiler.small_int_bits, + #else + mp_small_int_bits(), + #endif }; mp_print_bytes(print, header, sizeof(header)); @@ -408,7 +410,7 @@ STATIC void fd_print_strn(void *env, const char *str, size_t len) { void mp_raw_code_save_file(mp_raw_code_t *rc, const char *filename) { int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644); - mp_print_t fd_print = {(void*)(intptr_t)fd, fd_print_strn}; + mp_print_t fd_print = {(void *)(intptr_t)fd, fd_print_strn}; mp_raw_code_save(rc, &fd_print); close(fd); } diff --git a/py/proto.c b/py/proto.c index e4da157f05..ad9684f3c5 100644 --- a/py/proto.c +++ b/py/proto.c @@ -31,8 +31,10 @@ #ifndef MICROPY_UNSAFE_PROTO const void *mp_proto_get(uint16_t name, mp_const_obj_t obj) { mp_obj_type_t *type = mp_obj_get_type(obj); - if (!type->protocol) return NULL; - uint16_t proto_name = *(const uint16_t*) type->protocol; + if (!type->protocol) { + return NULL; + } + uint16_t proto_name = *(const uint16_t *)type->protocol; if (proto_name == name) { return type->protocol; } diff --git a/py/proto.h b/py/proto.h index fadf1f8822..2b2439eae1 100644 --- a/py/proto.h +++ b/py/proto.h @@ -30,7 +30,9 @@ #ifdef MICROPY_UNSAFE_PROTO #define MP_PROTOCOL_HEAD /* NOTHING */ #define MP_PROTO_IMPLEMENT(name) /* NOTHING */ -static inline void *mp_proto_get(uint16_t name, mp_const_obj_type_t obj) { return mp_obj_get_type(obj)->protocol; } +static inline void *mp_proto_get(uint16_t name, mp_const_obj_type_t obj) { + return mp_obj_get_type(obj)->protocol; +} #else #define MP_PROTOCOL_HEAD \ uint16_t name; // The name of this protocol, a qstr diff --git a/py/pystack.c b/py/pystack.c index 0def75b109..c48437aa74 100644 --- a/py/pystack.c +++ b/py/pystack.c @@ -49,7 +49,7 @@ void *mp_pystack_alloc(size_t n_bytes) { void *ptr = MP_STATE_THREAD(pystack_cur); MP_STATE_THREAD(pystack_cur) += n_bytes; #if MP_PYSTACK_DEBUG - *(size_t*)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN) = n_bytes; + *(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN) = n_bytes; #endif return ptr; } diff --git a/py/pystack.h b/py/pystack.h index 3fbcdeeb8a..66ff2a6950 100644 --- a/py/pystack.h +++ b/py/pystack.h @@ -41,21 +41,21 @@ void *mp_pystack_alloc(size_t n_bytes); // pointer to the block that was allocated first and it and all subsequently // allocated blocks will be freed. static inline void mp_pystack_free(void *ptr) { - assert((uint8_t*)ptr >= MP_STATE_THREAD(pystack_start)); - assert((uint8_t*)ptr <= MP_STATE_THREAD(pystack_cur)); + assert((uint8_t *)ptr >= MP_STATE_THREAD(pystack_start)); + assert((uint8_t *)ptr <= MP_STATE_THREAD(pystack_cur)); #if MP_PYSTACK_DEBUG - size_t n_bytes_to_free = MP_STATE_THREAD(pystack_cur) - (uint8_t*)ptr; - size_t n_bytes = *(size_t*)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN); + size_t n_bytes_to_free = MP_STATE_THREAD(pystack_cur) - (uint8_t *)ptr; + size_t n_bytes = *(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN); while (n_bytes < n_bytes_to_free) { - n_bytes += *(size_t*)(MP_STATE_THREAD(pystack_cur) - n_bytes - MICROPY_PYSTACK_ALIGN); + n_bytes += *(size_t *)(MP_STATE_THREAD(pystack_cur) - n_bytes - MICROPY_PYSTACK_ALIGN); } if (n_bytes != n_bytes_to_free) { mp_printf(&mp_plat_print, "mp_pystack_free() failed: %u != %u\n", (uint)n_bytes_to_free, - (uint)*(size_t*)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN)); + (uint)*(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN)); assert(0); } #endif - MP_STATE_THREAD(pystack_cur) = (uint8_t*)ptr; + MP_STATE_THREAD(pystack_cur) = (uint8_t *)ptr; } static inline void mp_pystack_realloc(void *ptr, size_t n_bytes) { diff --git a/py/qstr.c b/py/qstr.c old mode 100755 new mode 100644 index c9ba298fb7..2ae65379c7 --- a/py/qstr.c +++ b/py/qstr.c @@ -104,13 +104,13 @@ const qstr_pool_t mp_qstr_const_pool = { 10, // set so that the first dynamically allocated pool is twice this size; must be <= the len (just below) MP_QSTRnumber_of, // corresponds to number of strings in array just below { -#ifndef NO_QSTR + #ifndef NO_QSTR #define QDEF(id, str) str, -#define TRANSLATION(id, length, compressed...) -#include "genhdr/qstrdefs.generated.h" +#define TRANSLATION(id, length, compressed ...) + #include "genhdr/qstrdefs.generated.h" #undef TRANSLATION #undef QDEF -#endif + #endif }, }; @@ -122,7 +122,7 @@ extern const qstr_pool_t MICROPY_QSTR_EXTRA_POOL; #endif void qstr_init(void) { - MP_STATE_VM(last_pool) = (qstr_pool_t*)&CONST_POOL; // we won't modify the const_pool since it has no allocated room left + MP_STATE_VM(last_pool) = (qstr_pool_t *)&CONST_POOL; // we won't modify the const_pool since it has no allocated room left MP_STATE_VM(qstr_last_chunk) = NULL; #if MICROPY_PY_THREAD @@ -151,7 +151,7 @@ STATIC qstr qstr_add(const byte *q_ptr) { if (new_pool_length > MICROPY_QSTR_POOL_MAX_ENTRIES) { new_pool_length = MICROPY_QSTR_POOL_MAX_ENTRIES; } - qstr_pool_t *pool = m_new_ll_obj_var_maybe(qstr_pool_t, const char*, new_pool_length); + qstr_pool_t *pool = m_new_ll_obj_var_maybe(qstr_pool_t, const char *, new_pool_length); if (pool == NULL) { QSTR_EXIT(); m_malloc_fail(new_pool_length); @@ -173,7 +173,7 @@ STATIC qstr qstr_add(const byte *q_ptr) { qstr qstr_find_strn(const char *str, size_t str_len) { // work out hash of str - mp_uint_t str_hash = qstr_compute_hash((const byte*)str, str_len); + mp_uint_t str_hash = qstr_compute_hash((const byte *)str, str_len); // search pools for the data for (qstr_pool_t *pool = MP_STATE_VM(last_pool); pool != NULL; pool = pool->prev) { @@ -240,7 +240,7 @@ qstr qstr_from_strn(const char *str, size_t len) { MP_STATE_VM(qstr_last_used) += n_bytes; // store the interned strings' data - mp_uint_t hash = qstr_compute_hash((const byte*)str, len); + mp_uint_t hash = qstr_compute_hash((const byte *)str, len); Q_SET_HASH(q_ptr, hash); Q_SET_LENGTH(q_ptr, len); memcpy(q_ptr + MICROPY_QSTR_BYTES_IN_HASH + MICROPY_QSTR_BYTES_IN_LEN, str, len); @@ -262,7 +262,7 @@ size_t qstr_len(qstr q) { const char *qstr_str(qstr q) { const byte *qd = find_qstr(q); - return (const char*)Q_GET_DATA(qd); + return (const char *)Q_GET_DATA(qd); } const byte *qstr_data(qstr q, size_t *len) { diff --git a/py/qstr.h b/py/qstr.h index 070a3cd4f8..c86e74324c 100644 --- a/py/qstr.h +++ b/py/qstr.h @@ -37,11 +37,11 @@ // first entry in enum will be MP_QSTR_NULL=0, which indicates invalid/no qstr enum { -#ifndef NO_QSTR + #ifndef NO_QSTR #define QENUM(id) id, -#include "genhdr/qstrdefs.enum.h" + #include "genhdr/qstrdefs.enum.h" #undef QENUM -#endif + #endif MP_QSTRnumber_of, // no underscore so it can't clash with any of the above }; diff --git a/py/qstrdefs.h b/py/qstrdefs.h index b682671970..04ee03d737 100644 --- a/py/qstrdefs.h +++ b/py/qstrdefs.h @@ -24,6 +24,8 @@ * THE SOFTWARE. */ +// *FORMAT-OFF* + #include "py/mpconfig.h" // All the qstr definitions in this file are available as constants. diff --git a/py/reader.c b/py/reader.c index 1b0bbf094a..dfd5daf63e 100644 --- a/py/reader.c +++ b/py/reader.c @@ -39,7 +39,7 @@ typedef struct _mp_reader_mem_t { } mp_reader_mem_t; STATIC mp_uint_t mp_reader_mem_readbyte(void *data) { - mp_reader_mem_t *reader = (mp_reader_mem_t*)data; + mp_reader_mem_t *reader = (mp_reader_mem_t *)data; if (reader->cur < reader->end) { return *reader->cur++; } else { @@ -48,9 +48,9 @@ STATIC mp_uint_t mp_reader_mem_readbyte(void *data) { } STATIC void mp_reader_mem_close(void *data) { - mp_reader_mem_t *reader = (mp_reader_mem_t*)data; + mp_reader_mem_t *reader = (mp_reader_mem_t *)data; if (reader->free_len > 0) { - m_del(char, (char*)reader->beg, reader->free_len); + m_del(char, (char *)reader->beg, reader->free_len); } m_del_obj(mp_reader_mem_t, reader); } @@ -81,7 +81,7 @@ typedef struct _mp_reader_posix_t { } mp_reader_posix_t; STATIC mp_uint_t mp_reader_posix_readbyte(void *data) { - mp_reader_posix_t *reader = (mp_reader_posix_t*)data; + mp_reader_posix_t *reader = (mp_reader_posix_t *)data; if (reader->pos >= reader->len) { if (reader->len == 0) { return MP_READER_EOF; @@ -99,7 +99,7 @@ STATIC mp_uint_t mp_reader_posix_readbyte(void *data) { } STATIC void mp_reader_posix_close(void *data) { - mp_reader_posix_t *reader = (mp_reader_posix_t*)data; + mp_reader_posix_t *reader = (mp_reader_posix_t *)data; if (reader->close_fd) { close(reader->fd); } diff --git a/py/reload.c b/py/reload.c index f9f8a590a6..9f20004690 100644 --- a/py/reload.c +++ b/py/reload.c @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) @@ -23,10 +23,10 @@ void mp_raise_reload_exception(void) { MP_STATE_VM(mp_pending_exception) = MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_reload_exception)); -#if MICROPY_ENABLE_SCHEDULER + #if MICROPY_ENABLE_SCHEDULER if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) { MP_STATE_VM(sched_state) = MP_SCHED_PENDING; } -#endif + #endif } diff --git a/py/reload.h b/py/reload.h index 3e8928a32c..8e68ea3253 100644 --- a/py/reload.h +++ b/py/reload.h @@ -1,4 +1,4 @@ - /* +/* * This file is part of the MicroPython project, http://micropython.org/ * * The MIT License (MIT) @@ -23,4 +23,4 @@ void mp_raise_reload_exception(void); -#endif //CIRCUITPYTHON_RELOAD_H +#endif // CIRCUITPYTHON_RELOAD_H diff --git a/py/repl.c b/py/repl.c index 785c0fb538..3ef1401522 100644 --- a/py/repl.c +++ b/py/repl.c @@ -50,7 +50,7 @@ bool mp_repl_continue_with_input(const char *input) { // check if input starts with a certain keyword bool starts_with_compound_keyword = - input[0] == '@' + input[0] == '@' || str_startswith_word(input, "if") || str_startswith_word(input, "while") || str_startswith_word(input, "for") @@ -61,7 +61,7 @@ bool mp_repl_continue_with_input(const char *input) { #if MICROPY_PY_ASYNC_AWAIT || str_startswith_word(input, "async") #endif - ; + ; // check for unmatched open bracket, quote or escape quote #define Q_NONE (0) @@ -95,13 +95,26 @@ bool mp_repl_continue_with_input(const char *input) { } } else if (in_quote == Q_NONE) { switch (*i) { - case '(': n_paren += 1; break; - case ')': n_paren -= 1; break; - case '[': n_brack += 1; break; - case ']': n_brack -= 1; break; - case '{': n_brace += 1; break; - case '}': n_brace -= 1; break; - default: break; + case '(': + n_paren += 1; + break; + case ')': + n_paren -= 1; + break; + case '[': + n_brack += 1; + break; + case ']': + n_brack -= 1; + break; + case '{': + n_brace += 1; + break; + case '}': + n_brace -= 1; + break; + default: + break; } } } @@ -183,7 +196,7 @@ size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print qstr q_first = 0, q_last = 0; for (qstr q = MP_QSTR_ + 1; q < nqstr; ++q) { size_t d_len; - const char *d_str = (const char*)qstr_data(q, &d_len); + const char *d_str = (const char *)qstr_data(q, &d_len); if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) { mp_load_method_protected(obj, q, dest, true); if (dest[0] != MP_OBJ_NULL) { @@ -246,7 +259,7 @@ size_t mp_repl_autocomplete(const char *str, size_t len, const mp_print_t *print int line_len = MAX_LINE_LEN; // force a newline for first word for (qstr q = q_first; q <= q_last; ++q) { size_t d_len; - const char *d_str = (const char*)qstr_data(q, &d_len); + const char *d_str = (const char *)qstr_data(q, &d_len); if (s_len <= d_len && strncmp(s_start, d_str, s_len) == 0) { mp_load_method_protected(obj, q, dest, true); if (dest[0] != MP_OBJ_NULL) { diff --git a/py/ringbuf.c b/py/ringbuf.c index c19f1d44bc..f4be5ca3fb 100644 --- a/py/ringbuf.c +++ b/py/ringbuf.c @@ -32,7 +32,7 @@ // handles empty and full statuses. bool ringbuf_alloc(ringbuf_t *r, size_t capacity, bool long_lived) { r->buf = gc_alloc(capacity + 1, false, long_lived); - r->size = capacity + 1; + r->size = capacity + 1; r->iget = r->iput = 0; return r->buf != NULL; } @@ -89,10 +89,9 @@ size_t ringbuf_num_filled(ringbuf_t *r) { // If the ring buffer fills up, not all bytes will be written. // Returns how many bytes were successfully written. -size_t ringbuf_put_n(ringbuf_t* r, uint8_t* buf, size_t bufsize) -{ - for(size_t i=0; i < bufsize; i++) { - if ( ringbuf_put(r, buf[i]) < 0 ) { +size_t ringbuf_put_n(ringbuf_t *r, uint8_t *buf, size_t bufsize) { + for (size_t i = 0; i < bufsize; i++) { + if (ringbuf_put(r, buf[i]) < 0) { // If ringbuf is full, give up and return how many bytes // we wrote so far. return i; @@ -102,9 +101,8 @@ size_t ringbuf_put_n(ringbuf_t* r, uint8_t* buf, size_t bufsize) } // Returns how many bytes were fetched. -size_t ringbuf_get_n(ringbuf_t* r, uint8_t* buf, size_t bufsize) -{ - for(size_t i=0; i < bufsize; i++) { +size_t ringbuf_get_n(ringbuf_t *r, uint8_t *buf, size_t bufsize) { + for (size_t i = 0; i < bufsize; i++) { int b = ringbuf_get(r); if (b < 0) { return i; diff --git a/py/ringbuf.h b/py/ringbuf.h index 476bd428f9..88d88d86e9 100644 --- a/py/ringbuf.h +++ b/py/ringbuf.h @@ -52,7 +52,7 @@ int ringbuf_put(ringbuf_t *r, uint8_t v); void ringbuf_clear(ringbuf_t *r); size_t ringbuf_num_empty(ringbuf_t *r); size_t ringbuf_num_filled(ringbuf_t *r); -size_t ringbuf_put_n(ringbuf_t* r, uint8_t* buf, size_t bufsize); -size_t ringbuf_get_n(ringbuf_t* r, uint8_t* buf, size_t bufsize); +size_t ringbuf_put_n(ringbuf_t *r, uint8_t *buf, size_t bufsize); +size_t ringbuf_get_n(ringbuf_t *r, uint8_t *buf, size_t bufsize); #endif // MICROPY_INCLUDED_PY_RINGBUF_H diff --git a/py/runtime.c b/py/runtime.c index a3acb954a6..28ecddd786 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -60,7 +60,7 @@ const mp_obj_module_t mp_module___main__ = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&MP_STATE_VM(dict_main), + .globals = (mp_obj_dict_t *)&MP_STATE_VM(dict_main), }; void mp_init(void) { @@ -73,9 +73,9 @@ void mp_init(void) { MP_STATE_VM(sched_sp) = 0; #endif -#if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF + #if MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF mp_init_emergency_exception_buf(); -#endif + #endif #if MICROPY_KBD_EXCEPTION // initialise the exception object for raising KeyboardInterrupt @@ -83,19 +83,19 @@ void mp_init(void) { MP_STATE_VM(mp_kbd_exception).traceback_alloc = 0; MP_STATE_VM(mp_kbd_exception).traceback_len = 0; MP_STATE_VM(mp_kbd_exception).traceback_data = NULL; - MP_STATE_VM(mp_kbd_exception).args = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj; + MP_STATE_VM(mp_kbd_exception).args = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj; #endif MP_STATE_VM(mp_reload_exception).base.type = &mp_type_ReloadException; MP_STATE_VM(mp_reload_exception).traceback_alloc = 0; MP_STATE_VM(mp_reload_exception).traceback_len = 0; MP_STATE_VM(mp_reload_exception).traceback_data = NULL; - MP_STATE_VM(mp_reload_exception).args = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj; + MP_STATE_VM(mp_reload_exception).args = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj; // call port specific initialization if any -#ifdef MICROPY_PORT_INIT_FUNC + #ifdef MICROPY_PORT_INIT_FUNC MICROPY_PORT_INIT_FUNC; -#endif + #endif #if MICROPY_ENABLE_COMPILER // optimization disabled by default @@ -128,7 +128,7 @@ void mp_init(void) { #ifdef MICROPY_FSUSERMOUNT // zero out the pointers to the user-mounted devices memset(MP_STATE_VM(fs_user_mount) + MICROPY_FATFS_NUM_PERSISTENT, 0, - sizeof(MP_STATE_VM(fs_user_mount)) - MICROPY_FATFS_NUM_PERSISTENT); + sizeof(MP_STATE_VM(fs_user_mount)) - MICROPY_FATFS_NUM_PERSISTENT); #endif #if MICROPY_PY_THREAD_GIL @@ -139,13 +139,13 @@ void mp_init(void) { } void mp_deinit(void) { - //mp_obj_dict_free(&dict_main); - //mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map)); + // mp_obj_dict_free(&dict_main); + // mp_map_deinit(&MP_STATE_VM(mp_loaded_modules_map)); // call port specific deinitialization if any -#ifdef MICROPY_PORT_INIT_FUNC + #ifdef MICROPY_PORT_INIT_FUNC MICROPY_PORT_DEINIT_FUNC; -#endif + #endif } mp_obj_t mp_load_name(qstr qst) { @@ -175,13 +175,13 @@ mp_obj_t mp_load_global(qstr qst) { } } #endif - elem = mp_map_lookup((mp_map_t*)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); + elem = mp_map_lookup((mp_map_t *)&mp_module_builtins_globals.map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); if (elem == NULL) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_msg(&mp_type_NameError, translate("name not defined")); + mp_raise_msg(&mp_type_NameError, translate("name not defined")); #else - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError, - translate("name '%q' is not defined"), qst)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_NameError, + translate("name '%q' is not defined"), qst)); #endif } } @@ -276,11 +276,11 @@ mp_obj_t mp_unary_op(mp_unary_op_t op, mp_obj_t arg) { } } #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("unsupported type for operator")); + mp_raise_TypeError(translate("unsupported type for operator")); #else - mp_raise_TypeError_varg( - translate("unsupported type for %q: '%q'"), - mp_unary_op_method_name[op], mp_obj_get_type_qstr(arg)); + mp_raise_TypeError_varg( + translate("unsupported type for %q: '%q'"), + mp_unary_op_method_name[op], mp_obj_get_type_qstr(arg)); #endif } } @@ -359,11 +359,17 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r // << checked explicitly switch (op) { case MP_BINARY_OP_OR: - case MP_BINARY_OP_INPLACE_OR: lhs_val |= rhs_val; break; + case MP_BINARY_OP_INPLACE_OR: + lhs_val |= rhs_val; + break; case MP_BINARY_OP_XOR: - case MP_BINARY_OP_INPLACE_XOR: lhs_val ^= rhs_val; break; + case MP_BINARY_OP_INPLACE_XOR: + lhs_val ^= rhs_val; + break; case MP_BINARY_OP_AND: - case MP_BINARY_OP_INPLACE_AND: lhs_val &= rhs_val; break; + case MP_BINARY_OP_INPLACE_AND: + lhs_val &= rhs_val; + break; case MP_BINARY_OP_LSHIFT: case MP_BINARY_OP_INPLACE_LSHIFT: { if (rhs_val < 0) { @@ -395,9 +401,13 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r } break; case MP_BINARY_OP_ADD: - case MP_BINARY_OP_INPLACE_ADD: lhs_val += rhs_val; break; + case MP_BINARY_OP_INPLACE_ADD: + lhs_val += rhs_val; + break; case MP_BINARY_OP_SUBTRACT: - case MP_BINARY_OP_INPLACE_SUBTRACT: lhs_val -= rhs_val; break; + case MP_BINARY_OP_INPLACE_SUBTRACT: + lhs_val -= rhs_val; + break; case MP_BINARY_OP_MULTIPLY: case MP_BINARY_OP_INPLACE_MULTIPLY: { @@ -498,10 +508,14 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r return MP_OBJ_FROM_PTR(tuple); } - case MP_BINARY_OP_LESS: return mp_obj_new_bool(lhs_val < rhs_val); - case MP_BINARY_OP_MORE: return mp_obj_new_bool(lhs_val > rhs_val); - case MP_BINARY_OP_LESS_EQUAL: return mp_obj_new_bool(lhs_val <= rhs_val); - case MP_BINARY_OP_MORE_EQUAL: return mp_obj_new_bool(lhs_val >= rhs_val); + case MP_BINARY_OP_LESS: + return mp_obj_new_bool(lhs_val < rhs_val); + case MP_BINARY_OP_MORE: + return mp_obj_new_bool(lhs_val > rhs_val); + case MP_BINARY_OP_LESS_EQUAL: + return mp_obj_new_bool(lhs_val <= rhs_val); + case MP_BINARY_OP_MORE_EQUAL: + return mp_obj_new_bool(lhs_val >= rhs_val); default: goto unsupported_op; @@ -512,7 +526,7 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r } else { return mp_obj_new_int(lhs_val); } -#if MICROPY_PY_BUILTINS_FLOAT + #if MICROPY_PY_BUILTINS_FLOAT } else if (mp_obj_is_float(rhs)) { mp_obj_t res = mp_obj_float_binary_op(op, lhs_val, rhs); if (res == MP_OBJ_NULL) { @@ -520,7 +534,7 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r } else { return res; } -#if MICROPY_PY_BUILTINS_COMPLEX + #if MICROPY_PY_BUILTINS_COMPLEX } else if (MP_OBJ_IS_TYPE(rhs, &mp_type_complex)) { mp_obj_t res = mp_obj_complex_binary_op(op, lhs_val, 0, rhs); if (res == MP_OBJ_NULL) { @@ -528,8 +542,8 @@ mp_obj_t PLACE_IN_ITCM(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t r } else { return res; } -#endif -#endif + #endif + #endif } } @@ -552,7 +566,7 @@ generic_binary_op: } } -#if MICROPY_PY_REVERSE_SPECIAL_METHODS + #if MICROPY_PY_REVERSE_SPECIAL_METHODS if (op >= MP_BINARY_OP_OR && op <= MP_BINARY_OP_REVERSE_POWER) { mp_obj_t t = rhs; rhs = lhs; @@ -565,7 +579,7 @@ generic_binary_op: // Convert __rop__ back to __op__ for error message op -= MP_BINARY_OP_REVERSE_OR - MP_BINARY_OP_OR; } -#endif + #endif if (op == MP_BINARY_OP_CONTAINS) { // If type didn't support containment then explicitly walk the iterator. @@ -583,11 +597,11 @@ generic_binary_op: unsupported_op: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("unsupported type for operator")); + mp_raise_TypeError(translate("unsupported type for operator")); #else - mp_raise_TypeError_varg( - translate("unsupported types for %q: '%q', '%q'"), - mp_binary_op_method_name[op], mp_obj_get_type_qstr(lhs), mp_obj_get_type_qstr(rhs)); + mp_raise_TypeError_varg( + translate("unsupported types for %q: '%q', '%q'"), + mp_binary_op_method_name[op], mp_obj_get_type_qstr(lhs), mp_obj_get_type_qstr(rhs)); #endif zero_division: @@ -625,9 +639,9 @@ mp_obj_t mp_call_function_n_kw(mp_obj_t fun_in, size_t n_args, size_t n_kw, cons } #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object not callable")); + mp_raise_TypeError(translate("object not callable")); #else - mp_raise_TypeError_varg(translate("'%q' object is not callable"), mp_obj_get_type_qstr(fun_in)); + mp_raise_TypeError_varg(translate("'%q' object is not callable"), mp_obj_get_type_qstr(fun_in)); #endif } @@ -853,17 +867,17 @@ void mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) { too_short: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_ValueError(translate("wrong number of values to unpack")); + mp_raise_ValueError(translate("wrong number of values to unpack")); #else - mp_raise_ValueError_varg(translate("need more than %d values to unpack"), - (int)seq_len); + mp_raise_ValueError_varg(translate("need more than %d values to unpack"), + (int)seq_len); #endif too_long: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_ValueError(translate("wrong number of values to unpack")); + mp_raise_ValueError(translate("wrong number of values to unpack")); #else - mp_raise_ValueError_varg(translate("too many values to unpack (expected %d)"), - (int)num); + mp_raise_ValueError_varg(translate("too many values to unpack (expected %d)"), + (int)num); #endif } @@ -917,10 +931,10 @@ void mp_unpack_ex(mp_obj_t seq_in, size_t num_in, mp_obj_t *items) { too_short: #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_ValueError(translate("wrong number of values to unpack")); + mp_raise_ValueError(translate("wrong number of values to unpack")); #else - mp_raise_ValueError_varg(translate("need more than %d values to unpack"), - (int)seq_len); + mp_raise_ValueError_varg(translate("need more than %d values to unpack"), + (int)seq_len); #endif } @@ -989,7 +1003,7 @@ STATIC mp_obj_t mp_obj_new_checked_fun(const mp_obj_type_t *type, mp_obj_t fun) void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t member, mp_obj_t *dest) { if (MP_OBJ_IS_TYPE(member, &mp_type_staticmethod)) { // return just the function - dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun; + dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun; } else if (MP_OBJ_IS_TYPE(member, &mp_type_classmethod)) { // return a bound method, with self being the type of this object // this type should be the type of the original instance, not the base @@ -997,18 +1011,18 @@ void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t if (self != MP_OBJ_NULL) { type = mp_obj_get_type(self); } - dest[0] = ((mp_obj_static_class_method_t*)MP_OBJ_TO_PTR(member))->fun; + dest[0] = ((mp_obj_static_class_method_t *)MP_OBJ_TO_PTR(member))->fun; dest[1] = MP_OBJ_FROM_PTR(type); } else if (MP_OBJ_IS_TYPE(member, &mp_type_type)) { // Don't try to bind types (even though they're callable) dest[0] = member; } else if (MP_OBJ_IS_FUN(member) - || (MP_OBJ_IS_OBJ(member) - && (((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure - || ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) { + || (MP_OBJ_IS_OBJ(member) + && (((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_closure + || ((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type->name == MP_QSTR_generator))) { // only functions, closures and generators objects can be bound to self #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG - const mp_obj_type_t *m_type = ((mp_obj_base_t*)MP_OBJ_TO_PTR(member))->type; + const mp_obj_type_t *m_type = ((mp_obj_base_t *)MP_OBJ_TO_PTR(member))->type; if (self == MP_OBJ_NULL && (m_type == &mp_type_fun_builtin_0 || m_type == &mp_type_fun_builtin_1 @@ -1025,7 +1039,7 @@ void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t dest[0] = member; dest[1] = self; } - #if MICROPY_PY_BUILTINS_PROPERTY + #if MICROPY_PY_BUILTINS_PROPERTY // If self is MP_OBJ_NULL, we looking at the class itself, not an instance. } else if (MP_OBJ_IS_TYPE(member, &mp_type_property) && mp_obj_is_native_type(type) && self != MP_OBJ_NULL) { // object member is a property; delegate the load to the property @@ -1041,7 +1055,7 @@ void mp_convert_member_lookup(mp_obj_t self, const mp_obj_type_t *type, mp_obj_t } else { dest[0] = mp_call_function_n_kw(proxy[0], 1, 0, &self); } - #endif + #endif } else { // class member is a value, so just return that value dest[0] = member; @@ -1061,11 +1075,11 @@ void mp_load_method_maybe(mp_obj_t obj, qstr attr, mp_obj_t *dest) { // look for built-in names if (0) { -#if MICROPY_CPYTHON_COMPAT + #if MICROPY_CPYTHON_COMPAT } else if (attr == MP_QSTR___class__) { // a.__class__ is equivalent to type(a) dest[0] = MP_OBJ_FROM_PTR(type); -#endif + #endif } else if (attr == MP_QSTR___next__ && type->iternext != NULL) { dest[0] = MP_OBJ_FROM_PTR(&mp_builtin_next_obj); @@ -1095,22 +1109,22 @@ void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) { if (dest[0] == MP_OBJ_NULL) { // no attribute/method called attr #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_AttributeError(translate("no such attribute")); + mp_raise_AttributeError(translate("no such attribute")); #elif MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_DETAILED - // following CPython, we give a more detailed error message for type objects - if (MP_OBJ_IS_TYPE(base, &mp_type_type)) { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, - translate("type object '%q' has no attribute '%q'"), - ((mp_obj_type_t*)MP_OBJ_TO_PTR(base))->name, attr)); - } else { - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, - translate("'%q' object has no attribute '%q'"), - mp_obj_get_type_qstr(base), attr)); - } - #else + // following CPython, we give a more detailed error message for type objects + if (MP_OBJ_IS_TYPE(base, &mp_type_type)) { + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, + translate("type object '%q' has no attribute '%q'"), + ((mp_obj_type_t *)MP_OBJ_TO_PTR(base))->name, attr)); + } else { nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, translate("'%q' object has no attribute '%q'"), mp_obj_get_type_qstr(base), attr)); + } + #else + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, + translate("'%q' object has no attribute '%q'"), + mp_obj_get_type_qstr(base), attr)); #endif } } @@ -1123,7 +1137,7 @@ void mp_load_method_protected(mp_obj_t obj, qstr attr, mp_obj_t *dest, bool catc nlr_pop(); } else { if (!catch_all_exc - && !mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), + && !mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_AttributeError))) { // Re-raise the exception nlr_raise(MP_OBJ_FROM_PTR(nlr.ret_val)); @@ -1173,11 +1187,11 @@ void mp_store_attr(mp_obj_t base, qstr attr, mp_obj_t value) { #endif } #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_AttributeError(translate("no such attribute")); + mp_raise_AttributeError(translate("no such attribute")); #else - nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, - translate("'%q' object cannot assign attribute '%q'"), - mp_obj_get_type_qstr(base), attr)); + nlr_raise(mp_obj_new_exception_msg_varg(&mp_type_AttributeError, + translate("'%q' object cannot assign attribute '%q'"), + mp_obj_get_type_qstr(base), attr)); #endif } @@ -1214,10 +1228,10 @@ mp_obj_t mp_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) { // object not iterable #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object not iterable")); + mp_raise_TypeError(translate("object not iterable")); #else - mp_raise_TypeError_varg( - translate("'%q' object is not iterable"), mp_obj_get_type_qstr(o_in)); + mp_raise_TypeError_varg( + translate("'%q' object is not iterable"), mp_obj_get_type_qstr(o_in)); #endif } @@ -1236,10 +1250,10 @@ mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) { return mp_call_method_n_kw(0, 0, dest); } else { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object not an iterator")); + mp_raise_TypeError(translate("object not an iterator")); #else - mp_raise_TypeError_varg(translate("'%q' object is not an iterator"), - mp_obj_get_type_qstr(o_in)); + mp_raise_TypeError_varg(translate("'%q' object is not an iterator"), + mp_obj_get_type_qstr(o_in)); #endif } } @@ -1264,7 +1278,7 @@ mp_obj_t mp_iternext(mp_obj_t o_in) { nlr_pop(); return ret; } else { - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { return MP_OBJ_STOP_ITERATION; } else { nlr_jump(nlr.ret_val); @@ -1272,10 +1286,10 @@ mp_obj_t mp_iternext(mp_obj_t o_in) { } } else { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_TERSE - mp_raise_TypeError(translate("object not an iterator")); + mp_raise_TypeError(translate("object not an iterator")); #else - mp_raise_TypeError_varg(translate("'%q' object is not an iterator"), - mp_obj_get_type_qstr(o_in)); + mp_raise_TypeError_varg(translate("'%q' object is not an iterator"), + mp_obj_get_type_qstr(o_in)); #endif } } @@ -1405,7 +1419,7 @@ mp_obj_t mp_import_from(mp_obj_t module, qstr name) { if (dest[1] != MP_OBJ_NULL) { // Hopefully we can't import bound method from an object -import_error: + import_error: mp_raise_msg_varg(&mp_type_ImportError, translate("cannot import name %q"), name); } diff --git a/py/runtime.h b/py/runtime.h index 5e8fda35c1..74307d87cb 100644 --- a/py/runtime.h +++ b/py/runtime.h @@ -72,7 +72,9 @@ void mp_handle_pending_tail(mp_uint_t atomic_state); #if MICROPY_ENABLE_SCHEDULER void mp_sched_lock(void); void mp_sched_unlock(void); -static inline unsigned int mp_sched_num_pending(void) { return MP_STATE_VM(sched_sp); } +static inline unsigned int mp_sched_num_pending(void) { + return MP_STATE_VM(sched_sp); +} bool mp_sched_schedule(mp_obj_t function, mp_obj_t arg); #endif @@ -86,10 +88,18 @@ void mp_arg_parse_all_kw_array(size_t n_pos, size_t n_kw, const mp_obj_t *args, NORETURN void mp_arg_error_terse_mismatch(void); NORETURN void mp_arg_error_unimpl_kw(void); -static inline mp_obj_dict_t *PLACE_IN_ITCM(mp_locals_get)(void) { return MP_STATE_THREAD(dict_locals); } -static inline void PLACE_IN_ITCM(mp_locals_set)(mp_obj_dict_t *d) { MP_STATE_THREAD(dict_locals) = d; } -static inline mp_obj_dict_t *PLACE_IN_ITCM(mp_globals_get)(void) { return MP_STATE_THREAD(dict_globals); } -static inline void PLACE_IN_ITCM(mp_globals_set)(mp_obj_dict_t *d) { MP_STATE_THREAD(dict_globals) = d; } +static inline mp_obj_dict_t *PLACE_IN_ITCM(mp_locals_get)(void) { + return MP_STATE_THREAD(dict_locals); +} +static inline void PLACE_IN_ITCM(mp_locals_set)(mp_obj_dict_t * d) { + MP_STATE_THREAD(dict_locals) = d; +} +static inline mp_obj_dict_t *PLACE_IN_ITCM(mp_globals_get)(void) { + return MP_STATE_THREAD(dict_globals); +} +static inline void PLACE_IN_ITCM(mp_globals_set)(mp_obj_dict_t * d) { + MP_STATE_THREAD(dict_globals) = d; +} mp_obj_t mp_load_name(qstr qst); mp_obj_t mp_load_global(qstr qst); diff --git a/py/runtime0.h b/py/runtime0.h index fb35c8a9f4..566cec566a 100644 --- a/py/runtime0.h +++ b/py/runtime0.h @@ -112,7 +112,7 @@ typedef enum { MP_BINARY_OP_NUM_BYTECODE, // MP_BINARY_OP_REVERSE_* must follow immediately after MP_BINARY_OP_* -#if MICROPY_PY_REVERSE_SPECIAL_METHODS + #if MICROPY_PY_REVERSE_SPECIAL_METHODS MP_BINARY_OP_REVERSE_OR = MP_BINARY_OP_NUM_BYTECODE, MP_BINARY_OP_REVERSE_XOR, MP_BINARY_OP_REVERSE_AND, @@ -125,13 +125,13 @@ typedef enum { MP_BINARY_OP_REVERSE_TRUE_DIVIDE, MP_BINARY_OP_REVERSE_MODULO, MP_BINARY_OP_REVERSE_POWER, -#endif + #endif // This is not emitted by the compiler but is supported by the runtime MP_BINARY_OP_DIVMOD - #if !MICROPY_PY_REVERSE_SPECIAL_METHODS + #if !MICROPY_PY_REVERSE_SPECIAL_METHODS = MP_BINARY_OP_NUM_BYTECODE - #endif + #endif , // The runtime will convert MP_BINARY_OP_IN to this operator with swapped args. @@ -166,10 +166,10 @@ typedef enum { MP_F_LIST_APPEND, MP_F_BUILD_MAP, MP_F_STORE_MAP, -#if MICROPY_PY_BUILTINS_SET + #if MICROPY_PY_BUILTINS_SET MP_F_STORE_SET, MP_F_BUILD_SET, -#endif + #endif MP_F_MAKE_FUNCTION_FROM_RAW_CODE, MP_F_NATIVE_CALL_FUNCTION_N_KW, MP_F_CALL_METHOD_N_KW, @@ -182,9 +182,9 @@ typedef enum { MP_F_IMPORT_NAME, MP_F_IMPORT_FROM, MP_F_IMPORT_ALL, -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE MP_F_NEW_SLICE, -#endif + #endif MP_F_UNPACK_SEQUENCE, MP_F_UNPACK_EX, MP_F_DELETE_NAME, diff --git a/py/scope.c b/py/scope.c index 98f39d4c6d..4adf09afc4 100644 --- a/py/scope.c +++ b/py/scope.c @@ -47,7 +47,7 @@ scope_t *scope_new(scope_kind_t kind, mp_parse_node_t pn, qstr source_file, mp_u scope->source_file = source_file; if (kind == SCOPE_FUNCTION || kind == SCOPE_CLASS) { assert(MP_PARSE_NODE_IS_STRUCT(pn)); - scope->simple_name = MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t*)pn)->nodes[0]); + scope->simple_name = MP_PARSE_NODE_LEAF_ARG(((mp_parse_node_struct_t *)pn)->nodes[0]); } else { scope->simple_name = scope_simple_name_table[kind]; } diff --git a/py/sequence.c b/py/sequence.c index e6421fde5e..2fcd840171 100644 --- a/py/sequence.c +++ b/py/sequence.c @@ -54,7 +54,7 @@ void mp_seq_multiply(const void *items, size_t item_sz, size_t len, size_t times for (size_t i = 0; i < times; i++) { size_t copy_sz = item_sz * len; memcpy(dest, items, copy_sz); - dest = (char*)dest + copy_sz; + dest = (char *)dest + copy_sz; } } @@ -169,7 +169,7 @@ bool mp_seq_cmp_bytes(mp_uint_t op, const byte *data1, size_t len1, const byte * // Let's deal only with > & >= if (op == MP_BINARY_OP_LESS || op == MP_BINARY_OP_LESS_EQUAL) { - SWAP(const byte*, data1, data2); + SWAP(const byte *, data1, data2); SWAP(size_t, len1, len2); if (op == MP_BINARY_OP_LESS) { op = MP_BINARY_OP_MORE; @@ -236,7 +236,7 @@ bool mp_seq_cmp_objs(mp_uint_t op, const mp_obj_t *items1, size_t len1, const mp } // Otherwise, application of relation op gives the answer - return (mp_binary_op(op, items1[i], items2[i]) == mp_const_true); + return mp_binary_op(op, items1[i], items2[i]) == mp_const_true; } // If we had tie in the last element... @@ -281,9 +281,9 @@ mp_obj_t mp_seq_index_obj(const mp_obj_t *items, size_t len, size_t n_args, cons mp_obj_t mp_seq_count_obj(const mp_obj_t *items, size_t len, mp_obj_t value) { size_t count = 0; for (size_t i = 0; i < len; i++) { - if (mp_obj_equal(items[i], value)) { - count++; - } + if (mp_obj_equal(items[i], value)) { + count++; + } } // Common sense says this cannot overflow small int diff --git a/py/showbc.c b/py/showbc.c index 5a8e660fc4..a94b2b3a57 100644 --- a/py/showbc.c +++ b/py/showbc.c @@ -36,10 +36,10 @@ #define printf(...) mp_printf(&mp_plat_print, __VA_ARGS__) #define DECODE_UINT { \ - unum = 0; \ - do { \ - unum = (unum << 7) + (*ip & 0x7f); \ - } while ((*ip++ & 0x80) != 0); \ + unum = 0; \ + do { \ + unum = (unum << 7) + (*ip & 0x7f); \ + } while ((*ip++ & 0x80) != 0); \ } #define DECODE_ULABEL do { unum = (ip[0] | (ip[1] << 8)); ip += 2; } while (0) #define DECODE_SLABEL do { unum = (ip[0] | (ip[1] << 8)) - 0x8000; ip += 2; } while (0) @@ -59,20 +59,20 @@ #else #define DECODE_QSTR { \ - qst = 0; \ - do { \ - qst = (qst << 7) + (*ip & 0x7f); \ - } while ((*ip++ & 0x80) != 0); \ + qst = 0; \ + do { \ + qst = (qst << 7) + (*ip & 0x7f); \ + } while ((*ip++ & 0x80) != 0); \ } #define DECODE_PTR do { \ - ip = (byte*)MP_ALIGN(ip, sizeof(void*)); \ - unum = (uintptr_t)*(void**)ip; \ - ip += sizeof(void*); \ + ip = (byte *)MP_ALIGN(ip, sizeof(void *)); \ + unum = (uintptr_t)*(void **)ip; \ + ip += sizeof(void *); \ } while (0) #define DECODE_OBJ do { \ - ip = (byte*)MP_ALIGN(ip, sizeof(mp_obj_t)); \ - unum = (mp_uint_t)*(mp_obj_t*)ip; \ - ip += sizeof(mp_obj_t); \ + ip = (byte *)MP_ALIGN(ip, sizeof(mp_obj_t)); \ + unum = (mp_uint_t)*(mp_obj_t *)ip; \ + ip += sizeof(mp_obj_t); \ } while (0) #endif @@ -143,7 +143,7 @@ void mp_bytecode_print(const void *descr, const byte *ip, mp_uint_t len, const m mp_int_t bc = bytecode_start - ip; mp_uint_t source_line = 1; printf(" bc=" INT_FMT " line=" UINT_FMT "\n", bc, source_line); - for (const byte* ci = code_info; *ci;) { + for (const byte *ci = code_info; *ci;) { if ((ci[0] & 0x80) == 0) { // 0b0LLBBBBB encoding bc += ci[0] & 0x1f; @@ -435,12 +435,12 @@ const byte *mp_bytecode_print_str(const byte *ip) { printf("BUILD_SET " UINT_FMT, unum); break; -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE case MP_BC_BUILD_SLICE: DECODE_UINT; printf("BUILD_SLICE " UINT_FMT, unum); break; -#endif + #endif case MP_BC_STORE_COMP: DECODE_UINT; @@ -459,25 +459,25 @@ const byte *mp_bytecode_print_str(const byte *ip) { case MP_BC_MAKE_FUNCTION: DECODE_PTR; - printf("MAKE_FUNCTION %p", (void*)(uintptr_t)unum); + printf("MAKE_FUNCTION %p", (void *)(uintptr_t)unum); break; case MP_BC_MAKE_FUNCTION_DEFARGS: DECODE_PTR; - printf("MAKE_FUNCTION_DEFARGS %p", (void*)(uintptr_t)unum); + printf("MAKE_FUNCTION_DEFARGS %p", (void *)(uintptr_t)unum); break; case MP_BC_MAKE_CLOSURE: { DECODE_PTR; mp_uint_t n_closed_over = *ip++; - printf("MAKE_CLOSURE %p " UINT_FMT, (void*)(uintptr_t)unum, n_closed_over); + printf("MAKE_CLOSURE %p " UINT_FMT, (void *)(uintptr_t)unum, n_closed_over); break; } case MP_BC_MAKE_CLOSURE_DEFARGS: { DECODE_PTR; mp_uint_t n_closed_over = *ip++; - printf("MAKE_CLOSURE_DEFARGS %p " UINT_FMT, (void*)(uintptr_t)unum, n_closed_over); + printf("MAKE_CLOSURE_DEFARGS %p " UINT_FMT, (void *)(uintptr_t)unum, n_closed_over); break; } diff --git a/py/stackctrl.c b/py/stackctrl.c index 26fc065b7d..d699d6da61 100644 --- a/py/stackctrl.c +++ b/py/stackctrl.c @@ -31,7 +31,7 @@ void mp_stack_ctrl_init(void) { // Force routine to not be inlined. Better guarantee than MP_NOINLINE for -flto. __asm volatile (""); volatile int stack_dummy; - MP_STATE_THREAD(stack_top) = (char*)&stack_dummy; + MP_STATE_THREAD(stack_top) = (char *)&stack_dummy; } void mp_stack_set_top(void *top) { @@ -43,7 +43,7 @@ mp_uint_t mp_stack_usage(void) { // Force routine to not be inlined. Better guarantee than MP_NOINLINE for -flto. __asm volatile (""); volatile int stack_dummy; - return MP_STATE_THREAD(stack_top) - (char*)&stack_dummy; + return MP_STATE_THREAD(stack_top) - (char *)&stack_dummy; } #if MICROPY_STACK_CHECK @@ -66,7 +66,7 @@ void mp_stack_check(void) { const char MP_MAX_STACK_USAGE_SENTINEL_BYTE = 0xEE; // Record absolute bottom (logical limit) of stack. -void mp_stack_set_bottom(void* stack_bottom) { +void mp_stack_set_bottom(void *stack_bottom) { MP_STATE_THREAD(stack_bottom) = stack_bottom; } @@ -77,8 +77,8 @@ void mp_stack_set_bottom(void* stack_bottom) { // // The stack_dummy approach used elsewhere in this file is not safe in // all cases. That value may be below the actual top of the stack. -static void* approx_stack_pointer(void){ - __asm volatile (""); +static void *approx_stack_pointer(void) { + __asm volatile (""); return __builtin_frame_address(0); } @@ -89,10 +89,10 @@ void mp_stack_fill_with_sentinel(void) { // Start filling stack just below the current stack frame. // Continue until we've hit the bottom of the stack (lowest address, // logical "ceiling" of stack). - char* p = (char *) approx_stack_pointer() - 1; + char *p = (char *)approx_stack_pointer() - 1; - while(p >= MP_STATE_THREAD(stack_bottom)) { - *p-- = MP_MAX_STACK_USAGE_SENTINEL_BYTE; + while (p >= MP_STATE_THREAD(stack_bottom)) { + *p-- = MP_MAX_STACK_USAGE_SENTINEL_BYTE; } } diff --git a/py/stackctrl.h b/py/stackctrl.h index 18cd81e75b..6b003f6c28 100644 --- a/py/stackctrl.h +++ b/py/stackctrl.h @@ -48,7 +48,7 @@ void mp_stack_check(void); #if MICROPY_MAX_STACK_USAGE const char MP_MAX_STACK_USAGE_SENTINEL_BYTE; -void mp_stack_set_bottom(void* stack_bottom); +void mp_stack_set_bottom(void *stack_bottom); void mp_stack_fill_with_sentinel(void); #endif diff --git a/py/stream.c b/py/stream.c index 0813c1d7f2..159d32ffb4 100644 --- a/py/stream.c +++ b/py/stream.c @@ -235,7 +235,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read1_obj, 1, 2, stream_read1); mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len, byte flags) { int error; - mp_uint_t out_sz = mp_stream_rw(self_in, (void*)buf, len, &error, flags); + mp_uint_t out_sz = mp_stream_rw(self_in, (void *)buf, len, &error, flags); if (error != 0) { if (mp_is_nonblocking_error(error)) { // http://docs.python.org/3/library/io.html#io.RawIOBase.write @@ -272,7 +272,7 @@ STATIC mp_obj_t stream_write_method(size_t n_args, const mp_obj_t *args) { } } bufinfo.len -= off; - return mp_stream_write(args[0], (byte*)bufinfo.buf + off, MIN(bufinfo.len, max_len), MP_STREAM_RW_WRITE); + return mp_stream_write(args[0], (byte *)bufinfo.buf + off, MIN(bufinfo.len, max_len), MP_STREAM_RW_WRITE); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write_obj, 2, 4, stream_write_method); @@ -401,7 +401,7 @@ STATIC mp_obj_t stream_unbuffered_readline(size_t n_args, const mp_obj_t *args) mp_raise_OSError(error); } if (out_sz == 0) { -done: + done: // Back out previously added byte // Consider, what's better - read a char and get OutOfMemory (so read // char is lost), or allocate first as we do. @@ -534,7 +534,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_ioctl_obj, 2, 3, stream_ioctl); int mp_stream_errno; ssize_t mp_stream_posix_write(mp_obj_t stream, const void *buf, size_t len) { - mp_obj_base_t* o = (mp_obj_base_t*)MP_OBJ_TO_PTR(stream); + mp_obj_base_t *o = (mp_obj_base_t *)MP_OBJ_TO_PTR(stream); const mp_stream_p_t *stream_p = mp_get_stream(o); mp_uint_t out_sz = stream_p->write(stream, buf, len, &mp_stream_errno); if (out_sz == MP_STREAM_ERROR) { @@ -545,7 +545,7 @@ ssize_t mp_stream_posix_write(mp_obj_t stream, const void *buf, size_t len) { } ssize_t mp_stream_posix_read(mp_obj_t stream, void *buf, size_t len) { - mp_obj_base_t* o = (mp_obj_base_t*)MP_OBJ_TO_PTR(stream); + mp_obj_base_t *o = (mp_obj_base_t *)MP_OBJ_TO_PTR(stream); const mp_stream_p_t *stream_p = mp_get_stream(o); mp_uint_t out_sz = stream_p->read(stream, buf, len, &mp_stream_errno); if (out_sz == MP_STREAM_ERROR) { @@ -556,7 +556,7 @@ ssize_t mp_stream_posix_read(mp_obj_t stream, void *buf, size_t len) { } off_t mp_stream_posix_lseek(mp_obj_t stream, off_t offset, int whence) { - const mp_obj_base_t* o = (mp_obj_base_t*)MP_OBJ_TO_PTR(stream); + const mp_obj_base_t *o = (mp_obj_base_t *)MP_OBJ_TO_PTR(stream); const mp_stream_p_t *stream_p = mp_get_stream(o); struct mp_stream_seek_t seek_s; seek_s.offset = offset; @@ -569,7 +569,7 @@ off_t mp_stream_posix_lseek(mp_obj_t stream, off_t offset, int whence) { } int mp_stream_posix_fsync(mp_obj_t stream) { - mp_obj_base_t* o = (mp_obj_base_t*)MP_OBJ_TO_PTR(stream); + mp_obj_base_t *o = (mp_obj_base_t *)MP_OBJ_TO_PTR(stream); const mp_stream_p_t *stream_p = mp_get_stream(o); mp_uint_t res = stream_p->ioctl(stream, MP_STREAM_FLUSH, 0, &mp_stream_errno); if (res == MP_STREAM_ERROR) { diff --git a/py/stream.h b/py/stream.h index c05dcfc501..be0b4ace72 100644 --- a/py/stream.h +++ b/py/stream.h @@ -72,9 +72,9 @@ typedef struct _mp_stream_p_t { mp_uint_t (*write)(mp_obj_t obj, const void *buf, mp_uint_t size, int *errcode); mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); mp_uint_t is_text : 1; // default is bytes, set this for text stream - bool pyserial_readinto_compatibility: 1; // Disallow size parameter in readinto() - bool pyserial_read_compatibility: 1; // Disallow omitting read(size) size parameter - bool pyserial_dont_return_none_compatibility: 1; // Don't return None for read() or readinto() + bool pyserial_readinto_compatibility : 1; // Disallow size parameter in readinto() + bool pyserial_read_compatibility : 1; // Disallow omitting read(size) size parameter + bool pyserial_dont_return_none_compatibility : 1; // Don't return None for read() or readinto() } mp_stream_p_t; MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read_obj); @@ -113,7 +113,7 @@ mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len, byte fla #define MP_STREAM_RW_WRITE 2 #define MP_STREAM_RW_ONCE 1 mp_uint_t mp_stream_rw(mp_obj_t stream, void *buf, mp_uint_t size, int *errcode, byte flags); -#define mp_stream_write_exactly(stream, buf, size, err) mp_stream_rw(stream, (byte*)buf, size, err, MP_STREAM_RW_WRITE) +#define mp_stream_write_exactly(stream, buf, size, err) mp_stream_rw(stream, (byte *)buf, size, err, MP_STREAM_RW_WRITE) #define mp_stream_read_exactly(stream, buf, size, err) mp_stream_rw(stream, buf, size, err, MP_STREAM_RW_READ) void mp_stream_write_adaptor(void *self, const char *buf, size_t len); diff --git a/py/unicode.c b/py/unicode.c index a17dbf969b..17f05861ca 100644 --- a/py/unicode.c +++ b/py/unicode.c @@ -71,7 +71,9 @@ STATIC const uint8_t attr[] = { unichar utf8_get_char(const byte *s) { unichar ord = *s++; - if (!UTF8_IS_NONASCII(ord)) return ord; + if (!UTF8_IS_NONASCII(ord)) { + return ord; + } ord &= 0x7F; for (unichar mask = 0x40; ord & mask; mask >>= 1) { ord &= ~mask; diff --git a/py/vm.c b/py/vm.c index 890b5f26f4..21a9528b2b 100644 --- a/py/vm.c +++ b/py/vm.c @@ -65,7 +65,7 @@ ip += 2; #define DECODE_PTR \ DECODE_UINT; \ - void *ptr = (void*)(uintptr_t)code_state->fun_bc->const_table[unum] + void *ptr = (void *)(uintptr_t)code_state->fun_bc->const_table[unum] #define DECODE_OBJ \ DECODE_UINT; \ mp_obj_t obj = (mp_obj_t)code_state->fun_bc->const_table[unum] @@ -77,12 +77,12 @@ qst = (qst << 7) + (*ip & 0x7f); \ } while ((*ip++ & 0x80) != 0) #define DECODE_PTR \ - ip = (byte*)MP_ALIGN(ip, sizeof(void*)); \ - void *ptr = *(void**)ip; \ - ip += sizeof(void*) + ip = (byte *)MP_ALIGN(ip, sizeof(void *)); \ + void *ptr = *(void **)ip; \ + ip += sizeof(void *) #define DECODE_OBJ \ - ip = (byte*)MP_ALIGN(ip, sizeof(mp_obj_t)); \ - mp_obj_t obj = *(mp_obj_t*)ip; \ + ip = (byte *)MP_ALIGN(ip, sizeof(mp_obj_t)); \ + mp_obj_t obj = *(mp_obj_t *)ip; \ ip += sizeof(mp_obj_t) #endif @@ -99,12 +99,12 @@ #endif #define PUSH_EXC_BLOCK(with_or_finally) do { \ - DECODE_ULABEL; /* except labels are always forward */ \ - ++exc_sp; \ - exc_sp->handler = ip + ulab; \ - exc_sp->val_sp = MP_TAGPTR_MAKE(sp, ((with_or_finally) << 1) | currently_in_except_block); \ - exc_sp->prev_exc = NULL; \ - currently_in_except_block = 0; /* in a try block now */ \ + DECODE_ULABEL; /* except labels are always forward */ \ + ++exc_sp; \ + exc_sp->handler = ip + ulab; \ + exc_sp->val_sp = MP_TAGPTR_MAKE(sp, ((with_or_finally) << 1) | currently_in_except_block); \ + exc_sp->prev_exc = NULL; \ + currently_in_except_block = 0; /* in a try block now */ \ } while (0) #define POP_EXC_BLOCK() \ @@ -118,41 +118,41 @@ // MP_VM_RETURN_NORMAL, sp valid, return value in *sp // MP_VM_RETURN_YIELD, ip, sp valid, yielded value in *sp // MP_VM_RETURN_EXCEPTION, exception in fastn[0] -mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t *code_state, volatile mp_obj_t inject_exc) { +mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t * code_state, volatile mp_obj_t inject_exc) { #define SELECTIVE_EXC_IP (0) -#if SELECTIVE_EXC_IP + #if SELECTIVE_EXC_IP #define MARK_EXC_IP_SELECTIVE() { code_state->ip = ip; } /* stores ip 1 byte past last opcode */ #define MARK_EXC_IP_GLOBAL() -#else + #else #define MARK_EXC_IP_SELECTIVE() #define MARK_EXC_IP_GLOBAL() { code_state->ip = ip; } /* stores ip pointing to last opcode */ -#endif -#if MICROPY_OPT_COMPUTED_GOTO + #endif + #if MICROPY_OPT_COMPUTED_GOTO #include "py/vmentrytable.h" -#if MICROPY_OPT_COMPUTED_GOTO_SAVE_SPACE - #define ONE_TRUE_DISPATCH() one_true_dispatch: do { \ + #if MICROPY_OPT_COMPUTED_GOTO_SAVE_SPACE + #define ONE_TRUE_DISPATCH() one_true_dispatch : do { \ TRACE(ip); \ MARK_EXC_IP_GLOBAL(); \ - goto *(void*)((char*)&&entry_MP_BC_LOAD_CONST_FALSE + entry_table[*ip++]); \ - } while (0) - #define DISPATCH() do { goto one_true_dispatch; } while(0) -#else + goto *(void *)((char *) && entry_MP_BC_LOAD_CONST_FALSE + entry_table[*ip++]); \ +} while (0) + #define DISPATCH() do { goto one_true_dispatch; } while (0) + #else #define DISPATCH() do { \ TRACE(ip); \ MARK_EXC_IP_GLOBAL(); \ goto *entry_table[*ip++]; \ - } while (0) +} while (0) #define ONE_TRUE_DISPATCH() DISPATCH() -#endif + #endif #define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check #define ENTRY(op) entry_##op #define ENTRY_DEFAULT entry_default -#else + #else #define DISPATCH() break #define DISPATCH_WITH_PEND_EXC_CHECK() goto pending_exception_check #define ENTRY(op) case op #define ENTRY_DEFAULT default -#endif + #endif // nlr_raise needs to be implemented as a goto, so that the C compiler's flow analyser // sees that it's possible for us to jump from the dispatch loop to the exception @@ -160,16 +160,17 @@ mp_vm_return_kind_t PLACE_IN_ITCM(mp_execute_bytecode)(mp_code_state_t *code_sta // loop and the exception handler, leading to very obscure bugs. #define RAISE(o) do { nlr_pop(); nlr.ret_val = MP_OBJ_TO_PTR(o); goto exception_handler; } while (0) -#if MICROPY_STACKLESS -run_code_state: ; -#endif + #if MICROPY_STACKLESS + run_code_state: + ; + #endif // Pointers which are constant for particular invocation of mp_execute_bytecode() mp_obj_t * /*const*/ fastn; mp_exc_stack_t * /*const*/ exc_stack; { size_t n_state = mp_decode_uint_value(code_state->fun_bc->bytecode); fastn = &code_state->state[n_state - 1]; - exc_stack = (mp_exc_stack_t*)(code_state->state + n_state); + exc_stack = (mp_exc_stack_t *)(code_state->state + n_state); } // variables that are visible to the exception handler (declared volatile) @@ -185,7 +186,7 @@ run_code_state: ; // outer exception handling loop for (;;) { nlr_buf_t nlr; -outer_dispatch_loop: + outer_dispatch_loop: if (nlr_push(&nlr) == 0) { // local variables that are not visible to the exception handler const byte *ip = code_state->ip; @@ -207,28 +208,28 @@ outer_dispatch_loop: // loop to execute byte code for (;;) { -dispatch_loop: -#if MICROPY_OPT_COMPUTED_GOTO + dispatch_loop: + #if MICROPY_OPT_COMPUTED_GOTO ONE_TRUE_DISPATCH(); -#else + #else TRACE(ip); MARK_EXC_IP_GLOBAL(); switch (*ip++) { -#endif + #endif - ENTRY(MP_BC_LOAD_CONST_FALSE): + ENTRY(MP_BC_LOAD_CONST_FALSE) : PUSH(mp_const_false); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_CONST_NONE): + ENTRY(MP_BC_LOAD_CONST_NONE) : PUSH(mp_const_none); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_CONST_TRUE): + ENTRY(MP_BC_LOAD_CONST_TRUE) : PUSH(mp_const_true); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_CONST_SMALL_INT): { + ENTRY(MP_BC_LOAD_CONST_SMALL_INT) : { mp_int_t num = 0; if ((ip[0] & 0x40) != 0) { // Number is negative @@ -241,28 +242,28 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_LOAD_CONST_STRING): { + ENTRY(MP_BC_LOAD_CONST_STRING) : { DECODE_QSTR; PUSH(MP_OBJ_NEW_QSTR(qst)); DISPATCH(); } - ENTRY(MP_BC_LOAD_CONST_OBJ): { + ENTRY(MP_BC_LOAD_CONST_OBJ) : { DECODE_OBJ; PUSH(obj); DISPATCH(); } - ENTRY(MP_BC_LOAD_NULL): + ENTRY(MP_BC_LOAD_NULL) : PUSH(MP_OBJ_NULL); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_FAST_N): { + ENTRY(MP_BC_LOAD_FAST_N) : { DECODE_UINT; obj_shared = fastn[-unum]; - load_check: + load_check: if (obj_shared == MP_OBJ_NULL) { - local_name_error: { + local_name_error: { MARK_EXC_IP_SELECTIVE(); mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NameError, translate("local variable referenced before assignment")); RAISE(obj); @@ -272,21 +273,21 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_LOAD_DEREF): { + ENTRY(MP_BC_LOAD_DEREF) : { DECODE_UINT; obj_shared = mp_obj_cell_get(fastn[-unum]); goto load_check; } #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - ENTRY(MP_BC_LOAD_NAME): { + ENTRY(MP_BC_LOAD_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; PUSH(mp_load_name(qst)); DISPATCH(); } #else - ENTRY(MP_BC_LOAD_NAME): { + ENTRY(MP_BC_LOAD_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t key = MP_OBJ_NEW_QSTR(qst); @@ -296,7 +297,7 @@ dispatch_loop: } else { mp_map_elem_t *elem = mp_map_lookup(&mp_locals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); if (elem != NULL) { - *(byte*)ip = (elem - &mp_locals_get()->map.table[0]) & 0xff; + *(byte *)ip = (elem - &mp_locals_get()->map.table[0]) & 0xff; PUSH(elem->value); } else { PUSH(mp_load_name(MP_OBJ_QSTR_VALUE(key))); @@ -308,14 +309,14 @@ dispatch_loop: #endif #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - ENTRY(MP_BC_LOAD_GLOBAL): { + ENTRY(MP_BC_LOAD_GLOBAL) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; PUSH(mp_load_global(qst)); DISPATCH(); } #else - ENTRY(MP_BC_LOAD_GLOBAL): { + ENTRY(MP_BC_LOAD_GLOBAL) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t key = MP_OBJ_NEW_QSTR(qst); @@ -325,7 +326,7 @@ dispatch_loop: } else { mp_map_elem_t *elem = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(qst), MP_MAP_LOOKUP); if (elem != NULL) { - *(byte*)ip = (elem - &mp_globals_get()->map.table[0]) & 0xff; + *(byte *)ip = (elem - &mp_globals_get()->map.table[0]) & 0xff; PUSH(elem->value); } else { PUSH(mp_load_global(MP_OBJ_QSTR_VALUE(key))); @@ -337,14 +338,14 @@ dispatch_loop: #endif #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - ENTRY(MP_BC_LOAD_ATTR): { + ENTRY(MP_BC_LOAD_ATTR) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; SET_TOP(mp_load_attr(TOP(), qst)); DISPATCH(); } #else - ENTRY(MP_BC_LOAD_ATTR): { + ENTRY(MP_BC_LOAD_ATTR) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t top = TOP(); @@ -358,7 +359,7 @@ dispatch_loop: } else { elem = mp_map_lookup(&self->members, key, MP_MAP_LOOKUP); if (elem != NULL) { - *(byte*)ip = elem - &self->members.table[0]; + *(byte *)ip = elem - &self->members.table[0]; } else { goto load_attr_cache_fail; } @@ -374,7 +375,7 @@ dispatch_loop: } #endif - ENTRY(MP_BC_LOAD_METHOD): { + ENTRY(MP_BC_LOAD_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_load_method(*sp, qst, sp); @@ -382,7 +383,7 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_LOAD_SUPER_METHOD): { + ENTRY(MP_BC_LOAD_SUPER_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; sp -= 1; @@ -390,38 +391,38 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_LOAD_BUILD_CLASS): + ENTRY(MP_BC_LOAD_BUILD_CLASS) : MARK_EXC_IP_SELECTIVE(); - PUSH(mp_load_build_class()); - DISPATCH(); + PUSH(mp_load_build_class()); + DISPATCH(); - ENTRY(MP_BC_LOAD_SUBSCR): { + ENTRY(MP_BC_LOAD_SUBSCR) : { MARK_EXC_IP_SELECTIVE(); mp_obj_t index = POP(); SET_TOP(mp_obj_subscr(TOP(), index, MP_OBJ_SENTINEL)); DISPATCH(); } - ENTRY(MP_BC_STORE_FAST_N): { + ENTRY(MP_BC_STORE_FAST_N) : { DECODE_UINT; fastn[-unum] = POP(); DISPATCH(); } - ENTRY(MP_BC_STORE_DEREF): { + ENTRY(MP_BC_STORE_DEREF) : { DECODE_UINT; mp_obj_cell_set(fastn[-unum], POP()); DISPATCH(); } - ENTRY(MP_BC_STORE_NAME): { + ENTRY(MP_BC_STORE_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_name(qst, POP()); DISPATCH(); } - ENTRY(MP_BC_STORE_GLOBAL): { + ENTRY(MP_BC_STORE_GLOBAL) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_global(qst, POP()); @@ -429,7 +430,7 @@ dispatch_loop: } #if !MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE - ENTRY(MP_BC_STORE_ATTR): { + ENTRY(MP_BC_STORE_ATTR) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_store_attr(sp[0], qst, sp[-1]); @@ -442,7 +443,7 @@ dispatch_loop: // self->members then it can't be a property or have descriptors. A // consequence of this is that we can't use MP_MAP_LOOKUP_ADD_IF_NOT_FOUND // in the fast-path below, because that store could override a property. - ENTRY(MP_BC_STORE_ATTR): { + ENTRY(MP_BC_STORE_ATTR) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t top = TOP(); @@ -456,7 +457,7 @@ dispatch_loop: } else { elem = mp_map_lookup(&self->members, key, MP_MAP_LOOKUP); if (elem != NULL) { - *(byte*)ip = elem - &self->members.table[0]; + *(byte *)ip = elem - &self->members.table[0]; } else { goto store_attr_cache_fail; } @@ -474,13 +475,13 @@ dispatch_loop: } #endif - ENTRY(MP_BC_STORE_SUBSCR): + ENTRY(MP_BC_STORE_SUBSCR) : MARK_EXC_IP_SELECTIVE(); - mp_obj_subscr(sp[-1], sp[0], sp[-2]); - sp -= 3; - DISPATCH(); + mp_obj_subscr(sp[-1], sp[0], sp[-2]); + sp -= 3; + DISPATCH(); - ENTRY(MP_BC_DELETE_FAST): { + ENTRY(MP_BC_DELETE_FAST) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; if (fastn[-unum] == MP_OBJ_NULL) { @@ -490,7 +491,7 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_DELETE_DEREF): { + ENTRY(MP_BC_DELETE_DEREF) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; if (mp_obj_cell_get(fastn[-unum]) == MP_OBJ_NULL) { @@ -500,44 +501,44 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_DELETE_NAME): { + ENTRY(MP_BC_DELETE_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_delete_name(qst); DISPATCH(); } - ENTRY(MP_BC_DELETE_GLOBAL): { + ENTRY(MP_BC_DELETE_GLOBAL) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_delete_global(qst); DISPATCH(); } - ENTRY(MP_BC_DUP_TOP): { + ENTRY(MP_BC_DUP_TOP) : { mp_obj_t top = TOP(); PUSH(top); DISPATCH(); } - ENTRY(MP_BC_DUP_TOP_TWO): + ENTRY(MP_BC_DUP_TOP_TWO) : sp += 2; - sp[0] = sp[-2]; - sp[-1] = sp[-3]; - DISPATCH(); + sp[0] = sp[-2]; + sp[-1] = sp[-3]; + DISPATCH(); - ENTRY(MP_BC_POP_TOP): + ENTRY(MP_BC_POP_TOP) : sp -= 1; - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_ROT_TWO): { + ENTRY(MP_BC_ROT_TWO) : { mp_obj_t top = sp[0]; sp[0] = sp[-1]; sp[-1] = top; DISPATCH(); } - ENTRY(MP_BC_ROT_THREE): { + ENTRY(MP_BC_ROT_THREE) : { mp_obj_t top = sp[0]; sp[0] = sp[-1]; sp[-1] = sp[-2]; @@ -545,13 +546,13 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_JUMP): { + ENTRY(MP_BC_JUMP) : { DECODE_SLABEL; ip += slab; DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_POP_JUMP_IF_TRUE): { + ENTRY(MP_BC_POP_JUMP_IF_TRUE) : { DECODE_SLABEL; if (mp_obj_is_true(POP())) { ip += slab; @@ -559,7 +560,7 @@ dispatch_loop: DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_POP_JUMP_IF_FALSE): { + ENTRY(MP_BC_POP_JUMP_IF_FALSE) : { DECODE_SLABEL; if (!mp_obj_is_true(POP())) { ip += slab; @@ -567,7 +568,7 @@ dispatch_loop: DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_JUMP_IF_TRUE_OR_POP): { + ENTRY(MP_BC_JUMP_IF_TRUE_OR_POP) : { DECODE_SLABEL; if (mp_obj_is_true(TOP())) { ip += slab; @@ -577,7 +578,7 @@ dispatch_loop: DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_JUMP_IF_FALSE_OR_POP): { + ENTRY(MP_BC_JUMP_IF_FALSE_OR_POP) : { DECODE_SLABEL; if (mp_obj_is_true(TOP())) { sp--; @@ -587,7 +588,7 @@ dispatch_loop: DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_SETUP_WITH): { + ENTRY(MP_BC_SETUP_WITH) : { MARK_EXC_IP_SELECTIVE(); // stack: (..., ctx_mgr) mp_obj_t obj = TOP(); @@ -601,7 +602,7 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_WITH_CLEANUP): { + ENTRY(MP_BC_WITH_CLEANUP) : { MARK_EXC_IP_SELECTIVE(); // Arriving here, there's "exception control block" on top of stack, // and __exit__ method (with self) underneath it. Bytecode calls __exit__, @@ -656,12 +657,12 @@ dispatch_loop: DISPATCH(); } - ENTRY(MP_BC_UNWIND_JUMP): { + ENTRY(MP_BC_UNWIND_JUMP) : { MARK_EXC_IP_SELECTIVE(); DECODE_SLABEL; PUSH((mp_obj_t)(mp_uint_t)(uintptr_t)(ip + slab)); // push destination ip for jump PUSH((mp_obj_t)(mp_uint_t)(*ip)); // push number of exception handlers to unwind (0x80 bit set if we also need to pop stack) -unwind_jump:; + unwind_jump:; mp_uint_t unum = (mp_uint_t)POP(); // get number of exception handlers to unwind while ((unum & 0x7f) > 0) { unum -= 1; @@ -684,7 +685,7 @@ unwind_jump:; } POP_EXC_BLOCK(); } - ip = (const byte*)MP_OBJ_TO_PTR(POP()); // pop destination ip for jump + ip = (const byte *)MP_OBJ_TO_PTR(POP()); // pop destination ip for jump if (unum != 0) { // pop the exhausted iterator sp -= MP_OBJ_ITER_BUF_NSLOTS; @@ -693,8 +694,8 @@ unwind_jump:; } // matched against: POP_BLOCK or POP_EXCEPT (anything else?) - ENTRY(MP_BC_SETUP_EXCEPT): - ENTRY(MP_BC_SETUP_FINALLY): { + ENTRY(MP_BC_SETUP_EXCEPT) : + ENTRY(MP_BC_SETUP_FINALLY) : { MARK_EXC_IP_SELECTIVE(); #if SELECTIVE_EXC_IP PUSH_EXC_BLOCK((code_state->ip[-1] == MP_BC_SETUP_FINALLY) ? 1 : 0); @@ -704,45 +705,45 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_END_FINALLY): + ENTRY(MP_BC_END_FINALLY) : MARK_EXC_IP_SELECTIVE(); - // if TOS is None, just pops it and continues - // if TOS is an integer, finishes coroutine and returns control to caller - // if TOS is an exception, reraises the exception - if (TOP() == mp_const_none) { - sp--; - } else if (MP_OBJ_IS_SMALL_INT(TOP())) { - // We finished "finally" coroutine and now dispatch back - // to our caller, based on TOS value - mp_int_t cause = MP_OBJ_SMALL_INT_VALUE(POP()); - if (cause < 0) { - // A negative cause indicates unwind return - goto unwind_return; - } else { - // Otherwise it's an unwind jump and we must push as a raw - // number the number of exception handlers to unwind - PUSH((mp_obj_t)cause); - goto unwind_jump; - } + // if TOS is None, just pops it and continues + // if TOS is an integer, finishes coroutine and returns control to caller + // if TOS is an exception, reraises the exception + if (TOP() == mp_const_none) { + sp--; + } else if (MP_OBJ_IS_SMALL_INT(TOP())) { + // We finished "finally" coroutine and now dispatch back + // to our caller, based on TOS value + mp_int_t cause = MP_OBJ_SMALL_INT_VALUE(POP()); + if (cause < 0) { + // A negative cause indicates unwind return + goto unwind_return; } else { - assert(mp_obj_is_exception_instance(TOP())); - RAISE(TOP()); + // Otherwise it's an unwind jump and we must push as a raw + // number the number of exception handlers to unwind + PUSH((mp_obj_t)cause); + goto unwind_jump; } - DISPATCH(); + } else { + assert(mp_obj_is_exception_instance(TOP())); + RAISE(TOP()); + } + DISPATCH(); - ENTRY(MP_BC_GET_ITER): + ENTRY(MP_BC_GET_ITER) : MARK_EXC_IP_SELECTIVE(); - SET_TOP(mp_getiter(TOP(), NULL)); - DISPATCH(); + SET_TOP(mp_getiter(TOP(), NULL)); + DISPATCH(); // An iterator for a for-loop takes MP_OBJ_ITER_BUF_NSLOTS slots on // the Python value stack. These slots are either used to store the // iterator object itself, or the first slot is MP_OBJ_NULL and // the second slot holds a reference to the iterator object. - ENTRY(MP_BC_GET_ITER_STACK): { + ENTRY(MP_BC_GET_ITER_STACK) : { MARK_EXC_IP_SELECTIVE(); mp_obj_t obj = TOP(); - mp_obj_iter_buf_t *iter_buf = (mp_obj_iter_buf_t*)sp; + mp_obj_iter_buf_t *iter_buf = (mp_obj_iter_buf_t *)sp; sp += MP_OBJ_ITER_BUF_NSLOTS - 1; obj = mp_getiter(obj, iter_buf); if (obj != MP_OBJ_FROM_PTR(iter_buf)) { @@ -753,7 +754,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_FOR_ITER): { + ENTRY(MP_BC_FOR_ITER) : { MARK_EXC_IP_SELECTIVE(); DECODE_ULABEL; // the jump offset if iteration finishes; for labels are always forward code_state->sp = sp; @@ -774,20 +775,20 @@ unwind_jump:; } // matched against: SETUP_EXCEPT, SETUP_FINALLY, SETUP_WITH - ENTRY(MP_BC_POP_BLOCK): + ENTRY(MP_BC_POP_BLOCK) : // we are exiting an exception handler, so pop the last one of the exception-stack assert(exc_sp >= exc_stack); - POP_EXC_BLOCK(); - DISPATCH(); + POP_EXC_BLOCK(); + DISPATCH(); // matched against: SETUP_EXCEPT - ENTRY(MP_BC_POP_EXCEPT): + ENTRY(MP_BC_POP_EXCEPT) : assert(exc_sp >= exc_stack); - assert(currently_in_except_block); - POP_EXC_BLOCK(); - DISPATCH(); + assert(currently_in_except_block); + POP_EXC_BLOCK(); + DISPATCH(); - ENTRY(MP_BC_BUILD_TUPLE): { + ENTRY(MP_BC_BUILD_TUPLE) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; sp -= unum - 1; @@ -795,7 +796,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_BUILD_LIST): { + ENTRY(MP_BC_BUILD_LIST) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; sp -= unum - 1; @@ -803,31 +804,31 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_BUILD_MAP): { + ENTRY(MP_BC_BUILD_MAP) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; PUSH(mp_obj_new_dict(unum)); DISPATCH(); } - ENTRY(MP_BC_STORE_MAP): + ENTRY(MP_BC_STORE_MAP) : MARK_EXC_IP_SELECTIVE(); - sp -= 2; - mp_obj_dict_store(sp[0], sp[2], sp[1]); - DISPATCH(); + sp -= 2; + mp_obj_dict_store(sp[0], sp[2], sp[1]); + DISPATCH(); -#if MICROPY_PY_BUILTINS_SET - ENTRY(MP_BC_BUILD_SET): { + #if MICROPY_PY_BUILTINS_SET + ENTRY(MP_BC_BUILD_SET) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; sp -= unum - 1; SET_TOP(mp_obj_new_set(unum, sp)); DISPATCH(); } -#endif + #endif -#if MICROPY_PY_BUILTINS_SLICE - ENTRY(MP_BC_BUILD_SLICE): { + #if MICROPY_PY_BUILTINS_SLICE + ENTRY(MP_BC_BUILD_SLICE) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; if (unum == 2) { @@ -842,9 +843,9 @@ unwind_jump:; } DISPATCH(); } -#endif + #endif - ENTRY(MP_BC_STORE_COMP): { + ENTRY(MP_BC_STORE_COMP) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_obj_t obj = sp[-(unum >> 2)]; @@ -863,7 +864,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_UNPACK_SEQUENCE): { + ENTRY(MP_BC_UNPACK_SEQUENCE) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_unpack_sequence(sp[0], unum, sp); @@ -871,7 +872,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_UNPACK_EX): { + ENTRY(MP_BC_UNPACK_EX) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; mp_unpack_ex(sp[0], unum, sp); @@ -879,13 +880,13 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_MAKE_FUNCTION): { + ENTRY(MP_BC_MAKE_FUNCTION) : { DECODE_PTR; PUSH(mp_make_function_from_raw_code(ptr, MP_OBJ_NULL, MP_OBJ_NULL)); DISPATCH(); } - ENTRY(MP_BC_MAKE_FUNCTION_DEFARGS): { + ENTRY(MP_BC_MAKE_FUNCTION_DEFARGS) : { DECODE_PTR; // Stack layout: def_tuple def_dict <- TOS mp_obj_t def_dict = POP(); @@ -893,7 +894,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_MAKE_CLOSURE): { + ENTRY(MP_BC_MAKE_CLOSURE) : { DECODE_PTR; size_t n_closed_over = *ip++; // Stack layout: closed_overs <- TOS @@ -902,7 +903,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_MAKE_CLOSURE_DEFARGS): { + ENTRY(MP_BC_MAKE_CLOSURE_DEFARGS) : { DECODE_PTR; size_t n_closed_over = *ip++; // Stack layout: def_tuple def_dict closed_overs <- TOS @@ -911,7 +912,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_FUNCTION): { + ENTRY(MP_BC_CALL_FUNCTION) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -945,7 +946,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_FUNCTION_VAR_KW): { + ENTRY(MP_BC_CALL_FUNCTION_VAR_KW) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -990,7 +991,7 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_CALL_METHOD): { + ENTRY(MP_BC_CALL_METHOD) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -1028,7 +1029,7 @@ unwind_jump:; DISPATCH_WITH_PEND_EXC_CHECK(); } - ENTRY(MP_BC_CALL_METHOD_VAR_KW): { + ENTRY(MP_BC_CALL_METHOD_VAR_KW) : { MARK_EXC_IP_SELECTIVE(); DECODE_UINT; // unum & 0xff == n_positional @@ -1073,66 +1074,66 @@ unwind_jump:; DISPATCH(); } - ENTRY(MP_BC_RETURN_VALUE): + ENTRY(MP_BC_RETURN_VALUE) : MARK_EXC_IP_SELECTIVE(); - // These next 3 lines pop a try-finally exception handler, if one - // is there on the exception stack. Without this the finally block - // is executed a second time when the return is executed, because - // the try-finally exception handler is still on the stack. - // TODO Possibly find a better way to handle this case. - if (currently_in_except_block) { - POP_EXC_BLOCK(); - } -unwind_return: - while (exc_sp >= exc_stack) { - if (MP_TAGPTR_TAG1(exc_sp->val_sp)) { - // Getting here the stack looks like: - // (..., X, [iter0, iter1, ...,] ret_val) - // where X is pointed to by exc_sp->val_sp and in the case - // of a "with" block contains the context manager info. - // There may be 0 or more for-iterators between X and the - // return value, and these must be removed before control can - // pass to the finally code. We simply copy the ret_value down - // over these iterators, if they exist. If they don't then the - // following is a null operation. - mp_obj_t *finally_sp = MP_TAGPTR_PTR(exc_sp->val_sp); - finally_sp[1] = sp[0]; - sp = &finally_sp[1]; - // We're going to run "finally" code as a coroutine - // (not calling it recursively). Set up a sentinel - // on a stack so it can return back to us when it is - // done (when WITH_CLEANUP or END_FINALLY reached). - PUSH(MP_OBJ_NEW_SMALL_INT(-1)); - ip = exc_sp->handler; - exc_sp--; - goto dispatch_loop; - } + // These next 3 lines pop a try-finally exception handler, if one + // is there on the exception stack. Without this the finally block + // is executed a second time when the return is executed, because + // the try-finally exception handler is still on the stack. + // TODO Possibly find a better way to handle this case. + if (currently_in_except_block) { + POP_EXC_BLOCK(); + } + unwind_return: + while (exc_sp >= exc_stack) { + if (MP_TAGPTR_TAG1(exc_sp->val_sp)) { + // Getting here the stack looks like: + // (..., X, [iter0, iter1, ...,] ret_val) + // where X is pointed to by exc_sp->val_sp and in the case + // of a "with" block contains the context manager info. + // There may be 0 or more for-iterators between X and the + // return value, and these must be removed before control can + // pass to the finally code. We simply copy the ret_value down + // over these iterators, if they exist. If they don't then the + // following is a null operation. + mp_obj_t *finally_sp = MP_TAGPTR_PTR(exc_sp->val_sp); + finally_sp[1] = sp[0]; + sp = &finally_sp[1]; + // We're going to run "finally" code as a coroutine + // (not calling it recursively). Set up a sentinel + // on a stack so it can return back to us when it is + // done (when WITH_CLEANUP or END_FINALLY reached). + PUSH(MP_OBJ_NEW_SMALL_INT(-1)); + ip = exc_sp->handler; exc_sp--; + goto dispatch_loop; } - nlr_pop(); - code_state->sp = sp; - assert(exc_sp == exc_stack - 1); - MICROPY_VM_HOOK_RETURN - #if MICROPY_STACKLESS - if (code_state->prev != NULL) { - mp_obj_t res = *sp; - mp_globals_set(code_state->old_globals); - mp_code_state_t *new_code_state = code_state->prev; - #if MICROPY_ENABLE_PYSTACK - // Free code_state, and args allocated by mp_call_prepare_args_n_kw_var - // (The latter is implicitly freed when using pystack due to its LIFO nature.) - // The sizeof in the following statement does not include the size of the variable - // part of the struct. This arg is anyway not used if pystack is enabled. - mp_nonlocal_free(code_state, sizeof(mp_code_state_t)); - #endif - code_state = new_code_state; - *code_state->sp = res; - goto run_code_state; - } + exc_sp--; + } + nlr_pop(); + code_state->sp = sp; + assert(exc_sp == exc_stack - 1); + MICROPY_VM_HOOK_RETURN + #if MICROPY_STACKLESS + if (code_state->prev != NULL) { + mp_obj_t res = *sp; + mp_globals_set(code_state->old_globals); + mp_code_state_t *new_code_state = code_state->prev; + #if MICROPY_ENABLE_PYSTACK + // Free code_state, and args allocated by mp_call_prepare_args_n_kw_var + // (The latter is implicitly freed when using pystack due to its LIFO nature.) + // The sizeof in the following statement does not include the size of the variable + // part of the struct. This arg is anyway not used if pystack is enabled. + mp_nonlocal_free(code_state, sizeof(mp_code_state_t)); #endif - return MP_VM_RETURN_NORMAL; + code_state = new_code_state; + *code_state->sp = res; + goto run_code_state; + } + #endif + return MP_VM_RETURN_NORMAL; - ENTRY(MP_BC_RAISE_VARARGS): { + ENTRY(MP_BC_RAISE_VARARGS) : { MARK_EXC_IP_SELECTIVE(); mp_uint_t unum = *ip; mp_obj_t obj; @@ -1161,19 +1162,20 @@ unwind_return: RAISE(obj); } - ENTRY(MP_BC_YIELD_VALUE): -yield: + ENTRY(MP_BC_YIELD_VALUE) : + yield: nlr_pop(); - code_state->ip = ip; - code_state->sp = sp; - code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); - return MP_VM_RETURN_YIELD; + code_state->ip = ip; + code_state->sp = sp; + code_state->exc_sp = MP_TAGPTR_MAKE(exc_sp, currently_in_except_block); + return MP_VM_RETURN_YIELD; - ENTRY(MP_BC_YIELD_FROM): { + ENTRY(MP_BC_YIELD_FROM) : { MARK_EXC_IP_SELECTIVE(); -//#define EXC_MATCH(exc, type) MP_OBJ_IS_TYPE(exc, type) +// #define EXC_MATCH(exc, type) MP_OBJ_IS_TYPE(exc, type) #define EXC_MATCH(exc, type) mp_obj_exception_match(exc, type) -#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { RAISE(t); } +#define GENERATOR_EXIT_IF_NEEDED(t) if (t != MP_OBJ_NULL && EXC_MATCH(t, MP_OBJ_FROM_PTR(&mp_type_GeneratorExit))) { RAISE(t); \ +} mp_vm_return_kind_t ret_kind; mp_obj_t send_value = POP(); mp_obj_t t_exc = MP_OBJ_NULL; @@ -1222,7 +1224,7 @@ yield: } } - ENTRY(MP_BC_IMPORT_NAME): { + ENTRY(MP_BC_IMPORT_NAME) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t obj = POP(); @@ -1230,7 +1232,7 @@ yield: DISPATCH(); } - ENTRY(MP_BC_IMPORT_FROM): { + ENTRY(MP_BC_IMPORT_FROM) : { MARK_EXC_IP_SELECTIVE(); DECODE_QSTR; mp_obj_t obj = mp_import_from(TOP(), qst); @@ -1238,30 +1240,30 @@ yield: DISPATCH(); } - ENTRY(MP_BC_IMPORT_STAR): + ENTRY(MP_BC_IMPORT_STAR) : MARK_EXC_IP_SELECTIVE(); - mp_import_all(POP()); - DISPATCH(); + mp_import_all(POP()); + DISPATCH(); -#if MICROPY_OPT_COMPUTED_GOTO - ENTRY(MP_BC_LOAD_CONST_SMALL_INT_MULTI): + #if MICROPY_OPT_COMPUTED_GOTO + ENTRY(MP_BC_LOAD_CONST_SMALL_INT_MULTI) : PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16)); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_LOAD_FAST_MULTI): + ENTRY(MP_BC_LOAD_FAST_MULTI) : obj_shared = fastn[MP_BC_LOAD_FAST_MULTI - (mp_int_t)ip[-1]]; - goto load_check; + goto load_check; - ENTRY(MP_BC_STORE_FAST_MULTI): + ENTRY(MP_BC_STORE_FAST_MULTI) : fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP(); - DISPATCH(); + DISPATCH(); - ENTRY(MP_BC_UNARY_OP_MULTI): + ENTRY(MP_BC_UNARY_OP_MULTI) : MARK_EXC_IP_SELECTIVE(); - SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); - DISPATCH(); + SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); + DISPATCH(); - ENTRY(MP_BC_BINARY_OP_MULTI): { + ENTRY(MP_BC_BINARY_OP_MULTI) : { MARK_EXC_IP_SELECTIVE(); mp_obj_t rhs = POP(); mp_obj_t lhs = TOP(); @@ -1269,29 +1271,29 @@ yield: DISPATCH(); } - ENTRY_DEFAULT: - MARK_EXC_IP_SELECTIVE(); -#else - ENTRY_DEFAULT: - if (ip[-1] < MP_BC_LOAD_CONST_SMALL_INT_MULTI + 64) { - PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16)); - DISPATCH(); - } else if (ip[-1] < MP_BC_LOAD_FAST_MULTI + 16) { - obj_shared = fastn[MP_BC_LOAD_FAST_MULTI - (mp_int_t)ip[-1]]; - goto load_check; - } else if (ip[-1] < MP_BC_STORE_FAST_MULTI + 16) { - fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP(); - DISPATCH(); - } else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE) { - SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); - DISPATCH(); - } else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE) { - mp_obj_t rhs = POP(); - mp_obj_t lhs = TOP(); - SET_TOP(mp_binary_op(ip[-1] - MP_BC_BINARY_OP_MULTI, lhs, rhs)); - DISPATCH(); - } else -#endif + ENTRY_DEFAULT: + MARK_EXC_IP_SELECTIVE(); + #else + ENTRY_DEFAULT: + if (ip[-1] < MP_BC_LOAD_CONST_SMALL_INT_MULTI + 64) { + PUSH(MP_OBJ_NEW_SMALL_INT((mp_int_t)ip[-1] - MP_BC_LOAD_CONST_SMALL_INT_MULTI - 16)); + DISPATCH(); + } else if (ip[-1] < MP_BC_LOAD_FAST_MULTI + 16) { + obj_shared = fastn[MP_BC_LOAD_FAST_MULTI - (mp_int_t)ip[-1]]; + goto load_check; + } else if (ip[-1] < MP_BC_STORE_FAST_MULTI + 16) { + fastn[MP_BC_STORE_FAST_MULTI - (mp_int_t)ip[-1]] = POP(); + DISPATCH(); + } else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE) { + SET_TOP(mp_unary_op(ip[-1] - MP_BC_UNARY_OP_MULTI, TOP())); + DISPATCH(); + } else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE) { + mp_obj_t rhs = POP(); + mp_obj_t lhs = TOP(); + SET_TOP(mp_binary_op(ip[-1] - MP_BC_BINARY_OP_MULTI, lhs, rhs)); + DISPATCH(); + } else + #endif { mp_obj_t obj = mp_obj_new_exception_msg(&mp_type_NotImplementedError, translate("byte code not implemented")); nlr_pop(); @@ -1299,11 +1301,11 @@ yield: return MP_VM_RETURN_EXCEPTION; } -#if !MICROPY_OPT_COMPUTED_GOTO - } // switch -#endif + #if !MICROPY_OPT_COMPUTED_GOTO + } // switch + #endif -pending_exception_check: + pending_exception_check: MICROPY_VM_HOOK_LOOP #if MICROPY_ENABLE_SCHEDULER @@ -1345,8 +1347,8 @@ pending_exception_check: if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) #endif { - MP_THREAD_GIL_EXIT(); - MP_THREAD_GIL_ENTER(); + MP_THREAD_GIL_EXIT(); + MP_THREAD_GIL_ENTER(); } } #endif @@ -1354,7 +1356,7 @@ pending_exception_check: } // for loop } else { -exception_handler: + exception_handler: // exception occurred #if MICROPY_PY_SYS_EXC_INFO @@ -1366,7 +1368,7 @@ exception_handler: code_state->ip -= 1; #endif - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_StopIteration))) { if (code_state->ip) { // check if it's a StopIteration within a for block if (*code_state->ip == MP_BC_FOR_ITER) { @@ -1386,9 +1388,9 @@ exception_handler: } } -#if MICROPY_STACKLESS -unwind_loop: -#endif + #if MICROPY_STACKLESS + unwind_loop: + #endif // set file and line number that the exception occurred at // TODO: don't set traceback for exceptions re-raised by END_FINALLY. // But consider how to handle nested exceptions. @@ -1479,7 +1481,7 @@ unwind_loop: code_state = new_code_state; size_t n_state = mp_decode_uint_value(code_state->fun_bc->bytecode); fastn = &code_state->state[n_state - 1]; - exc_stack = (mp_exc_stack_t*)(code_state->state + n_state); + exc_stack = (mp_exc_stack_t *)(code_state->state + n_state); // variables that are visible to the exception handler (declared volatile) currently_in_except_block = MP_TAGPTR_TAG0(code_state->exc_sp); // 0 or 1, to detect nested exceptions exc_sp = MP_TAGPTR_PTR(code_state->exc_sp); // stack grows up, exc_sp points to top of stack diff --git a/py/vmentrytable.h b/py/vmentrytable.h index 31832bb580..0f6c5e96d3 100644 --- a/py/vmentrytable.h +++ b/py/vmentrytable.h @@ -32,7 +32,7 @@ #include "supervisor/linker.h" #if MICROPY_OPT_COMPUTED_GOTO_SAVE_SPACE -#define COMPUTE_ENTRY(x) ((char*)(x) - (char*)&&entry_MP_BC_LOAD_CONST_FALSE) +#define COMPUTE_ENTRY(x) ((char *)(x) - (char *) && entry_MP_BC_LOAD_CONST_FALSE) typedef int16_t entry_table_type; #else #define COMPUTE_ENTRY(x) (x) @@ -40,87 +40,87 @@ typedef void *entry_table_type; #endif static entry_table_type const PLACE_IN_DTCM_DATA(entry_table[256]) = { - [0 ... 255] = COMPUTE_ENTRY(&&entry_default), - [MP_BC_LOAD_CONST_FALSE] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_CONST_FALSE), - [MP_BC_LOAD_CONST_NONE] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_CONST_NONE), - [MP_BC_LOAD_CONST_TRUE] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_CONST_TRUE), - [MP_BC_LOAD_CONST_SMALL_INT] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_CONST_SMALL_INT), - [MP_BC_LOAD_CONST_STRING] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_CONST_STRING), - [MP_BC_LOAD_CONST_OBJ] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_CONST_OBJ), - [MP_BC_LOAD_NULL] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_NULL), - [MP_BC_LOAD_FAST_N] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_FAST_N), - [MP_BC_LOAD_DEREF] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_DEREF), - [MP_BC_LOAD_NAME] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_NAME), - [MP_BC_LOAD_GLOBAL] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_GLOBAL), - [MP_BC_LOAD_ATTR] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_ATTR), - [MP_BC_LOAD_METHOD] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_METHOD), - [MP_BC_LOAD_SUPER_METHOD] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_SUPER_METHOD), - [MP_BC_LOAD_BUILD_CLASS] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_BUILD_CLASS), - [MP_BC_LOAD_SUBSCR] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_SUBSCR), - [MP_BC_STORE_FAST_N] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_FAST_N), - [MP_BC_STORE_DEREF] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_DEREF), - [MP_BC_STORE_NAME] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_NAME), - [MP_BC_STORE_GLOBAL] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_GLOBAL), - [MP_BC_STORE_ATTR] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_ATTR), - [MP_BC_STORE_SUBSCR] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_SUBSCR), - [MP_BC_DELETE_FAST] = COMPUTE_ENTRY(&&entry_MP_BC_DELETE_FAST), - [MP_BC_DELETE_DEREF] = COMPUTE_ENTRY(&&entry_MP_BC_DELETE_DEREF), - [MP_BC_DELETE_NAME] = COMPUTE_ENTRY(&&entry_MP_BC_DELETE_NAME), - [MP_BC_DELETE_GLOBAL] = COMPUTE_ENTRY(&&entry_MP_BC_DELETE_GLOBAL), - [MP_BC_DUP_TOP] = COMPUTE_ENTRY(&&entry_MP_BC_DUP_TOP), - [MP_BC_DUP_TOP_TWO] = COMPUTE_ENTRY(&&entry_MP_BC_DUP_TOP_TWO), - [MP_BC_POP_TOP] = COMPUTE_ENTRY(&&entry_MP_BC_POP_TOP), - [MP_BC_ROT_TWO] = COMPUTE_ENTRY(&&entry_MP_BC_ROT_TWO), - [MP_BC_ROT_THREE] = COMPUTE_ENTRY(&&entry_MP_BC_ROT_THREE), - [MP_BC_JUMP] = COMPUTE_ENTRY(&&entry_MP_BC_JUMP), - [MP_BC_POP_JUMP_IF_TRUE] = COMPUTE_ENTRY(&&entry_MP_BC_POP_JUMP_IF_TRUE), - [MP_BC_POP_JUMP_IF_FALSE] = COMPUTE_ENTRY(&&entry_MP_BC_POP_JUMP_IF_FALSE), - [MP_BC_JUMP_IF_TRUE_OR_POP] = COMPUTE_ENTRY(&&entry_MP_BC_JUMP_IF_TRUE_OR_POP), - [MP_BC_JUMP_IF_FALSE_OR_POP] = COMPUTE_ENTRY(&&entry_MP_BC_JUMP_IF_FALSE_OR_POP), - [MP_BC_SETUP_WITH] = COMPUTE_ENTRY(&&entry_MP_BC_SETUP_WITH), - [MP_BC_WITH_CLEANUP] = COMPUTE_ENTRY(&&entry_MP_BC_WITH_CLEANUP), - [MP_BC_UNWIND_JUMP] = COMPUTE_ENTRY(&&entry_MP_BC_UNWIND_JUMP), - [MP_BC_SETUP_EXCEPT] = COMPUTE_ENTRY(&&entry_MP_BC_SETUP_EXCEPT), - [MP_BC_SETUP_FINALLY] = COMPUTE_ENTRY(&&entry_MP_BC_SETUP_FINALLY), - [MP_BC_END_FINALLY] = COMPUTE_ENTRY(&&entry_MP_BC_END_FINALLY), - [MP_BC_GET_ITER] = COMPUTE_ENTRY(&&entry_MP_BC_GET_ITER), - [MP_BC_GET_ITER_STACK] = COMPUTE_ENTRY(&&entry_MP_BC_GET_ITER_STACK), - [MP_BC_FOR_ITER] = COMPUTE_ENTRY(&&entry_MP_BC_FOR_ITER), - [MP_BC_POP_BLOCK] = COMPUTE_ENTRY(&&entry_MP_BC_POP_BLOCK), - [MP_BC_POP_EXCEPT] = COMPUTE_ENTRY(&&entry_MP_BC_POP_EXCEPT), - [MP_BC_BUILD_TUPLE] = COMPUTE_ENTRY(&&entry_MP_BC_BUILD_TUPLE), - [MP_BC_BUILD_LIST] = COMPUTE_ENTRY(&&entry_MP_BC_BUILD_LIST), - [MP_BC_BUILD_MAP] = COMPUTE_ENTRY(&&entry_MP_BC_BUILD_MAP), - [MP_BC_STORE_MAP] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_MAP), + [0 ... 255] = COMPUTE_ENTRY(&& entry_default), + [MP_BC_LOAD_CONST_FALSE] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_CONST_FALSE), + [MP_BC_LOAD_CONST_NONE] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_CONST_NONE), + [MP_BC_LOAD_CONST_TRUE] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_CONST_TRUE), + [MP_BC_LOAD_CONST_SMALL_INT] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_CONST_SMALL_INT), + [MP_BC_LOAD_CONST_STRING] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_CONST_STRING), + [MP_BC_LOAD_CONST_OBJ] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_CONST_OBJ), + [MP_BC_LOAD_NULL] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_NULL), + [MP_BC_LOAD_FAST_N] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_FAST_N), + [MP_BC_LOAD_DEREF] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_DEREF), + [MP_BC_LOAD_NAME] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_NAME), + [MP_BC_LOAD_GLOBAL] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_GLOBAL), + [MP_BC_LOAD_ATTR] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_ATTR), + [MP_BC_LOAD_METHOD] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_METHOD), + [MP_BC_LOAD_SUPER_METHOD] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_SUPER_METHOD), + [MP_BC_LOAD_BUILD_CLASS] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_BUILD_CLASS), + [MP_BC_LOAD_SUBSCR] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_SUBSCR), + [MP_BC_STORE_FAST_N] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_FAST_N), + [MP_BC_STORE_DEREF] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_DEREF), + [MP_BC_STORE_NAME] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_NAME), + [MP_BC_STORE_GLOBAL] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_GLOBAL), + [MP_BC_STORE_ATTR] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_ATTR), + [MP_BC_STORE_SUBSCR] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_SUBSCR), + [MP_BC_DELETE_FAST] = COMPUTE_ENTRY(&& entry_MP_BC_DELETE_FAST), + [MP_BC_DELETE_DEREF] = COMPUTE_ENTRY(&& entry_MP_BC_DELETE_DEREF), + [MP_BC_DELETE_NAME] = COMPUTE_ENTRY(&& entry_MP_BC_DELETE_NAME), + [MP_BC_DELETE_GLOBAL] = COMPUTE_ENTRY(&& entry_MP_BC_DELETE_GLOBAL), + [MP_BC_DUP_TOP] = COMPUTE_ENTRY(&& entry_MP_BC_DUP_TOP), + [MP_BC_DUP_TOP_TWO] = COMPUTE_ENTRY(&& entry_MP_BC_DUP_TOP_TWO), + [MP_BC_POP_TOP] = COMPUTE_ENTRY(&& entry_MP_BC_POP_TOP), + [MP_BC_ROT_TWO] = COMPUTE_ENTRY(&& entry_MP_BC_ROT_TWO), + [MP_BC_ROT_THREE] = COMPUTE_ENTRY(&& entry_MP_BC_ROT_THREE), + [MP_BC_JUMP] = COMPUTE_ENTRY(&& entry_MP_BC_JUMP), + [MP_BC_POP_JUMP_IF_TRUE] = COMPUTE_ENTRY(&& entry_MP_BC_POP_JUMP_IF_TRUE), + [MP_BC_POP_JUMP_IF_FALSE] = COMPUTE_ENTRY(&& entry_MP_BC_POP_JUMP_IF_FALSE), + [MP_BC_JUMP_IF_TRUE_OR_POP] = COMPUTE_ENTRY(&& entry_MP_BC_JUMP_IF_TRUE_OR_POP), + [MP_BC_JUMP_IF_FALSE_OR_POP] = COMPUTE_ENTRY(&& entry_MP_BC_JUMP_IF_FALSE_OR_POP), + [MP_BC_SETUP_WITH] = COMPUTE_ENTRY(&& entry_MP_BC_SETUP_WITH), + [MP_BC_WITH_CLEANUP] = COMPUTE_ENTRY(&& entry_MP_BC_WITH_CLEANUP), + [MP_BC_UNWIND_JUMP] = COMPUTE_ENTRY(&& entry_MP_BC_UNWIND_JUMP), + [MP_BC_SETUP_EXCEPT] = COMPUTE_ENTRY(&& entry_MP_BC_SETUP_EXCEPT), + [MP_BC_SETUP_FINALLY] = COMPUTE_ENTRY(&& entry_MP_BC_SETUP_FINALLY), + [MP_BC_END_FINALLY] = COMPUTE_ENTRY(&& entry_MP_BC_END_FINALLY), + [MP_BC_GET_ITER] = COMPUTE_ENTRY(&& entry_MP_BC_GET_ITER), + [MP_BC_GET_ITER_STACK] = COMPUTE_ENTRY(&& entry_MP_BC_GET_ITER_STACK), + [MP_BC_FOR_ITER] = COMPUTE_ENTRY(&& entry_MP_BC_FOR_ITER), + [MP_BC_POP_BLOCK] = COMPUTE_ENTRY(&& entry_MP_BC_POP_BLOCK), + [MP_BC_POP_EXCEPT] = COMPUTE_ENTRY(&& entry_MP_BC_POP_EXCEPT), + [MP_BC_BUILD_TUPLE] = COMPUTE_ENTRY(&& entry_MP_BC_BUILD_TUPLE), + [MP_BC_BUILD_LIST] = COMPUTE_ENTRY(&& entry_MP_BC_BUILD_LIST), + [MP_BC_BUILD_MAP] = COMPUTE_ENTRY(&& entry_MP_BC_BUILD_MAP), + [MP_BC_STORE_MAP] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_MAP), #if MICROPY_PY_BUILTINS_SET - [MP_BC_BUILD_SET] = COMPUTE_ENTRY(&&entry_MP_BC_BUILD_SET), + [MP_BC_BUILD_SET] = COMPUTE_ENTRY(&& entry_MP_BC_BUILD_SET), #endif #if MICROPY_PY_BUILTINS_SLICE - [MP_BC_BUILD_SLICE] = COMPUTE_ENTRY(&&entry_MP_BC_BUILD_SLICE), + [MP_BC_BUILD_SLICE] = COMPUTE_ENTRY(&& entry_MP_BC_BUILD_SLICE), #endif - [MP_BC_STORE_COMP] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_COMP), - [MP_BC_UNPACK_SEQUENCE] = COMPUTE_ENTRY(&&entry_MP_BC_UNPACK_SEQUENCE), - [MP_BC_UNPACK_EX] = COMPUTE_ENTRY(&&entry_MP_BC_UNPACK_EX), - [MP_BC_MAKE_FUNCTION] = COMPUTE_ENTRY(&&entry_MP_BC_MAKE_FUNCTION), - [MP_BC_MAKE_FUNCTION_DEFARGS] = COMPUTE_ENTRY(&&entry_MP_BC_MAKE_FUNCTION_DEFARGS), - [MP_BC_MAKE_CLOSURE] = COMPUTE_ENTRY(&&entry_MP_BC_MAKE_CLOSURE), - [MP_BC_MAKE_CLOSURE_DEFARGS] = COMPUTE_ENTRY(&&entry_MP_BC_MAKE_CLOSURE_DEFARGS), - [MP_BC_CALL_FUNCTION] = COMPUTE_ENTRY(&&entry_MP_BC_CALL_FUNCTION), - [MP_BC_CALL_FUNCTION_VAR_KW] = COMPUTE_ENTRY(&&entry_MP_BC_CALL_FUNCTION_VAR_KW), - [MP_BC_CALL_METHOD] = COMPUTE_ENTRY(&&entry_MP_BC_CALL_METHOD), - [MP_BC_CALL_METHOD_VAR_KW] = COMPUTE_ENTRY(&&entry_MP_BC_CALL_METHOD_VAR_KW), - [MP_BC_RETURN_VALUE] = COMPUTE_ENTRY(&&entry_MP_BC_RETURN_VALUE), - [MP_BC_RAISE_VARARGS] = COMPUTE_ENTRY(&&entry_MP_BC_RAISE_VARARGS), - [MP_BC_YIELD_VALUE] = COMPUTE_ENTRY(&&entry_MP_BC_YIELD_VALUE), - [MP_BC_YIELD_FROM] = COMPUTE_ENTRY(&&entry_MP_BC_YIELD_FROM), - [MP_BC_IMPORT_NAME] = COMPUTE_ENTRY(&&entry_MP_BC_IMPORT_NAME), - [MP_BC_IMPORT_FROM] = COMPUTE_ENTRY(&&entry_MP_BC_IMPORT_FROM), - [MP_BC_IMPORT_STAR] = COMPUTE_ENTRY(&&entry_MP_BC_IMPORT_STAR), - [MP_BC_LOAD_CONST_SMALL_INT_MULTI ... MP_BC_LOAD_CONST_SMALL_INT_MULTI + 63] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_CONST_SMALL_INT_MULTI), - [MP_BC_LOAD_FAST_MULTI ... MP_BC_LOAD_FAST_MULTI + 15] = COMPUTE_ENTRY(&&entry_MP_BC_LOAD_FAST_MULTI), - [MP_BC_STORE_FAST_MULTI ... MP_BC_STORE_FAST_MULTI + 15] = COMPUTE_ENTRY(&&entry_MP_BC_STORE_FAST_MULTI), - [MP_BC_UNARY_OP_MULTI ... MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE - 1] = COMPUTE_ENTRY(&&entry_MP_BC_UNARY_OP_MULTI), - [MP_BC_BINARY_OP_MULTI ... MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE - 1] = COMPUTE_ENTRY(&&entry_MP_BC_BINARY_OP_MULTI), + [MP_BC_STORE_COMP] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_COMP), + [MP_BC_UNPACK_SEQUENCE] = COMPUTE_ENTRY(&& entry_MP_BC_UNPACK_SEQUENCE), + [MP_BC_UNPACK_EX] = COMPUTE_ENTRY(&& entry_MP_BC_UNPACK_EX), + [MP_BC_MAKE_FUNCTION] = COMPUTE_ENTRY(&& entry_MP_BC_MAKE_FUNCTION), + [MP_BC_MAKE_FUNCTION_DEFARGS] = COMPUTE_ENTRY(&& entry_MP_BC_MAKE_FUNCTION_DEFARGS), + [MP_BC_MAKE_CLOSURE] = COMPUTE_ENTRY(&& entry_MP_BC_MAKE_CLOSURE), + [MP_BC_MAKE_CLOSURE_DEFARGS] = COMPUTE_ENTRY(&& entry_MP_BC_MAKE_CLOSURE_DEFARGS), + [MP_BC_CALL_FUNCTION] = COMPUTE_ENTRY(&& entry_MP_BC_CALL_FUNCTION), + [MP_BC_CALL_FUNCTION_VAR_KW] = COMPUTE_ENTRY(&& entry_MP_BC_CALL_FUNCTION_VAR_KW), + [MP_BC_CALL_METHOD] = COMPUTE_ENTRY(&& entry_MP_BC_CALL_METHOD), + [MP_BC_CALL_METHOD_VAR_KW] = COMPUTE_ENTRY(&& entry_MP_BC_CALL_METHOD_VAR_KW), + [MP_BC_RETURN_VALUE] = COMPUTE_ENTRY(&& entry_MP_BC_RETURN_VALUE), + [MP_BC_RAISE_VARARGS] = COMPUTE_ENTRY(&& entry_MP_BC_RAISE_VARARGS), + [MP_BC_YIELD_VALUE] = COMPUTE_ENTRY(&& entry_MP_BC_YIELD_VALUE), + [MP_BC_YIELD_FROM] = COMPUTE_ENTRY(&& entry_MP_BC_YIELD_FROM), + [MP_BC_IMPORT_NAME] = COMPUTE_ENTRY(&& entry_MP_BC_IMPORT_NAME), + [MP_BC_IMPORT_FROM] = COMPUTE_ENTRY(&& entry_MP_BC_IMPORT_FROM), + [MP_BC_IMPORT_STAR] = COMPUTE_ENTRY(&& entry_MP_BC_IMPORT_STAR), + [MP_BC_LOAD_CONST_SMALL_INT_MULTI ... MP_BC_LOAD_CONST_SMALL_INT_MULTI + 63] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_CONST_SMALL_INT_MULTI), + [MP_BC_LOAD_FAST_MULTI ... MP_BC_LOAD_FAST_MULTI + 15] = COMPUTE_ENTRY(&& entry_MP_BC_LOAD_FAST_MULTI), + [MP_BC_STORE_FAST_MULTI ... MP_BC_STORE_FAST_MULTI + 15] = COMPUTE_ENTRY(&& entry_MP_BC_STORE_FAST_MULTI), + [MP_BC_UNARY_OP_MULTI ... MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE - 1] = COMPUTE_ENTRY(&& entry_MP_BC_UNARY_OP_MULTI), + [MP_BC_BINARY_OP_MULTI ... MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE - 1] = COMPUTE_ENTRY(&& entry_MP_BC_BINARY_OP_MULTI), }; #ifdef __clang__ diff --git a/py/vstr.c b/py/vstr.c index ccc567d100..2b78fc5c83 100644 --- a/py/vstr.c +++ b/py/vstr.c @@ -50,7 +50,7 @@ void vstr_init(vstr_t *vstr, size_t alloc) { // Init the vstr so it allocs exactly enough ram to hold a null-terminated // string of the given length, and set the length. void vstr_init_len(vstr_t *vstr, size_t len) { - if(len == SIZE_MAX) { + if (len == SIZE_MAX) { m_malloc_fail(len); } vstr_init(vstr, len + 1); @@ -142,37 +142,37 @@ char *vstr_null_terminated_str(vstr_t *vstr) { } void vstr_add_byte(vstr_t *vstr, byte b) { - byte *buf = (byte*)vstr_add_len(vstr, 1); + byte *buf = (byte *)vstr_add_len(vstr, 1); buf[0] = b; } void vstr_add_char(vstr_t *vstr, unichar c) { -#if MICROPY_PY_BUILTINS_STR_UNICODE + #if MICROPY_PY_BUILTINS_STR_UNICODE // TODO: Can this be simplified and deduplicated? // Is it worth just calling vstr_add_len(vstr, 4)? if (c < 0x80) { - byte *buf = (byte*)vstr_add_len(vstr, 1); + byte *buf = (byte *)vstr_add_len(vstr, 1); *buf = (byte)c; } else if (c < 0x800) { - byte *buf = (byte*)vstr_add_len(vstr, 2); + byte *buf = (byte *)vstr_add_len(vstr, 2); buf[0] = (c >> 6) | 0xC0; buf[1] = (c & 0x3F) | 0x80; } else if (c < 0x10000) { - byte *buf = (byte*)vstr_add_len(vstr, 3); + byte *buf = (byte *)vstr_add_len(vstr, 3); buf[0] = (c >> 12) | 0xE0; buf[1] = ((c >> 6) & 0x3F) | 0x80; buf[2] = (c & 0x3F) | 0x80; } else { assert(c < 0x110000); - byte *buf = (byte*)vstr_add_len(vstr, 4); + byte *buf = (byte *)vstr_add_len(vstr, 4); buf[0] = (c >> 18) | 0xF0; buf[1] = ((c >> 12) & 0x3F) | 0x80; buf[2] = ((c >> 6) & 0x3F) | 0x80; buf[3] = (c & 0x3F) | 0x80; } -#else + #else vstr_add_byte(vstr, c); -#endif + #endif } void vstr_add_str(vstr_t *vstr, const char *str) { diff --git a/shared-bindings/_bleio/Adapter.c b/shared-bindings/_bleio/Adapter.c index 81277fd701..5cacfa0691 100644 --- a/shared-bindings/_bleio/Adapter.c +++ b/shared-bindings/_bleio/Adapter.c @@ -82,7 +82,7 @@ //| ... //| STATIC mp_obj_t bleio_adapter_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { -#if CIRCUITPY_BLEIO_HCI + #if CIRCUITPY_BLEIO_HCI bleio_adapter_obj_t *self = common_hal_bleio_allocate_adapter_or_raise(); enum { ARG_uart, ARG_rts, ARG_cts }; @@ -111,10 +111,10 @@ STATIC mp_obj_t bleio_adapter_make_new(const mp_obj_type_t *type, size_t n_args, common_hal_bleio_adapter_construct_hci_uart(self, uart, rts, cts); return MP_OBJ_FROM_PTR(self); -#else + #else mp_raise_NotImplementedError(translate("Cannot create a new Adapter; use _bleio.adapter;")); return mp_const_none; -#endif // CIRCUITPY_BLEIO_HCI + #endif // CIRCUITPY_BLEIO_HCI } //| @@ -240,7 +240,7 @@ STATIC mp_obj_t bleio_adapter_start_advertising(mp_uint_t n_args, const mp_obj_t const mp_float_t interval = mp_obj_get_float(args[ARG_interval].u_obj); if (interval < ADV_INTERVAL_MIN || interval > ADV_INTERVAL_MAX) { mp_raise_ValueError_varg(translate("interval must be in range %s-%s"), - ADV_INTERVAL_MIN_STRING, ADV_INTERVAL_MAX_STRING); + ADV_INTERVAL_MIN_STRING, ADV_INTERVAL_MAX_STRING); } bool connectable = args[ARG_connectable].u_bool; @@ -251,7 +251,7 @@ STATIC mp_obj_t bleio_adapter_start_advertising(mp_uint_t n_args, const mp_obj_t } common_hal_bleio_adapter_start_advertising(self, connectable, anonymous, timeout, interval, - &data_bufinfo, &scan_response_bufinfo); + &data_bufinfo, &scan_response_bufinfo); return mp_const_none; } @@ -325,12 +325,12 @@ STATIC mp_obj_t bleio_adapter_start_scan(size_t n_args, const mp_obj_t *pos_args mp_raise_ValueError_varg(translate("interval must be in range %s-%s"), INTERVAL_MIN_STRING, INTERVAL_MAX_STRING); } -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" if (timeout != 0.0f && timeout < interval) { mp_raise_ValueError(translate("non-zero timeout must be >= interval")); } -#pragma GCC diagnostic pop + #pragma GCC diagnostic pop const mp_float_t window = mp_obj_get_float(args[ARG_window].u_obj); if (window > interval) { diff --git a/shared-bindings/_bleio/Adapter.h b/shared-bindings/_bleio/Adapter.h index ac7e216d83..81b9ec3130 100644 --- a/shared-bindings/_bleio/Adapter.h +++ b/shared-bindings/_bleio/Adapter.h @@ -48,15 +48,15 @@ extern bool common_hal_bleio_adapter_get_connected(bleio_adapter_obj_t *self); extern bleio_address_obj_t *common_hal_bleio_adapter_get_address(bleio_adapter_obj_t *self); extern bool common_hal_bleio_adapter_set_address(bleio_adapter_obj_t *self, bleio_address_obj_t *address); -extern mp_obj_str_t* common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self); -extern void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char* name); +extern mp_obj_str_t *common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self); +extern void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char *name); extern uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool connectable, bool anonymous, uint32_t timeout, float interval, uint8_t *advertising_data, uint16_t advertising_data_len, uint8_t *scan_response_data, uint16_t scan_response_data_len); extern void common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool connectable, bool anonymous, uint32_t timeout, mp_float_t interval, mp_buffer_info_t *advertising_data_bufinfo, mp_buffer_info_t *scan_response_data_bufinfo); extern void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self); -extern mp_obj_t common_hal_bleio_adapter_start_scan(bleio_adapter_obj_t *self, uint8_t* prefixes, size_t prefix_length, bool extended, mp_int_t buffer_size, mp_float_t timeout, mp_float_t interval, mp_float_t window, mp_int_t minimum_rssi, bool active); +extern mp_obj_t common_hal_bleio_adapter_start_scan(bleio_adapter_obj_t *self, uint8_t *prefixes, size_t prefix_length, bool extended, mp_int_t buffer_size, mp_float_t timeout, mp_float_t interval, mp_float_t window, mp_int_t minimum_rssi, bool active); extern void common_hal_bleio_adapter_stop_scan(bleio_adapter_obj_t *self); extern bool common_hal_bleio_adapter_get_connected(bleio_adapter_obj_t *self); diff --git a/shared-bindings/_bleio/Address.c b/shared-bindings/_bleio/Address.c index 04c667db44..56e8a013ff 100644 --- a/shared-bindings/_bleio/Address.c +++ b/shared-bindings/_bleio/Address.c @@ -141,7 +141,7 @@ STATIC mp_obj_t bleio_address_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_o bleio_address_obj_t *rhs = MP_OBJ_TO_PTR(rhs_in); return mp_obj_new_bool( mp_obj_equal(common_hal_bleio_address_get_address_bytes(lhs), - common_hal_bleio_address_get_address_bytes(rhs)) && + common_hal_bleio_address_get_address_bytes(rhs)) && common_hal_bleio_address_get_type(lhs) == common_hal_bleio_address_get_type(rhs)); @@ -182,9 +182,9 @@ STATIC void bleio_address_print(const mp_print_t *print, mp_obj_t self_in, mp_pr mp_obj_t address_bytes = common_hal_bleio_address_get_address_bytes(self); mp_get_buffer_raise(address_bytes, &buf_info, MP_BUFFER_READ); - const uint8_t *buf = (uint8_t *) buf_info.buf; + const uint8_t *buf = (uint8_t *)buf_info.buf; mp_printf(print, "
", - buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); + buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } //| PUBLIC: int @@ -220,5 +220,5 @@ const mp_obj_type_t bleio_address_type = { .print = bleio_address_print, .unary_op = bleio_address_unary_op, .binary_op = bleio_address_binary_op, - .locals_dict = (mp_obj_dict_t*)&bleio_address_locals_dict + .locals_dict = (mp_obj_dict_t *)&bleio_address_locals_dict }; diff --git a/shared-bindings/_bleio/Attribute.c b/shared-bindings/_bleio/Attribute.c index 2c144c71b9..d639f2a421 100644 --- a/shared-bindings/_bleio/Attribute.c +++ b/shared-bindings/_bleio/Attribute.c @@ -78,5 +78,5 @@ STATIC MP_DEFINE_CONST_DICT(bleio_attribute_locals_dict, bleio_attribute_locals_ const mp_obj_type_t bleio_attribute_type = { { &mp_type_type }, .name = MP_QSTR_Attribute, - .locals_dict = (mp_obj_dict_t*)&bleio_attribute_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bleio_attribute_locals_dict, }; diff --git a/shared-bindings/_bleio/Characteristic.c b/shared-bindings/_bleio/Characteristic.c index a0751b7e34..0aa832cf21 100644 --- a/shared-bindings/_bleio/Characteristic.c +++ b/shared-bindings/_bleio/Characteristic.c @@ -77,12 +77,12 @@ STATIC mp_obj_t bleio_characteristic_add_to_service(size_t n_args, const mp_obj_ static const mp_arg_t allowed_args[] = { { MP_QSTR_service, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_uuid, MP_ARG_REQUIRED | MP_ARG_OBJ }, - { MP_QSTR_properties, MP_ARG_KW_ONLY| MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_read_perm, MP_ARG_KW_ONLY| MP_ARG_INT, {.u_int = SECURITY_MODE_OPEN} }, - { MP_QSTR_write_perm, MP_ARG_KW_ONLY| MP_ARG_INT, {.u_int = SECURITY_MODE_OPEN} }, - { MP_QSTR_max_length, MP_ARG_KW_ONLY| MP_ARG_INT, {.u_int = 20} }, - { MP_QSTR_fixed_length, MP_ARG_KW_ONLY| MP_ARG_BOOL, {.u_bool = false} }, - { MP_QSTR_initial_value, MP_ARG_KW_ONLY| MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_properties, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_read_perm, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = SECURITY_MODE_OPEN} }, + { MP_QSTR_write_perm, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = SECURITY_MODE_OPEN} }, + { MP_QSTR_max_length, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 20} }, + { MP_QSTR_fixed_length, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_initial_value, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -113,8 +113,8 @@ STATIC mp_obj_t bleio_characteristic_add_to_service(size_t n_args, const mp_obj_ if (max_length_int < 0) { mp_raise_ValueError(translate("max_length must be >= 0")); } - const size_t max_length = (size_t) max_length_int; - const bool fixed_length = args[ARG_fixed_length].u_bool; + const size_t max_length = (size_t)max_length_int; + const bool fixed_length = args[ARG_fixed_length].u_bool; mp_obj_t initial_value = args[ARG_initial_value].u_obj; mp_buffer_info_t initial_value_bufinfo; @@ -129,7 +129,7 @@ STATIC mp_obj_t bleio_characteristic_add_to_service(size_t n_args, const mp_obj_ mp_get_buffer_raise(initial_value, &initial_value_bufinfo, MP_BUFFER_READ); if (initial_value_bufinfo.len > max_length || (fixed_length && initial_value_bufinfo.len != max_length)) { - mp_raise_ValueError(translate("initial_value length is wrong")); + mp_raise_ValueError(translate("initial_value length is wrong")); } bleio_characteristic_obj_t *characteristic = m_new_obj(bleio_characteristic_obj_t); @@ -330,5 +330,5 @@ const mp_obj_type_t bleio_characteristic_type = { { &mp_type_type }, .name = MP_QSTR_Characteristic, .print = bleio_characteristic_print, - .locals_dict = (mp_obj_dict_t*)&bleio_characteristic_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bleio_characteristic_locals_dict, }; diff --git a/shared-bindings/_bleio/Characteristic.h b/shared-bindings/_bleio/Characteristic.h index e28d61e1f0..a8486866f9 100644 --- a/shared-bindings/_bleio/Characteristic.h +++ b/shared-bindings/_bleio/Characteristic.h @@ -40,7 +40,7 @@ extern bleio_characteristic_properties_t common_hal_bleio_characteristic_get_pro extern mp_obj_tuple_t *common_hal_bleio_characteristic_get_descriptors(bleio_characteristic_obj_t *self); extern bleio_service_obj_t *common_hal_bleio_characteristic_get_service(bleio_characteristic_obj_t *self); extern bleio_uuid_obj_t *common_hal_bleio_characteristic_get_uuid(bleio_characteristic_obj_t *self); -extern size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t* buf, size_t len); +extern size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *self, uint8_t *buf, size_t len); extern void common_hal_bleio_characteristic_add_descriptor(bleio_characteristic_obj_t *self, bleio_descriptor_obj_t *descriptor); extern void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, bleio_service_obj_t *service, uint16_t handle, bleio_uuid_obj_t *uuid, bleio_characteristic_properties_t props, bleio_attribute_security_mode_t read_perm, bleio_attribute_security_mode_t write_perm, mp_int_t max_length, bool fixed_length, mp_buffer_info_t *initial_value_bufinfo); extern void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, bool notify, bool indicate); diff --git a/shared-bindings/_bleio/CharacteristicBuffer.c b/shared-bindings/_bleio/CharacteristicBuffer.c index 333b275ffb..ddc0c42253 100644 --- a/shared-bindings/_bleio/CharacteristicBuffer.c +++ b/shared-bindings/_bleio/CharacteristicBuffer.c @@ -243,5 +243,5 @@ const mp_obj_type_t bleio_characteristic_buffer_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &characteristic_buffer_stream_p, - .locals_dict = (mp_obj_dict_t*)&bleio_characteristic_buffer_locals_dict + .locals_dict = (mp_obj_dict_t *)&bleio_characteristic_buffer_locals_dict }; diff --git a/shared-bindings/_bleio/Connection.c b/shared-bindings/_bleio/Connection.c index fe82af098f..b714f42dfd 100644 --- a/shared-bindings/_bleio/Connection.c +++ b/shared-bindings/_bleio/Connection.c @@ -146,8 +146,8 @@ STATIC mp_obj_t bleio_connection_discover_remote_services(mp_uint_t n_args, cons bleio_connection_ensure_connected(self); return MP_OBJ_FROM_PTR(common_hal_bleio_connection_discover_remote_services( - self, - args[ARG_service_uuids_whitelist].u_obj)); + self, + args[ARG_service_uuids_whitelist].u_obj)); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(bleio_connection_discover_remote_services_obj, 1, bleio_connection_discover_remote_services); @@ -267,6 +267,6 @@ STATIC MP_DEFINE_CONST_DICT(bleio_connection_locals_dict, bleio_connection_local const mp_obj_type_t bleio_connection_type = { { &mp_type_type }, .name = MP_QSTR_Connection, - .locals_dict = (mp_obj_dict_t*)&bleio_connection_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bleio_connection_locals_dict, .unary_op = mp_generic_unary_op, }; diff --git a/shared-bindings/_bleio/Descriptor.c b/shared-bindings/_bleio/Descriptor.c index 60f0acf44b..0eee9d7040 100644 --- a/shared-bindings/_bleio/Descriptor.c +++ b/shared-bindings/_bleio/Descriptor.c @@ -74,11 +74,11 @@ STATIC mp_obj_t bleio_descriptor_add_to_characteristic(size_t n_args, const mp_o static const mp_arg_t allowed_args[] = { { MP_QSTR_characteristic, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_uuid, MP_ARG_REQUIRED | MP_ARG_OBJ }, - { MP_QSTR_read_perm, MP_ARG_KW_ONLY| MP_ARG_INT, {.u_int = SECURITY_MODE_OPEN} }, - { MP_QSTR_write_perm, MP_ARG_KW_ONLY| MP_ARG_INT, {.u_int = SECURITY_MODE_OPEN} }, - { MP_QSTR_max_length, MP_ARG_KW_ONLY| MP_ARG_INT, {.u_int = 20} }, - { MP_QSTR_fixed_length, MP_ARG_KW_ONLY| MP_ARG_BOOL, {.u_bool = false} }, - { MP_QSTR_initial_value, MP_ARG_KW_ONLY| MP_ARG_OBJ, {.u_obj = mp_const_empty_bytes} }, + { MP_QSTR_read_perm, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = SECURITY_MODE_OPEN} }, + { MP_QSTR_write_perm, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = SECURITY_MODE_OPEN} }, + { MP_QSTR_max_length, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 20} }, + { MP_QSTR_fixed_length, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_initial_value, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_empty_bytes} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -104,8 +104,8 @@ STATIC mp_obj_t bleio_descriptor_add_to_characteristic(size_t n_args, const mp_o if (max_length_int < 0) { mp_raise_ValueError(translate("max_length must be >= 0")); } - const size_t max_length = (size_t) max_length_int; - const bool fixed_length = args[ARG_fixed_length].u_bool; + const size_t max_length = (size_t)max_length_int; + const bool fixed_length = args[ARG_fixed_length].u_bool; mp_obj_t initial_value = args[ARG_initial_value].u_obj; mp_buffer_info_t initial_value_bufinfo; @@ -119,7 +119,7 @@ STATIC mp_obj_t bleio_descriptor_add_to_characteristic(size_t n_args, const mp_o mp_get_buffer_raise(initial_value, &initial_value_bufinfo, MP_BUFFER_READ); if (initial_value_bufinfo.len > max_length || (fixed_length && initial_value_bufinfo.len != max_length)) { - mp_raise_ValueError(translate("initial_value length is wrong")); + mp_raise_ValueError(translate("initial_value length is wrong")); } bleio_descriptor_obj_t *descriptor = m_new_obj(bleio_descriptor_obj_t); @@ -229,5 +229,5 @@ const mp_obj_type_t bleio_descriptor_type = { { &mp_type_type }, .name = MP_QSTR_Descriptor, .print = bleio_descriptor_print, - .locals_dict = (mp_obj_dict_t*)&bleio_descriptor_locals_dict + .locals_dict = (mp_obj_dict_t *)&bleio_descriptor_locals_dict }; diff --git a/shared-bindings/_bleio/Descriptor.h b/shared-bindings/_bleio/Descriptor.h index 273cb1c1e3..bda381e3d4 100644 --- a/shared-bindings/_bleio/Descriptor.h +++ b/shared-bindings/_bleio/Descriptor.h @@ -38,7 +38,7 @@ extern const mp_obj_type_t bleio_descriptor_type; extern void common_hal_bleio_descriptor_construct(bleio_descriptor_obj_t *self, bleio_characteristic_obj_t *characteristic, bleio_uuid_obj_t *uuid, bleio_attribute_security_mode_t read_perm, bleio_attribute_security_mode_t write_perm, mp_int_t max_length, bool fixed_length, mp_buffer_info_t *initial_value_bufinfo); extern bleio_uuid_obj_t *common_hal_bleio_descriptor_get_uuid(bleio_descriptor_obj_t *self); extern bleio_characteristic_obj_t *common_hal_bleio_descriptor_get_characteristic(bleio_descriptor_obj_t *self); -extern size_t common_hal_bleio_descriptor_get_value(bleio_descriptor_obj_t *self, uint8_t* buf, size_t len); +extern size_t common_hal_bleio_descriptor_get_value(bleio_descriptor_obj_t *self, uint8_t *buf, size_t len); extern void common_hal_bleio_descriptor_set_value(bleio_descriptor_obj_t *self, mp_buffer_info_t *bufinfo); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_BLEIO_DESCRIPTOR_H diff --git a/shared-bindings/_bleio/PacketBuffer.c b/shared-bindings/_bleio/PacketBuffer.c index f2a3cbce07..16ad02a461 100644 --- a/shared-bindings/_bleio/PacketBuffer.c +++ b/shared-bindings/_bleio/PacketBuffer.c @@ -247,5 +247,5 @@ const mp_obj_type_t bleio_packet_buffer_type = { { &mp_type_type }, .name = MP_QSTR_PacketBuffer, .make_new = bleio_packet_buffer_make_new, - .locals_dict = (mp_obj_dict_t*)&bleio_packet_buffer_locals_dict + .locals_dict = (mp_obj_dict_t *)&bleio_packet_buffer_locals_dict }; diff --git a/shared-bindings/_bleio/PacketBuffer.h b/shared-bindings/_bleio/PacketBuffer.h index 769e0a0c78..65ce3ded1f 100644 --- a/shared-bindings/_bleio/PacketBuffer.h +++ b/shared-bindings/_bleio/PacketBuffer.h @@ -34,7 +34,7 @@ extern const mp_obj_type_t bleio_packet_buffer_type; extern void common_hal_bleio_packet_buffer_construct( bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, size_t buffer_size); -mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len, uint8_t* header, size_t header_len); +mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len, uint8_t *header, size_t header_len); mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self, uint8_t *data, size_t len); mp_int_t common_hal_bleio_packet_buffer_get_incoming_packet_length(bleio_packet_buffer_obj_t *self); mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length(bleio_packet_buffer_obj_t *self); diff --git a/shared-bindings/_bleio/ScanEntry.c b/shared-bindings/_bleio/ScanEntry.c index 4f07890190..5692e3db25 100644 --- a/shared-bindings/_bleio/ScanEntry.c +++ b/shared-bindings/_bleio/ScanEntry.c @@ -164,5 +164,5 @@ STATIC MP_DEFINE_CONST_DICT(bleio_scanentry_locals_dict, bleio_scanentry_locals_ const mp_obj_type_t bleio_scanentry_type = { { &mp_type_type }, .name = MP_QSTR_ScanEntry, - .locals_dict = (mp_obj_dict_t*)&bleio_scanentry_locals_dict + .locals_dict = (mp_obj_dict_t *)&bleio_scanentry_locals_dict }; diff --git a/shared-bindings/_bleio/ScanEntry.h b/shared-bindings/_bleio/ScanEntry.h index 9aeaf20d33..b37cb61097 100644 --- a/shared-bindings/_bleio/ScanEntry.h +++ b/shared-bindings/_bleio/ScanEntry.h @@ -39,6 +39,6 @@ mp_obj_t common_hal_bleio_scanentry_get_advertisement_bytes(bleio_scanentry_obj_ mp_int_t common_hal_bleio_scanentry_get_rssi(bleio_scanentry_obj_t *self); bool common_hal_bleio_scanentry_get_connectable(bleio_scanentry_obj_t *self); bool common_hal_bleio_scanentry_get_scan_response(bleio_scanentry_obj_t *self); -bool common_hal_bleio_scanentry_matches(bleio_scanentry_obj_t *self, uint8_t* prefixes, size_t prefixes_len, bool all); +bool common_hal_bleio_scanentry_matches(bleio_scanentry_obj_t *self, uint8_t *prefixes, size_t prefixes_len, bool all); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_BLEIO_SCANENTRY_H diff --git a/shared-bindings/_bleio/Service.c b/shared-bindings/_bleio/Service.c index 2ddf1a7126..6657c7e73f 100644 --- a/shared-bindings/_bleio/Service.c +++ b/shared-bindings/_bleio/Service.c @@ -169,5 +169,5 @@ const mp_obj_type_t bleio_service_type = { .name = MP_QSTR_Service, .make_new = bleio_service_make_new, .print = bleio_service_print, - .locals_dict = (mp_obj_dict_t*)&bleio_service_locals_dict + .locals_dict = (mp_obj_dict_t *)&bleio_service_locals_dict }; diff --git a/shared-bindings/_bleio/Service.h b/shared-bindings/_bleio/Service.h index 44d11f60d4..b2a35793fb 100644 --- a/shared-bindings/_bleio/Service.h +++ b/shared-bindings/_bleio/Service.h @@ -37,9 +37,9 @@ extern const mp_obj_type_t bleio_service_type; // Private version that doesn't allocate on the heap -extern uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary, mp_obj_list_t * characteristic_list); +extern uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary, mp_obj_list_t *characteristic_list); extern void common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_obj_t *uuid, bool is_secondary); -extern void common_hal_bleio_service_from_remote_service(bleio_service_obj_t *self, bleio_connection_obj_t* connection, bleio_uuid_obj_t *uuid, bool is_secondary); +extern void common_hal_bleio_service_from_remote_service(bleio_service_obj_t *self, bleio_connection_obj_t *connection, bleio_uuid_obj_t *uuid, bool is_secondary); extern bleio_uuid_obj_t *common_hal_bleio_service_get_uuid(bleio_service_obj_t *self); extern mp_obj_tuple_t *common_hal_bleio_service_get_characteristics(bleio_service_obj_t *self); extern bool common_hal_bleio_service_get_is_remote(bleio_service_obj_t *self); diff --git a/shared-bindings/_bleio/UUID.c b/shared-bindings/_bleio/UUID.c index fe045f3853..2da54c1d5d 100644 --- a/shared-bindings/_bleio/UUID.c +++ b/shared-bindings/_bleio/UUID.c @@ -228,23 +228,23 @@ STATIC MP_DEFINE_CONST_DICT(bleio_uuid_locals_dict, bleio_uuid_locals_dict_table STATIC mp_obj_t bleio_uuid_unary_op(mp_unary_op_t op, mp_obj_t self_in) { bleio_uuid_obj_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { - case MP_UNARY_OP_HASH: - if (common_hal_bleio_uuid_get_size(self) == 16) { - return MP_OBJ_NEW_SMALL_INT(common_hal_bleio_uuid_get_uuid16(self)); - } else { - union { - uint8_t uuid128_bytes[16]; - uint16_t uuid128_uint16[8]; - } uuid128; - common_hal_bleio_uuid_get_uuid128(self, uuid128.uuid128_bytes); - int hash = 0; - for (size_t i = 0; i < MP_ARRAY_SIZE(uuid128.uuid128_uint16); i++) { - hash += uuid128.uuid128_uint16[i]; + case MP_UNARY_OP_HASH: + if (common_hal_bleio_uuid_get_size(self) == 16) { + return MP_OBJ_NEW_SMALL_INT(common_hal_bleio_uuid_get_uuid16(self)); + } else { + union { + uint8_t uuid128_bytes[16]; + uint16_t uuid128_uint16[8]; + } uuid128; + common_hal_bleio_uuid_get_uuid128(self, uuid128.uuid128_bytes); + int hash = 0; + for (size_t i = 0; i < MP_ARRAY_SIZE(uuid128.uuid128_uint16); i++) { + hash += uuid128.uuid128_uint16[i]; + } + return MP_OBJ_NEW_SMALL_INT(hash); } - return MP_OBJ_NEW_SMALL_INT(hash); - } - default: - return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -260,7 +260,7 @@ STATIC mp_obj_t bleio_uuid_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_ if (common_hal_bleio_uuid_get_size(lhs_in) == 16 && common_hal_bleio_uuid_get_size(rhs_in) == 16) { return mp_obj_new_bool(common_hal_bleio_uuid_get_uuid16(lhs_in) == - common_hal_bleio_uuid_get_uuid16(rhs_in)); + common_hal_bleio_uuid_get_uuid16(rhs_in)); } uint8_t lhs[16]; uint8_t rhs[16]; @@ -285,16 +285,16 @@ void bleio_uuid_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t uint8_t uuid128[16]; common_hal_bleio_uuid_get_uuid128(self, uuid128); mp_printf(print, "UUID('" - "%02x%02x%02x%02x-" - "%02x%02x-" - "%02x%02x-" - "%02x%02x-" - "%02x%02x%02x%02x%02x%02x')", - uuid128[15], uuid128[14], uuid128[13], uuid128[12], - uuid128[11], uuid128[10], - uuid128[9], uuid128[8], - uuid128[7], uuid128[6], - uuid128[5], uuid128[4], uuid128[3], uuid128[2], uuid128[1], uuid128[0]); + "%02x%02x%02x%02x-" + "%02x%02x-" + "%02x%02x-" + "%02x%02x-" + "%02x%02x%02x%02x%02x%02x')", + uuid128[15], uuid128[14], uuid128[13], uuid128[12], + uuid128[11], uuid128[10], + uuid128[9], uuid128[8], + uuid128[7], uuid128[6], + uuid128[5], uuid128[4], uuid128[3], uuid128[2], uuid128[1], uuid128[0]); } } @@ -305,5 +305,5 @@ const mp_obj_type_t bleio_uuid_type = { .make_new = bleio_uuid_make_new, .unary_op = bleio_uuid_unary_op, .binary_op = bleio_uuid_binary_op, - .locals_dict = (mp_obj_dict_t*)&bleio_uuid_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bleio_uuid_locals_dict, }; diff --git a/shared-bindings/_bleio/UUID.h b/shared-bindings/_bleio/UUID.h index b10cce67f3..d07e903803 100644 --- a/shared-bindings/_bleio/UUID.h +++ b/shared-bindings/_bleio/UUID.h @@ -39,6 +39,6 @@ extern uint32_t common_hal_bleio_uuid_get_uuid16(bleio_uuid_obj_t *self); extern void common_hal_bleio_uuid_get_uuid128(bleio_uuid_obj_t *self, uint8_t uuid128[16]); extern uint32_t common_hal_bleio_uuid_get_size(bleio_uuid_obj_t *self); -void common_hal_bleio_uuid_pack_into(bleio_uuid_obj_t *self, uint8_t* buf); +void common_hal_bleio_uuid_pack_into(bleio_uuid_obj_t *self, uint8_t *buf); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_BLEIO_UUID_H diff --git a/shared-bindings/_bleio/__init__.c b/shared-bindings/_bleio/__init__.c index 2ef70a64f7..b9d68abaed 100644 --- a/shared-bindings/_bleio/__init__.c +++ b/shared-bindings/_bleio/__init__.c @@ -63,7 +63,7 @@ //| """Catchall exception for Bluetooth related errors.""" //| ... MP_DEFINE_BLEIO_EXCEPTION(BluetoothError, Exception) -NORETURN void mp_raise_bleio_BluetoothError(const compressed_string_t* fmt, ...) { +NORETURN void mp_raise_bleio_BluetoothError(const compressed_string_t *fmt, ...) { va_list argptr; va_start(argptr,fmt); mp_obj_t exception = mp_obj_new_exception_msg_vlist(&mp_type_bleio_BluetoothError, fmt, argptr); @@ -77,7 +77,7 @@ NORETURN void mp_raise_bleio_BluetoothError(const compressed_string_t* fmt, ...) //| ... //| MP_DEFINE_BLEIO_EXCEPTION(RoleError, bleio_BluetoothError) -NORETURN void mp_raise_bleio_RoleError(const compressed_string_t* msg) { +NORETURN void mp_raise_bleio_RoleError(const compressed_string_t *msg) { mp_raise_msg(&mp_type_bleio_RoleError, msg); } @@ -86,7 +86,7 @@ NORETURN void mp_raise_bleio_RoleError(const compressed_string_t* msg) { //| ... //| MP_DEFINE_BLEIO_EXCEPTION(SecurityError, bleio_BluetoothError) -NORETURN void mp_raise_bleio_SecurityError(const compressed_string_t* fmt, ...) { +NORETURN void mp_raise_bleio_SecurityError(const compressed_string_t *fmt, ...) { va_list argptr; va_start(argptr,fmt); mp_obj_t exception = mp_obj_new_exception_msg_vlist(&mp_type_bleio_SecurityError, fmt, argptr); @@ -97,9 +97,9 @@ NORETURN void mp_raise_bleio_SecurityError(const compressed_string_t* fmt, ...) // Called when _bleio is imported. STATIC mp_obj_t bleio___init__(void) { // HCI cannot be enabled on import, because we need to setup the HCI adapter first. -#if !CIRCUITPY_BLEIO_HCI + #if !CIRCUITPY_BLEIO_HCI common_hal_bleio_adapter_set_enabled(&common_hal_bleio_adapter_obj, true); -#endif + #endif return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_0(bleio___init___obj, bleio___init__); @@ -116,7 +116,7 @@ STATIC mp_obj_dict_t bleio_module_globals; //| ... //| mp_obj_t bleio_set_adapter(mp_obj_t adapter_obj) { -#if CIRCUITPY_BLEIO_HCI + #if CIRCUITPY_BLEIO_HCI if (adapter_obj != mp_const_none && !MP_OBJ_IS_TYPE(adapter_obj, &bleio_adapter_type)) { mp_raise_TypeError_varg(translate("Expected a %q"), bleio_adapter_type.name); } @@ -127,9 +127,9 @@ mp_obj_t bleio_set_adapter(mp_obj_t adapter_obj) { if (elem) { elem->value = adapter_obj; } -#else + #else mp_raise_NotImplementedError(translate("Not settable")); -#endif + #endif return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(bleio_set_adapter_obj, bleio_set_adapter); @@ -142,7 +142,7 @@ STATIC mp_map_elem_t bleio_module_globals_table[] = { #else #define OBJ_FROM_PTR MP_ROM_PTR STATIC const mp_rom_map_elem_t bleio_module_globals_table[] = { -#endif + #endif // Name must be the first entry so that the exception printing below is correct. { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__bleio) }, { MP_ROM_QSTR(MP_QSTR_Adapter), OBJ_FROM_PTR(&bleio_adapter_type) }, @@ -158,16 +158,16 @@ STATIC const mp_rom_map_elem_t bleio_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_Service), OBJ_FROM_PTR(&bleio_service_type) }, { MP_ROM_QSTR(MP_QSTR_UUID), OBJ_FROM_PTR(&bleio_uuid_type) }, -#if CIRCUITPY_BLEIO_HCI + #if CIRCUITPY_BLEIO_HCI // For HCI, _bleio.adapter is settable, and starts as None. { MP_ROM_QSTR(MP_QSTR_adapter), mp_const_none }, - { MP_ROM_QSTR(MP_QSTR_set_adapter), (mp_obj_t) &bleio_set_adapter_obj }, -#else + { MP_ROM_QSTR(MP_QSTR_set_adapter), (mp_obj_t)&bleio_set_adapter_obj }, + #else // For non-HCI _bleio.adapter is a fixed singleton, and is not settable. // _bleio.set_adapter will raise NotImplementedError. { MP_ROM_QSTR(MP_QSTR_adapter), MP_ROM_PTR(&common_hal_bleio_adapter_obj) }, { MP_ROM_QSTR(MP_QSTR_set_adapter), MP_ROM_PTR(&bleio_set_adapter_obj) }, -#endif + #endif // Errors { MP_ROM_QSTR(MP_QSTR_BluetoothError), OBJ_FROM_PTR(&mp_type_bleio_BluetoothError) }, @@ -197,5 +197,5 @@ void bleio_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind const mp_obj_module_t bleio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&bleio_module_globals, + .globals = (mp_obj_dict_t *)&bleio_module_globals, }; diff --git a/shared-bindings/_bleio/__init__.h b/shared-bindings/_bleio/__init__.h index 65ba9b3a5d..7f251ef188 100644 --- a/shared-bindings/_bleio/__init__.h +++ b/shared-bindings/_bleio/__init__.h @@ -41,14 +41,14 @@ extern bleio_adapter_obj_t common_hal_bleio_adapter_obj; void bleio_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind); #define MP_DEFINE_BLEIO_EXCEPTION(exc_name, base_name) \ -const mp_obj_type_t mp_type_bleio_ ## exc_name = { \ - { &mp_type_type }, \ - .name = MP_QSTR_ ## exc_name, \ - .print = bleio_exception_print, \ - .make_new = mp_obj_exception_make_new, \ - .attr = mp_obj_exception_attr, \ - .parent = &mp_type_ ## base_name, \ -}; + const mp_obj_type_t mp_type_bleio_##exc_name = { \ + { &mp_type_type }, \ + .name = MP_QSTR_##exc_name, \ + .print = bleio_exception_print, \ + .make_new = mp_obj_exception_make_new, \ + .attr = mp_obj_exception_attr, \ + .parent = &mp_type_##base_name, \ + }; extern const mp_obj_type_t mp_type_bleio_BluetoothError; extern const mp_obj_type_t mp_type_bleio_RoleError; @@ -56,9 +56,9 @@ extern const mp_obj_type_t mp_type_bleio_SecurityError; extern mp_obj_t bleio_set_adapter(mp_obj_t adapter_obj); -NORETURN void mp_raise_bleio_BluetoothError(const compressed_string_t* msg, ...); -NORETURN void mp_raise_bleio_RoleError(const compressed_string_t* msg); -NORETURN void mp_raise_bleio_SecurityError(const compressed_string_t* msg, ...); +NORETURN void mp_raise_bleio_BluetoothError(const compressed_string_t *msg, ...); +NORETURN void mp_raise_bleio_RoleError(const compressed_string_t *msg); +NORETURN void mp_raise_bleio_SecurityError(const compressed_string_t *msg, ...); bleio_adapter_obj_t *common_hal_bleio_allocate_adapter_or_raise(void); void common_hal_bleio_check_connected(uint16_t conn_handle); @@ -66,9 +66,9 @@ void common_hal_bleio_check_connected(uint16_t conn_handle); uint16_t common_hal_bleio_device_get_conn_handle(mp_obj_t device); void common_hal_bleio_device_discover_remote_services(mp_obj_t device, mp_obj_t service_uuids_whitelist); -size_t common_hal_bleio_gatts_read(uint16_t handle, uint16_t conn_handle, uint8_t* buf, size_t len); +size_t common_hal_bleio_gatts_read(uint16_t handle, uint16_t conn_handle, uint8_t *buf, size_t len); void common_hal_bleio_gatts_write(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo); -size_t common_hal_bleio_gattc_read(uint16_t handle, uint16_t conn_handle, uint8_t* buf, size_t len); +size_t common_hal_bleio_gattc_read(uint16_t handle, uint16_t conn_handle, uint8_t *buf, size_t len); void common_hal_bleio_gattc_write(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo, bool write_no_response); void common_hal_bleio_gc_collect(void); diff --git a/shared-bindings/_eve/__init__.c b/shared-bindings/_eve/__init__.c index c043aa5fae..3e2591621a 100644 --- a/shared-bindings/_eve/__init__.c +++ b/shared-bindings/_eve/__init__.c @@ -52,7 +52,7 @@ typedef struct _mp_obj__EVE_t { STATIC const mp_obj_type_t _EVE_type; #define EVEHAL(s) \ - (&((mp_obj__EVE_t*)mp_instance_cast_to_native_base((s), &_EVE_type))->_eve) + (&((mp_obj__EVE_t *)mp_instance_cast_to_native_base((s), &_EVE_type))->_eve) //| def register(self, o: object) -> None: //| ... @@ -90,7 +90,7 @@ STATIC mp_obj_t _cc(mp_obj_t self, mp_obj_t b) { } STATIC MP_DEFINE_CONST_FUN_OBJ_2(cc_obj, _cc); -//{ +// { //| def AlphaFunc(self, func: int, ref: int) -> None: //| """Set the alpha test function @@ -103,8 +103,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(cc_obj, _cc); //| STATIC mp_obj_t _alphafunc(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t func = mp_obj_get_int_truncated(a0); - uint32_t ref = mp_obj_get_int_truncated(a1); + uint32_t func = mp_obj_get_int_truncated(a0); + uint32_t ref = mp_obj_get_int_truncated(a1); common_hal__eve_AlphaFunc(EVEHAL(self), func, ref); return mp_const_none; } @@ -120,7 +120,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(alphafunc_obj, _alphafunc); //| STATIC mp_obj_t _begin(mp_obj_t self, mp_obj_t a0) { - uint32_t prim = mp_obj_get_int_truncated(a0); + uint32_t prim = mp_obj_get_int_truncated(a0); common_hal__eve_Begin(EVEHAL(self), prim); return mp_const_none; } @@ -134,7 +134,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(begin_obj, _begin); //| STATIC mp_obj_t _bitmapextformat(mp_obj_t self, mp_obj_t a0) { - uint32_t fmt = mp_obj_get_int_truncated(a0); + uint32_t fmt = mp_obj_get_int_truncated(a0); common_hal__eve_BitmapExtFormat(EVEHAL(self), fmt); return mp_const_none; } @@ -199,7 +199,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bitmaplayout_obj, 4, 4, _bitmaplayout //| STATIC mp_obj_t _bitmapsizeh(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t width = mp_obj_get_int_truncated(a0); + uint32_t width = mp_obj_get_int_truncated(a0); uint32_t height = mp_obj_get_int_truncated(a1); common_hal__eve_BitmapSizeH(EVEHAL(self), width, height); return mp_const_none; @@ -219,9 +219,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(bitmapsizeh_obj, _bitmapsizeh); STATIC mp_obj_t _bitmapsize(size_t n_args, const mp_obj_t *args) { uint32_t filter = mp_obj_get_int_truncated(args[1]); - uint32_t wrapx = mp_obj_get_int_truncated(args[2]); - uint32_t wrapy = mp_obj_get_int_truncated(args[3]); - uint32_t width = mp_obj_get_int_truncated(args[4]); + uint32_t wrapx = mp_obj_get_int_truncated(args[2]); + uint32_t wrapy = mp_obj_get_int_truncated(args[3]); + uint32_t width = mp_obj_get_int_truncated(args[4]); uint32_t height = mp_obj_get_int_truncated(args[5]); common_hal__eve_BitmapSize(EVEHAL(args[0]), filter, wrapx, wrapy, width, height); return mp_const_none; @@ -236,7 +236,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bitmapsize_obj, 6, 6, _bitmapsize); //| STATIC mp_obj_t _bitmapsource(mp_obj_t self, mp_obj_t a0) { - uint32_t addr = mp_obj_get_int_truncated(a0); + uint32_t addr = mp_obj_get_int_truncated(a0); common_hal__eve_BitmapSource(EVEHAL(self), addr); return mp_const_none; } @@ -253,10 +253,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(bitmapsource_obj, _bitmapsource); //| STATIC mp_obj_t _bitmapswizzle(size_t n_args, const mp_obj_t *args) { - uint32_t r = mp_obj_get_int_truncated(args[1]); - uint32_t g = mp_obj_get_int_truncated(args[2]); - uint32_t b = mp_obj_get_int_truncated(args[3]); - uint32_t a = mp_obj_get_int_truncated(args[4]); + uint32_t r = mp_obj_get_int_truncated(args[1]); + uint32_t g = mp_obj_get_int_truncated(args[2]); + uint32_t b = mp_obj_get_int_truncated(args[3]); + uint32_t a = mp_obj_get_int_truncated(args[4]); common_hal__eve_BitmapSwizzle(EVEHAL(args[0]), r, g, b, a); return mp_const_none; } @@ -275,8 +275,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(bitmapswizzle_obj, 5, 5, _bitmapswizz //| STATIC mp_obj_t _bitmaptransforma(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t p = mp_obj_get_int_truncated(a0); - uint32_t v = mp_obj_get_int_truncated(a1); + uint32_t p = mp_obj_get_int_truncated(a0); + uint32_t v = mp_obj_get_int_truncated(a1); common_hal__eve_BitmapTransformA(EVEHAL(self), p, v); return mp_const_none; } @@ -295,8 +295,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(bitmaptransforma_obj, _bitmaptransforma); //| STATIC mp_obj_t _bitmaptransformb(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t p = mp_obj_get_int_truncated(a0); - uint32_t v = mp_obj_get_int_truncated(a1); + uint32_t p = mp_obj_get_int_truncated(a0); + uint32_t v = mp_obj_get_int_truncated(a1); common_hal__eve_BitmapTransformB(EVEHAL(self), p, v); return mp_const_none; } @@ -312,7 +312,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(bitmaptransformb_obj, _bitmaptransformb); //| STATIC mp_obj_t _bitmaptransformc(mp_obj_t self, mp_obj_t a0) { - uint32_t v = mp_obj_get_int_truncated(a0); + uint32_t v = mp_obj_get_int_truncated(a0); common_hal__eve_BitmapTransformC(EVEHAL(self), v); return mp_const_none; } @@ -331,8 +331,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(bitmaptransformc_obj, _bitmaptransformc); //| STATIC mp_obj_t _bitmaptransformd(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t p = mp_obj_get_int_truncated(a0); - uint32_t v = mp_obj_get_int_truncated(a1); + uint32_t p = mp_obj_get_int_truncated(a0); + uint32_t v = mp_obj_get_int_truncated(a1); common_hal__eve_BitmapTransformD(EVEHAL(self), p, v); return mp_const_none; } @@ -351,8 +351,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(bitmaptransformd_obj, _bitmaptransformd); //| STATIC mp_obj_t _bitmaptransforme(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t p = mp_obj_get_int_truncated(a0); - uint32_t v = mp_obj_get_int_truncated(a1); + uint32_t p = mp_obj_get_int_truncated(a0); + uint32_t v = mp_obj_get_int_truncated(a1); common_hal__eve_BitmapTransformE(EVEHAL(self), p, v); return mp_const_none; } @@ -368,7 +368,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(bitmaptransforme_obj, _bitmaptransforme); //| STATIC mp_obj_t _bitmaptransformf(mp_obj_t self, mp_obj_t a0) { - uint32_t v = mp_obj_get_int_truncated(a0); + uint32_t v = mp_obj_get_int_truncated(a0); common_hal__eve_BitmapTransformF(EVEHAL(self), v); return mp_const_none; } @@ -385,8 +385,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(bitmaptransformf_obj, _bitmaptransformf); //| STATIC mp_obj_t _blendfunc(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t src = mp_obj_get_int_truncated(a0); - uint32_t dst = mp_obj_get_int_truncated(a1); + uint32_t src = mp_obj_get_int_truncated(a0); + uint32_t dst = mp_obj_get_int_truncated(a1); common_hal__eve_BlendFunc(EVEHAL(self), src, dst); return mp_const_none; } @@ -400,7 +400,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(blendfunc_obj, _blendfunc); //| STATIC mp_obj_t _call(mp_obj_t self, mp_obj_t a0) { - uint32_t dest = mp_obj_get_int_truncated(a0); + uint32_t dest = mp_obj_get_int_truncated(a0); common_hal__eve_Call(EVEHAL(self), dest); return mp_const_none; } @@ -416,7 +416,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(call_obj, _call); //| STATIC mp_obj_t _cell(mp_obj_t self, mp_obj_t a0) { - uint32_t cell = mp_obj_get_int_truncated(a0); + uint32_t cell = mp_obj_get_int_truncated(a0); common_hal__eve_Cell(EVEHAL(self), cell); return mp_const_none; } @@ -432,7 +432,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(cell_obj, _cell); //| STATIC mp_obj_t _clearcolora(mp_obj_t self, mp_obj_t a0) { - uint32_t alpha = mp_obj_get_int_truncated(a0); + uint32_t alpha = mp_obj_get_int_truncated(a0); common_hal__eve_ClearColorA(EVEHAL(self), alpha); return mp_const_none; } @@ -450,9 +450,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(clearcolora_obj, _clearcolora); //| STATIC mp_obj_t _clearcolorrgb(size_t n_args, const mp_obj_t *args) { - uint32_t red = mp_obj_get_int_truncated(args[1]); - uint32_t green = mp_obj_get_int_truncated(args[2]); - uint32_t blue = mp_obj_get_int_truncated(args[3]); + uint32_t red = mp_obj_get_int_truncated(args[1]); + uint32_t green = mp_obj_get_int_truncated(args[2]); + uint32_t blue = mp_obj_get_int_truncated(args[3]); common_hal__eve_ClearColorRGB(EVEHAL(args[0]), red, green, blue); return mp_const_none; } @@ -468,9 +468,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(clearcolorrgb_obj, 4, 4, _clearcolorr //| STATIC mp_obj_t _clear(size_t n_args, const mp_obj_t *args) { - uint32_t c = (n_args > 1) ? mp_obj_get_int_truncated(args[1]) : 1; - uint32_t s = (n_args > 2) ? mp_obj_get_int_truncated(args[2]) : 1; - uint32_t t = (n_args > 3) ? mp_obj_get_int_truncated(args[3]) : 1; + uint32_t c = (n_args > 1) ? mp_obj_get_int_truncated(args[1]) : 1; + uint32_t s = (n_args > 2) ? mp_obj_get_int_truncated(args[2]) : 1; + uint32_t t = (n_args > 3) ? mp_obj_get_int_truncated(args[3]) : 1; common_hal__eve_Clear(EVEHAL(args[0]), c, s, t); return mp_const_none; } @@ -486,7 +486,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(clear_obj, 1, 4, _clear); //| STATIC mp_obj_t _clearstencil(mp_obj_t self, mp_obj_t a0) { - uint32_t s = mp_obj_get_int_truncated(a0); + uint32_t s = mp_obj_get_int_truncated(a0); common_hal__eve_ClearStencil(EVEHAL(self), s); return mp_const_none; } @@ -501,7 +501,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(clearstencil_obj, _clearstencil); //| STATIC mp_obj_t _cleartag(mp_obj_t self, mp_obj_t a0) { - uint32_t s = mp_obj_get_int_truncated(a0); + uint32_t s = mp_obj_get_int_truncated(a0); common_hal__eve_ClearTag(EVEHAL(self), s); return mp_const_none; } @@ -517,7 +517,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(cleartag_obj, _cleartag); //| STATIC mp_obj_t _colora(mp_obj_t self, mp_obj_t a0) { - uint32_t alpha = mp_obj_get_int_truncated(a0); + uint32_t alpha = mp_obj_get_int_truncated(a0); common_hal__eve_ColorA(EVEHAL(self), alpha); return mp_const_none; } @@ -536,10 +536,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(colora_obj, _colora); //| STATIC mp_obj_t _colormask(size_t n_args, const mp_obj_t *args) { - uint32_t r = mp_obj_get_int_truncated(args[1]); - uint32_t g = mp_obj_get_int_truncated(args[2]); - uint32_t b = mp_obj_get_int_truncated(args[3]); - uint32_t a = mp_obj_get_int_truncated(args[4]); + uint32_t r = mp_obj_get_int_truncated(args[1]); + uint32_t g = mp_obj_get_int_truncated(args[2]); + uint32_t b = mp_obj_get_int_truncated(args[3]); + uint32_t a = mp_obj_get_int_truncated(args[4]); common_hal__eve_ColorMask(EVEHAL(args[0]), r, g, b, a); return mp_const_none; } @@ -557,9 +557,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(colormask_obj, 5, 5, _colormask); //| STATIC mp_obj_t _colorrgb(size_t n_args, const mp_obj_t *args) { - uint32_t red = mp_obj_get_int_truncated(args[1]); - uint32_t green = mp_obj_get_int_truncated(args[2]); - uint32_t blue = mp_obj_get_int_truncated(args[3]); + uint32_t red = mp_obj_get_int_truncated(args[1]); + uint32_t green = mp_obj_get_int_truncated(args[2]); + uint32_t blue = mp_obj_get_int_truncated(args[3]); common_hal__eve_ColorRGB(EVEHAL(args[0]), red, green, blue); return mp_const_none; } @@ -598,7 +598,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(end_obj, _end); //| STATIC mp_obj_t _jump(mp_obj_t self, mp_obj_t a0) { - uint32_t dest = mp_obj_get_int_truncated(a0); + uint32_t dest = mp_obj_get_int_truncated(a0); common_hal__eve_Jump(EVEHAL(self), dest); return mp_const_none; } @@ -612,7 +612,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(jump_obj, _jump); //| STATIC mp_obj_t _macro(mp_obj_t self, mp_obj_t a0) { - uint32_t m = mp_obj_get_int_truncated(a0); + uint32_t m = mp_obj_get_int_truncated(a0); common_hal__eve_Macro(EVEHAL(self), m); return mp_const_none; } @@ -640,7 +640,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(nop_obj, _nop); //| STATIC mp_obj_t _palettesource(mp_obj_t self, mp_obj_t a0) { - uint32_t addr = mp_obj_get_int_truncated(a0); + uint32_t addr = mp_obj_get_int_truncated(a0); common_hal__eve_PaletteSource(EVEHAL(self), addr); return mp_const_none; } @@ -693,7 +693,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(savecontext_obj, _savecontext); //| STATIC mp_obj_t _scissorsize(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t width = mp_obj_get_int_truncated(a0); + uint32_t width = mp_obj_get_int_truncated(a0); uint32_t height = mp_obj_get_int_truncated(a1); common_hal__eve_ScissorSize(EVEHAL(self), width, height); return mp_const_none; @@ -711,8 +711,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(scissorsize_obj, _scissorsize); //| STATIC mp_obj_t _scissorxy(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t x = mp_obj_get_int_truncated(a0); - uint32_t y = mp_obj_get_int_truncated(a1); + uint32_t x = mp_obj_get_int_truncated(a0); + uint32_t y = mp_obj_get_int_truncated(a1); common_hal__eve_ScissorXY(EVEHAL(self), x, y); return mp_const_none; } @@ -730,9 +730,9 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(scissorxy_obj, _scissorxy); //| STATIC mp_obj_t _stencilfunc(size_t n_args, const mp_obj_t *args) { - uint32_t func = mp_obj_get_int_truncated(args[1]); - uint32_t ref = mp_obj_get_int_truncated(args[2]); - uint32_t mask = mp_obj_get_int_truncated(args[3]); + uint32_t func = mp_obj_get_int_truncated(args[1]); + uint32_t ref = mp_obj_get_int_truncated(args[2]); + uint32_t mask = mp_obj_get_int_truncated(args[3]); common_hal__eve_StencilFunc(EVEHAL(args[0]), func, ref, mask); return mp_const_none; } @@ -748,7 +748,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(stencilfunc_obj, 4, 4, _stencilfunc); //| STATIC mp_obj_t _stencilmask(mp_obj_t self, mp_obj_t a0) { - uint32_t mask = mp_obj_get_int_truncated(a0); + uint32_t mask = mp_obj_get_int_truncated(a0); common_hal__eve_StencilMask(EVEHAL(self), mask); return mp_const_none; } @@ -765,8 +765,8 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(stencilmask_obj, _stencilmask); //| STATIC mp_obj_t _stencilop(mp_obj_t self, mp_obj_t a0, mp_obj_t a1) { - uint32_t sfail = mp_obj_get_int_truncated(a0); - uint32_t spass = mp_obj_get_int_truncated(a1); + uint32_t sfail = mp_obj_get_int_truncated(a0); + uint32_t spass = mp_obj_get_int_truncated(a1); common_hal__eve_StencilOp(EVEHAL(self), sfail, spass); return mp_const_none; } @@ -782,7 +782,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(stencilop_obj, _stencilop); //| STATIC mp_obj_t _tagmask(mp_obj_t self, mp_obj_t a0) { - uint32_t mask = mp_obj_get_int_truncated(a0); + uint32_t mask = mp_obj_get_int_truncated(a0); common_hal__eve_TagMask(EVEHAL(self), mask); return mp_const_none; } @@ -798,14 +798,14 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(tagmask_obj, _tagmask); //| STATIC mp_obj_t _tag(mp_obj_t self, mp_obj_t a0) { - uint32_t s = mp_obj_get_int_truncated(a0); + uint32_t s = mp_obj_get_int_truncated(a0); common_hal__eve_Tag(EVEHAL(self), s); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(tag_obj, _tag); STATIC mp_obj_t _vertexformat(mp_obj_t self, mp_obj_t a0) { - uint32_t frac = mp_obj_get_int_truncated(a0); + uint32_t frac = mp_obj_get_int_truncated(a0); common_hal__eve_VertexFormat(EVEHAL(self), frac); return mp_const_none; } @@ -822,10 +822,10 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(vertexformat_obj, _vertexformat); //| STATIC mp_obj_t _vertex2ii(size_t n_args, const mp_obj_t *args) { - uint32_t x = mp_obj_get_int_truncated(args[1]); - uint32_t y = mp_obj_get_int_truncated(args[2]); + uint32_t x = mp_obj_get_int_truncated(args[1]); + uint32_t y = mp_obj_get_int_truncated(args[2]); uint32_t handle = (n_args > 3) ? mp_obj_get_int_truncated(args[3]) : 0; - uint32_t cell = (n_args > 4) ? mp_obj_get_int_truncated(args[4]) : 0; + uint32_t cell = (n_args > 4) ? mp_obj_get_int_truncated(args[4]) : 0; common_hal__eve_Vertex2ii(EVEHAL(args[0]), x, y, handle, cell); return mp_const_none; } @@ -882,7 +882,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(vertex2ii_obj, 3, 5, _vertex2ii); { MP_ROM_QSTR(MP_QSTR_VertexFormat), MP_ROM_PTR(&vertexformat_obj) }, \ { MP_ROM_QSTR(MP_QSTR_Vertex2ii), MP_ROM_PTR(&vertex2ii_obj) } -//} +// } // Hand-written functions { @@ -911,7 +911,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(vertex2f_obj, _vertex2f); //| STATIC mp_obj_t _linewidth(mp_obj_t self, mp_obj_t a0) { - mp_float_t width = mp_obj_get_float(a0); + mp_float_t width = mp_obj_get_float(a0); common_hal__eve_LineWidth(EVEHAL(self), width); return mp_const_none; } @@ -927,7 +927,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(linewidth_obj, _linewidth); //| STATIC mp_obj_t _pointsize(mp_obj_t self, mp_obj_t a0) { - mp_float_t size = mp_obj_get_float(a0); + mp_float_t size = mp_obj_get_float(a0); common_hal__eve_PointSize(EVEHAL(self), size); return mp_const_none; } @@ -943,7 +943,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(pointsize_obj, _pointsize); //| STATIC mp_obj_t _vertextranslatex(mp_obj_t self, mp_obj_t a0) { - mp_float_t x = mp_obj_get_float(a0); + mp_float_t x = mp_obj_get_float(a0); common_hal__eve_VertexTranslateX(EVEHAL(self), x); return mp_const_none; } @@ -960,7 +960,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(vertextranslatex_obj, _vertextranslatex); STATIC mp_obj_t _vertextranslatey(mp_obj_t self, mp_obj_t a0) { - mp_float_t y = mp_obj_get_float(a0); + mp_float_t y = mp_obj_get_float(a0); common_hal__eve_VertexTranslateY(EVEHAL(self), y); return mp_const_none; } @@ -975,7 +975,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_2(vertextranslatey_obj, _vertextranslatey); //| ... //| -//} +// } // Append an object x to the FIFO #define ADD_X(self, x) \ @@ -1024,7 +1024,7 @@ STATIC mp_obj_t _cmd(size_t n_args, const mp_obj_t *args) { // Count how many 32-bit words required size_t n = 0; for (size_t i = 0; i < fmt.len; n++) { - switch (((char*)fmt.buf)[i]) { + switch (((char *)fmt.buf)[i]) { case 'I': case 'i': i += 1; @@ -1044,8 +1044,8 @@ STATIC mp_obj_t _cmd(size_t n_args, const mp_obj_t *args) { mp_obj_t *a = items; uint32_t lo; - for (size_t i = 0; i < fmt.len; ) { - switch (((char*)fmt.buf)[i]) { + for (size_t i = 0; i < fmt.len;) { + switch (((char *)fmt.buf)[i]) { case 'I': case 'i': *p++ = mp_obj_get_int_truncated(*a++); @@ -1091,7 +1091,7 @@ STATIC const mp_obj_type_t _EVE_type = { { &mp_type_type }, .name = MP_QSTR__EVE, .make_new = _EVE_make_new, - .locals_dict = (void*)&_EVE_locals_dict, + .locals_dict = (void *)&_EVE_locals_dict, }; STATIC const mp_rom_map_elem_t mp_module__eve_globals_table[] = { @@ -1103,5 +1103,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module__eve_globals, mp_module__eve_globals_table const mp_obj_module_t _eve_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module__eve_globals, + .globals = (mp_obj_dict_t *)&mp_module__eve_globals, }; diff --git a/shared-bindings/_pew/PewPew.c b/shared-bindings/_pew/PewPew.c index a8a43e1571..b98a124600 100644 --- a/shared-bindings/_pew/PewPew.c +++ b/shared-bindings/_pew/PewPew.c @@ -63,7 +63,7 @@ //| ... //| STATIC mp_obj_t pewpew_make_new(const mp_obj_type_t *type, size_t n_args, - const mp_obj_t *pos_args, mp_map_t *kw_args) { + const mp_obj_t *pos_args, mp_map_t *kw_args) { mp_arg_check_num(n_args, kw_args, 4, 4, true); enum { ARG_buffer, ARG_rows, ARG_cols, ARG_buttons }; static const mp_arg_t allowed_args[] = { @@ -74,7 +74,7 @@ STATIC mp_obj_t pewpew_make_new(const mp_obj_type_t *type, size_t n_args, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), - allowed_args, args); + allowed_args, args); mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); @@ -112,11 +112,11 @@ STATIC mp_obj_t pewpew_make_new(const mp_obj_type_t *type, size_t n_args, } if (!MP_OBJ_IS_TYPE(args[ARG_buttons].u_obj, - &digitalio_digitalinout_type)) { + &digitalio_digitalinout_type)) { mp_raise_TypeError(translate("buttons must be digitalio.DigitalInOut")); } digitalio_digitalinout_obj_t *buttons = MP_OBJ_TO_PTR( - args[ARG_buttons].u_obj); + args[ARG_buttons].u_obj); if (common_hal_digitalio_digitalinout_deinited(buttons)) { raise_deinited_error(); } @@ -149,5 +149,5 @@ const mp_obj_type_t pewpew_type = { { &mp_type_type }, .name = MP_QSTR_PewPew, .make_new = pewpew_make_new, - .locals_dict = (mp_obj_dict_t*)&pewpew_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pewpew_locals_dict, }; diff --git a/shared-bindings/_pew/__init__.c b/shared-bindings/_pew/__init__.c index 912d267c4c..2ecf341900 100644 --- a/shared-bindings/_pew/__init__.c +++ b/shared-bindings/_pew/__init__.c @@ -57,9 +57,9 @@ STATIC const mp_rom_map_elem_t pew_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_get_ticks), MP_ROM_PTR(&get_ticks_obj)}, }; STATIC MP_DEFINE_CONST_DICT(pew_module_globals, - pew_module_globals_table); + pew_module_globals_table); const mp_obj_module_t pew_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pew_module_globals, + .globals = (mp_obj_dict_t *)&pew_module_globals, }; diff --git a/shared-bindings/_pixelbuf/PixelBuf.c b/shared-bindings/_pixelbuf/PixelBuf.c index a4b5b5b1b3..22923e97d5 100644 --- a/shared-bindings/_pixelbuf/PixelBuf.c +++ b/shared-bindings/_pixelbuf/PixelBuf.c @@ -46,7 +46,7 @@ extern const int32_t colorwheel(float pos); -static void parse_byteorder(mp_obj_t byteorder_obj, pixelbuf_byteorder_details_t* parsed); +static void parse_byteorder(mp_obj_t byteorder_obj, pixelbuf_byteorder_details_t *parsed); //| class PixelBuf: //| """A fast RGB[W] pixel buffer for LED and similar devices.""" @@ -113,13 +113,13 @@ STATIC mp_obj_t pixelbuf_pixelbuf_make_new(const mp_obj_type_t *type, size_t n_a pixelbuf_pixelbuf_obj_t *self = m_new_obj(pixelbuf_pixelbuf_obj_t); self->base.type = &pixelbuf_pixelbuf_type; common_hal__pixelbuf_pixelbuf_construct(self, args[ARG_size].u_int, - &byteorder_details, brightness, args[ARG_auto_write].u_bool, header_bufinfo.buf, - header_bufinfo.len, trailer_bufinfo.buf, trailer_bufinfo.len); + &byteorder_details, brightness, args[ARG_auto_write].u_bool, header_bufinfo.buf, + header_bufinfo.len, trailer_bufinfo.buf, trailer_bufinfo.len); return MP_OBJ_FROM_PTR(self); } -static void parse_byteorder(mp_obj_t byteorder_obj, pixelbuf_byteorder_details_t* parsed) { +static void parse_byteorder(mp_obj_t byteorder_obj, pixelbuf_byteorder_details_t *parsed) { if (!MP_OBJ_IS_STR(byteorder_obj)) { mp_raise_TypeError(translate("byteorder is not a string")); } @@ -242,10 +242,12 @@ const mp_obj_property_t pixelbuf_pixelbuf_byteorder_str = { STATIC mp_obj_t pixelbuf_pixelbuf_unary_op(mp_unary_op_t op, mp_obj_t self_in) { switch (op) { - case MP_UNARY_OP_BOOL: return mp_const_true; + case MP_UNARY_OP_BOOL: + return mp_const_true; case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(common_hal__pixelbuf_pixelbuf_get_len(self_in)); - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -303,7 +305,7 @@ STATIC mp_obj_t pixelbuf_pixelbuf_subscr(mp_obj_t self_in, mp_obj_t index_in, mp } if (0) { -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE } else if (MP_OBJ_IS_TYPE(index_in, &mp_type_slice)) { mp_bound_slice_t slice; @@ -332,7 +334,7 @@ STATIC mp_obj_t pixelbuf_pixelbuf_subscr(mp_obj_t self_in, mp_obj_t index_in, mp } if (value == MP_OBJ_SENTINEL) { // Get - mp_obj_tuple_t* t = MP_OBJ_TO_PTR(mp_obj_new_tuple(slice_len, NULL)); + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(slice_len, NULL)); for (uint i = 0; i < slice_len; i++) { t->items[i] = common_hal__pixelbuf_pixelbuf_get_pixel(self_in, i * slice.step + slice.start); } @@ -352,7 +354,7 @@ STATIC mp_obj_t pixelbuf_pixelbuf_subscr(mp_obj_t self_in, mp_obj_t index_in, mp return MP_OBJ_NULL; // op not supported #endif } -#endif + #endif } else { // Single index rather than slice. size_t length = common_hal__pixelbuf_pixelbuf_get_len(self_in); size_t index = mp_get_index(mp_obj_get_type(self_in), length, index_in, false); @@ -379,12 +381,12 @@ STATIC MP_DEFINE_CONST_DICT(pixelbuf_pixelbuf_locals_dict, pixelbuf_pixelbuf_loc const mp_obj_type_t pixelbuf_pixelbuf_type = { - { &mp_type_type }, - .name = MP_QSTR_PixelBuf, - .subscr = pixelbuf_pixelbuf_subscr, - .make_new = pixelbuf_pixelbuf_make_new, - .unary_op = pixelbuf_pixelbuf_unary_op, - .getiter = mp_obj_new_generic_iterator, - .print = NULL, - .locals_dict = (mp_obj_t)&pixelbuf_pixelbuf_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_PixelBuf, + .subscr = pixelbuf_pixelbuf_subscr, + .make_new = pixelbuf_pixelbuf_make_new, + .unary_op = pixelbuf_pixelbuf_unary_op, + .getiter = mp_obj_new_generic_iterator, + .print = NULL, + .locals_dict = (mp_obj_t)&pixelbuf_pixelbuf_locals_dict, }; diff --git a/shared-bindings/_pixelbuf/PixelBuf.h b/shared-bindings/_pixelbuf/PixelBuf.h index d410820591..5e83b9b2d4 100644 --- a/shared-bindings/_pixelbuf/PixelBuf.h +++ b/shared-bindings/_pixelbuf/PixelBuf.h @@ -32,8 +32,8 @@ extern const mp_obj_type_t pixelbuf_pixelbuf_type; void common_hal__pixelbuf_pixelbuf_construct(pixelbuf_pixelbuf_obj_t *self, size_t n, - pixelbuf_byteorder_details_t* byteorder, mp_float_t brightness, bool auto_write, uint8_t* header, - size_t header_len, uint8_t* trailer, size_t trailer_len); + pixelbuf_byteorder_details_t *byteorder, mp_float_t brightness, bool auto_write, uint8_t *header, + size_t header_len, uint8_t *trailer, size_t trailer_len); // These take mp_obj_t because they are called on subclasses of PixelBuf. uint8_t common_hal__pixelbuf_pixelbuf_get_bpp(mp_obj_t self); @@ -47,6 +47,6 @@ void common_hal__pixelbuf_pixelbuf_fill(mp_obj_t self, mp_obj_t item); void common_hal__pixelbuf_pixelbuf_show(mp_obj_t self); mp_obj_t common_hal__pixelbuf_pixelbuf_get_pixel(mp_obj_t self, size_t index); void common_hal__pixelbuf_pixelbuf_set_pixel(mp_obj_t self, size_t index, mp_obj_t item); -void common_hal__pixelbuf_pixelbuf_set_pixels(mp_obj_t self_in, size_t start, mp_int_t step, size_t slice_len, mp_obj_t* values, mp_obj_tuple_t *flatten_to); +void common_hal__pixelbuf_pixelbuf_set_pixels(mp_obj_t self_in, size_t start, mp_int_t step, size_t slice_len, mp_obj_t *values, mp_obj_tuple_t *flatten_to); #endif // CP_SHARED_BINDINGS_PIXELBUF_PIXELBUF_H diff --git a/shared-bindings/_pixelbuf/__init__.c b/shared-bindings/_pixelbuf/__init__.c index fdd02509c8..5e87bacab1 100644 --- a/shared-bindings/_pixelbuf/__init__.c +++ b/shared-bindings/_pixelbuf/__init__.c @@ -59,9 +59,9 @@ const int32_t colorwheel(float pos) { if (pos > 255) { pos = pos - ((uint32_t)(pos / 256) * 256); } - if (pos < 85) + if (pos < 85) { return (uint8_t)(255 - (pos * 3)) << 16 | (uint8_t)(pos * 3) << 8; - else if (pos < 170) { + } else if (pos < 170) { pos -= 85; return (uint8_t)(255 - (pos * 3)) << 8 | (uint8_t)(pos * 3); } else { @@ -81,5 +81,5 @@ STATIC MP_DEFINE_CONST_DICT(pixelbuf_module_globals, pixelbuf_module_globals_tab const mp_obj_module_t pixelbuf_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pixelbuf_module_globals, + .globals = (mp_obj_dict_t *)&pixelbuf_module_globals, }; diff --git a/shared-bindings/_pixelbuf/__init__.h b/shared-bindings/_pixelbuf/__init__.h index 0e8c4a37f9..890543d3e9 100644 --- a/shared-bindings/_pixelbuf/__init__.h +++ b/shared-bindings/_pixelbuf/__init__.h @@ -31,4 +31,4 @@ const int32_t colorwheel(float pos); -#endif //CP_SHARED_BINDINGS_PIXELBUF_INIT_H +#endif // CP_SHARED_BINDINGS_PIXELBUF_INIT_H diff --git a/shared-bindings/_stage/Layer.c b/shared-bindings/_stage/Layer.c index 612323a4e4..51ed5c3bf6 100644 --- a/shared-bindings/_stage/Layer.c +++ b/shared-bindings/_stage/Layer.c @@ -49,7 +49,7 @@ //| ... //| STATIC mp_obj_t layer_make_new(const mp_obj_type_t *type, size_t n_args, - const mp_obj_t *args, mp_map_t *kw_args) { + const mp_obj_t *args, mp_map_t *kw_args) { mp_arg_check_num(n_args, kw_args, 4, 5, false); layer_obj_t *self = m_new_obj(layer_obj_t); @@ -82,7 +82,7 @@ STATIC mp_obj_t layer_make_new(const mp_obj_type_t *type, size_t n_args, mp_raise_ValueError(translate("map buffer too small")); } } else { - self-> map = NULL; + self->map = NULL; } return MP_OBJ_FROM_PTR(self); @@ -106,7 +106,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(layer_move_obj, layer_move); //| ... //| STATIC mp_obj_t layer_frame(mp_obj_t self_in, mp_obj_t frame_in, - mp_obj_t rotation_in) { + mp_obj_t rotation_in) { layer_obj_t *self = MP_OBJ_TO_PTR(self_in); self->frame = mp_obj_get_int(frame_in); self->rotation = mp_obj_get_int(rotation_in); @@ -125,5 +125,5 @@ const mp_obj_type_t mp_type_layer = { { &mp_type_type }, .name = MP_QSTR_Layer, .make_new = layer_make_new, - .locals_dict = (mp_obj_dict_t*)&layer_locals_dict, + .locals_dict = (mp_obj_dict_t *)&layer_locals_dict, }; diff --git a/shared-bindings/_stage/Text.c b/shared-bindings/_stage/Text.c index d1e50fa236..55b60953b6 100644 --- a/shared-bindings/_stage/Text.c +++ b/shared-bindings/_stage/Text.c @@ -49,7 +49,7 @@ //| ... //| STATIC mp_obj_t text_make_new(const mp_obj_type_t *type, size_t n_args, - const mp_obj_t *args, mp_map_t *kw_args) { + const mp_obj_t *args, mp_map_t *kw_args) { mp_arg_check_num(n_args, kw_args, 5, 5, false); text_obj_t *self = m_new_obj(text_obj_t); @@ -104,5 +104,5 @@ const mp_obj_type_t mp_type_text = { { &mp_type_type }, .name = MP_QSTR_Text, .make_new = text_make_new, - .locals_dict = (mp_obj_dict_t*)&text_locals_dict, + .locals_dict = (mp_obj_dict_t *)&text_locals_dict, }; diff --git a/shared-bindings/_stage/__init__.c b/shared-bindings/_stage/__init__.c index f173147e31..0e3f08da59 100644 --- a/shared-bindings/_stage/__init__.c +++ b/shared-bindings/_stage/__init__.c @@ -91,7 +91,7 @@ STATIC mp_obj_t stage_render(size_t n_args, const mp_obj_t *args) { } render_stage(x0, y0, x1, y1, layers, layers_size, buffer, buffer_size, - display, scale, background); + display, scale, background); return mp_const_none; } @@ -109,5 +109,5 @@ STATIC MP_DEFINE_CONST_DICT(stage_module_globals, stage_module_globals_table); const mp_obj_module_t stage_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&stage_module_globals, + .globals = (mp_obj_dict_t *)&stage_module_globals, }; diff --git a/shared-bindings/adafruit_bus_device/I2CDevice.c b/shared-bindings/adafruit_bus_device/I2CDevice.c index e6ec8c1472..ac760a490f 100644 --- a/shared-bindings/adafruit_bus_device/I2CDevice.c +++ b/shared-bindings/adafruit_bus_device/I2CDevice.c @@ -77,7 +77,7 @@ STATIC mp_obj_t adafruit_bus_device_i2cdevice_make_new(const mp_obj_type_t *type mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - mp_obj_t* i2c = args[ARG_i2c].u_obj; + mp_obj_t *i2c = args[ARG_i2c].u_obj; common_hal_adafruit_bus_device_i2cdevice_construct(MP_OBJ_TO_PTR(self), i2c, args[ARG_device_address].u_int); if (args[ARG_probe].u_bool == true) { @@ -138,7 +138,7 @@ STATIC mp_obj_t adafruit_bus_device_i2cdevice_readinto(size_t n_args, const mp_o mp_load_method(self->i2c, MP_QSTR_readfrom_into, dest); dest[2] = MP_OBJ_NEW_SMALL_INT(self->device_address); dest[3] = args[ARG_buffer].u_obj; - //dest[4] = mp_obj_new_str("start", 5); + // dest[4] = mp_obj_new_str("start", 5); dest[4] = MP_OBJ_NEW_QSTR(MP_QSTR_start); dest[5] = MP_OBJ_NEW_SMALL_INT(args[ARG_start].u_int); if (args[ARG_end].u_int != INT_MAX) { @@ -272,8 +272,8 @@ STATIC const mp_rom_map_elem_t adafruit_bus_device_i2cdevice_locals_dict_table[] STATIC MP_DEFINE_CONST_DICT(adafruit_bus_device_i2cdevice_locals_dict, adafruit_bus_device_i2cdevice_locals_dict_table); const mp_obj_type_t adafruit_bus_device_i2cdevice_type = { - { &mp_type_type }, - .name = MP_QSTR_I2CDevice, - .make_new = adafruit_bus_device_i2cdevice_make_new, - .locals_dict = (mp_obj_dict_t*)&adafruit_bus_device_i2cdevice_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_I2CDevice, + .make_new = adafruit_bus_device_i2cdevice_make_new, + .locals_dict = (mp_obj_dict_t *)&adafruit_bus_device_i2cdevice_locals_dict, }; diff --git a/shared-bindings/adafruit_bus_device/I2CDevice.h b/shared-bindings/adafruit_bus_device/I2CDevice.h index 82ef1feb80..36a95b6a24 100644 --- a/shared-bindings/adafruit_bus_device/I2CDevice.h +++ b/shared-bindings/adafruit_bus_device/I2CDevice.h @@ -37,7 +37,7 @@ #include "py/obj.h" #include "shared-module/adafruit_bus_device/I2CDevice.h" -//#include "shared-bindings/busio/I2C.h" +// #include "shared-bindings/busio/I2C.h" // Type object used in Python. Should be shared between ports. extern const mp_obj_type_t adafruit_bus_device_i2cdevice_type; diff --git a/shared-bindings/adafruit_bus_device/SPIDevice.c b/shared-bindings/adafruit_bus_device/SPIDevice.c index 74fa28e4d5..94901e4a15 100644 --- a/shared-bindings/adafruit_bus_device/SPIDevice.c +++ b/shared-bindings/adafruit_bus_device/SPIDevice.c @@ -84,7 +84,7 @@ STATIC mp_obj_t adafruit_bus_device_spidevice_make_new(const mp_obj_type_t *type mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - busio_spi_obj_t* spi = args[ARG_spi].u_obj; + busio_spi_obj_t *spi = args[ARG_spi].u_obj; common_hal_adafruit_bus_device_spidevice_construct(MP_OBJ_TO_PTR(self), spi, args[ARG_chip_select].u_obj, args[ARG_baudrate].u_int, args[ARG_polarity].u_int, args[ARG_phase].u_int, args[ARG_extra_clocks].u_int); @@ -130,8 +130,8 @@ STATIC const mp_rom_map_elem_t adafruit_bus_device_spidevice_locals_dict_table[] STATIC MP_DEFINE_CONST_DICT(adafruit_bus_device_spidevice_locals_dict, adafruit_bus_device_spidevice_locals_dict_table); const mp_obj_type_t adafruit_bus_device_spidevice_type = { - { &mp_type_type }, - .name = MP_QSTR_SPIDevice, - .make_new = adafruit_bus_device_spidevice_make_new, - .locals_dict = (mp_obj_dict_t*)&adafruit_bus_device_spidevice_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_SPIDevice, + .make_new = adafruit_bus_device_spidevice_make_new, + .locals_dict = (mp_obj_dict_t *)&adafruit_bus_device_spidevice_locals_dict, }; diff --git a/shared-bindings/adafruit_bus_device/__init__.c b/shared-bindings/adafruit_bus_device/__init__.c index e01abcab3f..84abbd0c2e 100644 --- a/shared-bindings/adafruit_bus_device/__init__.c +++ b/shared-bindings/adafruit_bus_device/__init__.c @@ -43,7 +43,7 @@ STATIC MP_DEFINE_CONST_DICT(adafruit_bus_device_i2c_device_globals, adafruit_bus const mp_obj_module_t adafruit_bus_device_i2c_device_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&adafruit_bus_device_i2c_device_globals, + .globals = (mp_obj_dict_t *)&adafruit_bus_device_i2c_device_globals, }; STATIC const mp_rom_map_elem_t adafruit_bus_device_spi_device_globals_table[] = { @@ -54,7 +54,7 @@ STATIC MP_DEFINE_CONST_DICT(adafruit_bus_device_spi_device_globals, adafruit_bus const mp_obj_module_t adafruit_bus_device_spi_device_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&adafruit_bus_device_spi_device_globals, + .globals = (mp_obj_dict_t *)&adafruit_bus_device_spi_device_globals, }; //| """Hardware accelerated external bus access @@ -74,5 +74,5 @@ STATIC MP_DEFINE_CONST_DICT(adafruit_bus_device_module_globals, adafruit_bus_dev const mp_obj_module_t adafruit_bus_device_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&adafruit_bus_device_module_globals, + .globals = (mp_obj_dict_t *)&adafruit_bus_device_module_globals, }; diff --git a/shared-bindings/aesio/__init__.h b/shared-bindings/aesio/__init__.h index 634fed2e54..60f6b83611 100644 --- a/shared-bindings/aesio/__init__.h +++ b/shared-bindings/aesio/__init__.h @@ -31,23 +31,23 @@ extern const mp_obj_type_t aesio_aes_type; -void common_hal_aesio_aes_construct(aesio_aes_obj_t* self, - const uint8_t* key, - uint32_t key_length, - const uint8_t* iv, - int mode, - int counter); -void common_hal_aesio_aes_rekey(aesio_aes_obj_t* self, - const uint8_t* key, - uint32_t key_length, - const uint8_t* iv); -void common_hal_aesio_aes_set_mode(aesio_aes_obj_t* self, - int mode); -void common_hal_aesio_aes_encrypt(aesio_aes_obj_t* self, - uint8_t* buffer, - size_t len); -void common_hal_aesio_aes_decrypt(aesio_aes_obj_t* self, - uint8_t* buffer, - size_t len); +void common_hal_aesio_aes_construct(aesio_aes_obj_t *self, + const uint8_t *key, + uint32_t key_length, + const uint8_t *iv, + int mode, + int counter); +void common_hal_aesio_aes_rekey(aesio_aes_obj_t *self, + const uint8_t *key, + uint32_t key_length, + const uint8_t *iv); +void common_hal_aesio_aes_set_mode(aesio_aes_obj_t *self, + int mode); +void common_hal_aesio_aes_encrypt(aesio_aes_obj_t *self, + uint8_t *buffer, + size_t len); +void common_hal_aesio_aes_decrypt(aesio_aes_obj_t *self, + uint8_t *buffer, + size_t len); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_AESIO_H diff --git a/shared-bindings/aesio/aes.c b/shared-bindings/aesio/aes.c index a121845e34..f021e9abc5 100644 --- a/shared-bindings/aesio/aes.c +++ b/shared-bindings/aesio/aes.c @@ -37,119 +37,119 @@ //| STATIC mp_obj_t aesio_aes_make_new(const mp_obj_type_t *type, size_t n_args, - const mp_obj_t *pos_args, - mp_map_t *kw_args) { - (void)type; - enum { ARG_key, ARG_mode, ARG_IV, ARG_counter, ARG_segment_size }; - static const mp_arg_t allowed_args[] = { - {MP_QSTR_key, MP_ARG_OBJ | MP_ARG_REQUIRED}, - {MP_QSTR_mode, MP_ARG_INT, {.u_int = AES_MODE_ECB}}, - {MP_QSTR_IV, MP_ARG_OBJ}, - {MP_QSTR_counter, MP_ARG_OBJ}, - {MP_QSTR_segment_size, MP_ARG_INT, {.u_int = 8}}, - }; - mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + const mp_obj_t *pos_args, + mp_map_t *kw_args) { + (void)type; + enum { ARG_key, ARG_mode, ARG_IV, ARG_counter, ARG_segment_size }; + static const mp_arg_t allowed_args[] = { + {MP_QSTR_key, MP_ARG_OBJ | MP_ARG_REQUIRED}, + {MP_QSTR_mode, MP_ARG_INT, {.u_int = AES_MODE_ECB}}, + {MP_QSTR_IV, MP_ARG_OBJ}, + {MP_QSTR_counter, MP_ARG_OBJ}, + {MP_QSTR_segment_size, MP_ARG_INT, {.u_int = 8}}, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), - allowed_args, args); + mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), + allowed_args, args); - aesio_aes_obj_t *self = m_new_obj(aesio_aes_obj_t); - self->base.type = &aesio_aes_type; + aesio_aes_obj_t *self = m_new_obj(aesio_aes_obj_t); + self->base.type = &aesio_aes_type; - mp_buffer_info_t bufinfo; + mp_buffer_info_t bufinfo; - const uint8_t *key = NULL; - uint32_t key_length = 0; - if (mp_get_buffer(args[ARG_key].u_obj, &bufinfo, MP_BUFFER_READ)) { - if ((bufinfo.len != 16) && (bufinfo.len != 24) && (bufinfo.len != 32)) { - mp_raise_TypeError(translate("Key must be 16, 24, or 32 bytes long")); + const uint8_t *key = NULL; + uint32_t key_length = 0; + if (mp_get_buffer(args[ARG_key].u_obj, &bufinfo, MP_BUFFER_READ)) { + if ((bufinfo.len != 16) && (bufinfo.len != 24) && (bufinfo.len != 32)) { + mp_raise_TypeError(translate("Key must be 16, 24, or 32 bytes long")); + } + key = bufinfo.buf; + key_length = bufinfo.len; + } else { + mp_raise_TypeError(translate("No key was specified")); } - key = bufinfo.buf; - key_length = bufinfo.len; - } else { - mp_raise_TypeError(translate("No key was specified")); - } - int mode = args[ARG_mode].u_int; - switch (args[ARG_mode].u_int) { - case AES_MODE_CBC: - case AES_MODE_ECB: - case AES_MODE_CTR: - break; - default: - mp_raise_TypeError(translate("Requested AES mode is unsupported")); - } - - // IV is required for CBC mode and is ignored for other modes. - const uint8_t *iv = NULL; - if (args[ARG_IV].u_obj != NULL && - mp_get_buffer(args[ARG_IV].u_obj, &bufinfo, MP_BUFFER_READ)) { - if (bufinfo.len != AES_BLOCKLEN) { - mp_raise_TypeError_varg(translate("IV must be %d bytes long"), - AES_BLOCKLEN); + int mode = args[ARG_mode].u_int; + switch (args[ARG_mode].u_int) { + case AES_MODE_CBC: + case AES_MODE_ECB: + case AES_MODE_CTR: + break; + default: + mp_raise_TypeError(translate("Requested AES mode is unsupported")); } - iv = bufinfo.buf; - } - common_hal_aesio_aes_construct(self, key, key_length, iv, mode, - args[ARG_counter].u_int); - return MP_OBJ_FROM_PTR(self); + // IV is required for CBC mode and is ignored for other modes. + const uint8_t *iv = NULL; + if (args[ARG_IV].u_obj != NULL && + mp_get_buffer(args[ARG_IV].u_obj, &bufinfo, MP_BUFFER_READ)) { + if (bufinfo.len != AES_BLOCKLEN) { + mp_raise_TypeError_varg(translate("IV must be %d bytes long"), + AES_BLOCKLEN); + } + iv = bufinfo.buf; + } + + common_hal_aesio_aes_construct(self, key, key_length, iv, mode, + args[ARG_counter].u_int); + return MP_OBJ_FROM_PTR(self); } STATIC mp_obj_t aesio_aes_rekey(size_t n_args, const mp_obj_t *pos_args) { - aesio_aes_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + aesio_aes_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(pos_args[1], &bufinfo, MP_BUFFER_READ); - const uint8_t *key = bufinfo.buf; - size_t key_length = bufinfo.len; - if (key == NULL) { - mp_raise_ValueError(translate("No key was specified")); - } - if ((key_length != 16) && (key_length != 24) && (key_length != 32)) { - mp_raise_TypeError(translate("Key must be 16, 24, or 32 bytes long")); - } - - const uint8_t *iv = NULL; - if (n_args > 2) { - mp_get_buffer_raise(pos_args[2], &bufinfo, MP_BUFFER_READ); - size_t iv_length = bufinfo.len; - iv = (const uint8_t *)bufinfo.buf; - if (iv_length != AES_BLOCKLEN) { - mp_raise_TypeError_varg(translate("IV must be %d bytes long"), - AES_BLOCKLEN); + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(pos_args[1], &bufinfo, MP_BUFFER_READ); + const uint8_t *key = bufinfo.buf; + size_t key_length = bufinfo.len; + if (key == NULL) { + mp_raise_ValueError(translate("No key was specified")); + } + if ((key_length != 16) && (key_length != 24) && (key_length != 32)) { + mp_raise_TypeError(translate("Key must be 16, 24, or 32 bytes long")); } - } - common_hal_aesio_aes_rekey(self, key, key_length, iv); - return mp_const_none; + const uint8_t *iv = NULL; + if (n_args > 2) { + mp_get_buffer_raise(pos_args[2], &bufinfo, MP_BUFFER_READ); + size_t iv_length = bufinfo.len; + iv = (const uint8_t *)bufinfo.buf; + if (iv_length != AES_BLOCKLEN) { + mp_raise_TypeError_varg(translate("IV must be %d bytes long"), + AES_BLOCKLEN); + } + } + + common_hal_aesio_aes_rekey(self, key, key_length, iv); + return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_VAR(aesio_aes_rekey_obj, 2, aesio_aes_rekey); STATIC void validate_length(aesio_aes_obj_t *self, size_t src_length, - size_t dest_length) { - if (src_length != dest_length) { - mp_raise_ValueError( - translate("Source and destination buffers must be the same length")); - } + size_t dest_length) { + if (src_length != dest_length) { + mp_raise_ValueError( + translate("Source and destination buffers must be the same length")); + } - switch (self->mode) { - case AES_MODE_ECB: - if (src_length != 16) { - mp_raise_msg(&mp_type_ValueError, - translate("ECB only operates on 16 bytes at a time")); + switch (self->mode) { + case AES_MODE_ECB: + if (src_length != 16) { + mp_raise_msg(&mp_type_ValueError, + translate("ECB only operates on 16 bytes at a time")); + } + break; + case AES_MODE_CBC: + if ((src_length & 15) != 0) { + mp_raise_msg(&mp_type_ValueError, + translate("CBC blocks must be multiples of 16 bytes")); + } + break; + case AES_MODE_CTR: + break; } - break; - case AES_MODE_CBC: - if ((src_length & 15) != 0) { - mp_raise_msg(&mp_type_ValueError, - translate("CBC blocks must be multiples of 16 bytes")); - } - break; - case AES_MODE_CTR: - break; - } } //| def encrypt_into(self, src: ReadableBuffer, dest: WriteableBuffer) -> None: @@ -161,27 +161,27 @@ STATIC void validate_length(aesio_aes_obj_t *self, size_t src_length, //| ... //| STATIC mp_obj_t aesio_aes_encrypt_into(mp_obj_t aesio_obj, mp_obj_t src, - mp_obj_t dest) { - if (!MP_OBJ_IS_TYPE(aesio_obj, &aesio_aes_type)) { - mp_raise_TypeError_varg(translate("Expected a %q"), aesio_aes_type.name); - } - // Convert parameters into expected types. - aesio_aes_obj_t *aes = MP_OBJ_TO_PTR(aesio_obj); + mp_obj_t dest) { + if (!MP_OBJ_IS_TYPE(aesio_obj, &aesio_aes_type)) { + mp_raise_TypeError_varg(translate("Expected a %q"), aesio_aes_type.name); + } + // Convert parameters into expected types. + aesio_aes_obj_t *aes = MP_OBJ_TO_PTR(aesio_obj); - mp_buffer_info_t srcbufinfo, destbufinfo; - mp_get_buffer_raise(src, &srcbufinfo, MP_BUFFER_READ); - mp_get_buffer_raise(dest, &destbufinfo, MP_BUFFER_WRITE); - validate_length(aes, srcbufinfo.len, destbufinfo.len); + mp_buffer_info_t srcbufinfo, destbufinfo; + mp_get_buffer_raise(src, &srcbufinfo, MP_BUFFER_READ); + mp_get_buffer_raise(dest, &destbufinfo, MP_BUFFER_WRITE); + validate_length(aes, srcbufinfo.len, destbufinfo.len); - memcpy(destbufinfo.buf, srcbufinfo.buf, srcbufinfo.len); + memcpy(destbufinfo.buf, srcbufinfo.buf, srcbufinfo.len); - common_hal_aesio_aes_encrypt(aes, (uint8_t *)destbufinfo.buf, - destbufinfo.len); - return mp_const_none; + common_hal_aesio_aes_encrypt(aes, (uint8_t *)destbufinfo.buf, + destbufinfo.len); + return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(aesio_aes_encrypt_into_obj, - aesio_aes_encrypt_into); + aesio_aes_encrypt_into); //| def decrypt_into(self, src: ReadableBuffer, dest: WriteableBuffer) -> None: //| """Decrypt the buffer from ``src`` into ``dest``. @@ -191,55 +191,55 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_3(aesio_aes_encrypt_into_obj, //| ... //| STATIC mp_obj_t aesio_aes_decrypt_into(mp_obj_t aesio_obj, mp_obj_t src, - mp_obj_t dest) { - if (!MP_OBJ_IS_TYPE(aesio_obj, &aesio_aes_type)) { - mp_raise_TypeError_varg(translate("Expected a %q"), aesio_aes_type.name); - } - // Convert parameters into expected types. - aesio_aes_obj_t *aes = MP_OBJ_TO_PTR(aesio_obj); + mp_obj_t dest) { + if (!MP_OBJ_IS_TYPE(aesio_obj, &aesio_aes_type)) { + mp_raise_TypeError_varg(translate("Expected a %q"), aesio_aes_type.name); + } + // Convert parameters into expected types. + aesio_aes_obj_t *aes = MP_OBJ_TO_PTR(aesio_obj); - mp_buffer_info_t srcbufinfo, destbufinfo; - mp_get_buffer_raise(src, &srcbufinfo, MP_BUFFER_READ); - mp_get_buffer_raise(dest, &destbufinfo, MP_BUFFER_WRITE); - validate_length(aes, srcbufinfo.len, destbufinfo.len); + mp_buffer_info_t srcbufinfo, destbufinfo; + mp_get_buffer_raise(src, &srcbufinfo, MP_BUFFER_READ); + mp_get_buffer_raise(dest, &destbufinfo, MP_BUFFER_WRITE); + validate_length(aes, srcbufinfo.len, destbufinfo.len); - memcpy(destbufinfo.buf, srcbufinfo.buf, srcbufinfo.len); + memcpy(destbufinfo.buf, srcbufinfo.buf, srcbufinfo.len); - common_hal_aesio_aes_decrypt(aes, (uint8_t *)destbufinfo.buf, - destbufinfo.len); - return mp_const_none; + common_hal_aesio_aes_decrypt(aes, (uint8_t *)destbufinfo.buf, + destbufinfo.len); + return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_3(aesio_aes_decrypt_into_obj, - aesio_aes_decrypt_into); + aesio_aes_decrypt_into); STATIC mp_obj_t aesio_aes_get_mode(mp_obj_t aesio_obj) { - if (!MP_OBJ_IS_TYPE(aesio_obj, &aesio_aes_type)) { - mp_raise_TypeError_varg(translate("Expected a %q"), aesio_aes_type.name); - } - aesio_aes_obj_t *self = MP_OBJ_TO_PTR(aesio_obj); - return MP_OBJ_NEW_SMALL_INT(self->mode); + if (!MP_OBJ_IS_TYPE(aesio_obj, &aesio_aes_type)) { + mp_raise_TypeError_varg(translate("Expected a %q"), aesio_aes_type.name); + } + aesio_aes_obj_t *self = MP_OBJ_TO_PTR(aesio_obj); + return MP_OBJ_NEW_SMALL_INT(self->mode); } MP_DEFINE_CONST_FUN_OBJ_1(aesio_aes_get_mode_obj, aesio_aes_get_mode); STATIC mp_obj_t aesio_aes_set_mode(mp_obj_t aesio_obj, mp_obj_t mode_obj) { - if (!MP_OBJ_IS_TYPE(aesio_obj, &aesio_aes_type)) { - mp_raise_TypeError_varg(translate("Expected a %q"), aesio_aes_type.name); - } - aesio_aes_obj_t *self = MP_OBJ_TO_PTR(aesio_obj); + if (!MP_OBJ_IS_TYPE(aesio_obj, &aesio_aes_type)) { + mp_raise_TypeError_varg(translate("Expected a %q"), aesio_aes_type.name); + } + aesio_aes_obj_t *self = MP_OBJ_TO_PTR(aesio_obj); - int mode = mp_obj_get_int(mode_obj); - switch (mode) { - case AES_MODE_CBC: - case AES_MODE_ECB: - case AES_MODE_CTR: - break; - default: - mp_raise_TypeError(translate("Requested AES mode is unsupported")); - } + int mode = mp_obj_get_int(mode_obj); + switch (mode) { + case AES_MODE_CBC: + case AES_MODE_ECB: + case AES_MODE_CTR: + break; + default: + mp_raise_TypeError(translate("Requested AES mode is unsupported")); + } - common_hal_aesio_aes_set_mode(self, mode); - return mp_const_none; + common_hal_aesio_aes_set_mode(self, mode); + return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(aesio_aes_set_mode_obj, aesio_aes_set_mode); diff --git a/shared-bindings/alarm/SleepMemory.c b/shared-bindings/alarm/SleepMemory.c index aed24827ad..9ca0ec0472 100644 --- a/shared-bindings/alarm/SleepMemory.c +++ b/shared-bindings/alarm/SleepMemory.c @@ -67,9 +67,12 @@ STATIC mp_obj_t alarm_sleep_memory_unary_op(mp_unary_op_t op, mp_obj_t self_in) alarm_sleep_memory_obj_t *self = MP_OBJ_TO_PTR(self_in); uint16_t len = common_hal_alarm_sleep_memory_get_length(self); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -100,7 +103,7 @@ STATIC mp_obj_t alarm_sleep_memory_subscr(mp_obj_t self_in, mp_obj_t index_in, m } else { alarm_sleep_memory_obj_t *self = MP_OBJ_TO_PTR(self_in); if (0) { -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE } else if (MP_OBJ_IS_TYPE(index_in, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(common_hal_alarm_sleep_memory_get_length(self), index_in, &slice)) { @@ -110,11 +113,11 @@ STATIC mp_obj_t alarm_sleep_memory_subscr(mp_obj_t self_in, mp_obj_t index_in, m #if MICROPY_PY_ARRAY_SLICE_ASSIGN // Assign size_t src_len = slice.stop - slice.start; - uint8_t* src_items; + uint8_t *src_items; if (MP_OBJ_IS_TYPE(value, &mp_type_array) || - MP_OBJ_IS_TYPE(value, &mp_type_bytearray) || - MP_OBJ_IS_TYPE(value, &mp_type_memoryview) || - MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { + MP_OBJ_IS_TYPE(value, &mp_type_bytearray) || + MP_OBJ_IS_TYPE(value, &mp_type_memoryview) || + MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(value, &bufinfo, MP_BUFFER_READ); if (bufinfo.len != src_len) { @@ -143,11 +146,11 @@ STATIC mp_obj_t alarm_sleep_memory_subscr(mp_obj_t self_in, mp_obj_t index_in, m common_hal_alarm_sleep_memory_get_bytes(self, slice.start, items, len); return mp_obj_new_bytearray_by_ref(len, items); } -#endif + #endif } else { // Single index rather than slice. size_t index = mp_get_index(self->base.type, common_hal_alarm_sleep_memory_get_length(self), - index_in, false); + index_in, false); if (value == MP_OBJ_SENTINEL) { // load uint8_t value_out; diff --git a/shared-bindings/alarm/SleepMemory.h b/shared-bindings/alarm/SleepMemory.h index e7a56521b9..c1667ec883 100644 --- a/shared-bindings/alarm/SleepMemory.h +++ b/shared-bindings/alarm/SleepMemory.h @@ -34,7 +34,7 @@ extern const mp_obj_type_t alarm_sleep_memory_type; uint32_t common_hal_alarm_sleep_memory_get_length(alarm_sleep_memory_obj_t *self); -bool common_hal_alarm_sleep_memory_set_bytes(alarm_sleep_memory_obj_t *self, uint32_t start_index, const uint8_t* values, uint32_t len); -void common_hal_alarm_sleep_memory_get_bytes(alarm_sleep_memory_obj_t *self, uint32_t start_index, uint8_t* values, uint32_t len); +bool common_hal_alarm_sleep_memory_set_bytes(alarm_sleep_memory_obj_t *self, uint32_t start_index, const uint8_t *values, uint32_t len); +void common_hal_alarm_sleep_memory_get_bytes(alarm_sleep_memory_obj_t *self, uint32_t start_index, uint8_t *values, uint32_t len); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_ALARM_SLEEPMEMORY_H diff --git a/shared-bindings/alarm/__init__.c b/shared-bindings/alarm/__init__.c index 7023c70e5d..a7af63f02f 100644 --- a/shared-bindings/alarm/__init__.c +++ b/shared-bindings/alarm/__init__.c @@ -168,7 +168,7 @@ STATIC MP_DEFINE_CONST_DICT(alarm_pin_globals, alarm_pin_globals_table); STATIC const mp_obj_module_t alarm_pin_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&alarm_pin_globals, + .globals = (mp_obj_dict_t *)&alarm_pin_globals, }; STATIC const mp_map_elem_t alarm_time_globals_table[] = { @@ -181,7 +181,7 @@ STATIC MP_DEFINE_CONST_DICT(alarm_time_globals, alarm_time_globals_table); STATIC const mp_obj_module_t alarm_time_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&alarm_time_globals, + .globals = (mp_obj_dict_t *)&alarm_time_globals, }; STATIC const mp_map_elem_t alarm_touch_globals_table[] = { @@ -193,7 +193,7 @@ STATIC MP_DEFINE_CONST_DICT(alarm_touch_globals, alarm_touch_globals_table); STATIC const mp_obj_module_t alarm_touch_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&alarm_touch_globals, + .globals = (mp_obj_dict_t *)&alarm_touch_globals, }; // The module table is mutable because .wake_alarm is a mutable attribute. @@ -205,7 +205,7 @@ STATIC mp_map_elem_t alarm_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_light_sleep_until_alarms), MP_OBJ_FROM_PTR(&alarm_light_sleep_until_alarms_obj) }, { MP_ROM_QSTR(MP_QSTR_exit_and_deep_sleep_until_alarms), - MP_OBJ_FROM_PTR(&alarm_exit_and_deep_sleep_until_alarms_obj) }, + MP_OBJ_FROM_PTR(&alarm_exit_and_deep_sleep_until_alarms_obj) }, { MP_ROM_QSTR(MP_QSTR_pin), MP_OBJ_FROM_PTR(&alarm_pin_module) }, { MP_ROM_QSTR(MP_QSTR_time), MP_OBJ_FROM_PTR(&alarm_time_module) }, @@ -240,5 +240,5 @@ void alarm_save_wake_alarm(void) { const mp_obj_module_t alarm_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&alarm_module_globals, + .globals = (mp_obj_dict_t *)&alarm_module_globals, }; diff --git a/shared-bindings/alarm/pin/PinAlarm.c b/shared-bindings/alarm/pin/PinAlarm.c index 89de016bcc..04063e89c2 100644 --- a/shared-bindings/alarm/pin/PinAlarm.c +++ b/shared-bindings/alarm/pin/PinAlarm.c @@ -89,7 +89,7 @@ STATIC mp_obj_t alarm_pin_pinalarm_make_new(const mp_obj_type_t *type, mp_uint_t //| STATIC mp_obj_t alarm_pin_pinalarm_obj_get_pin(mp_obj_t self_in) { alarm_pin_pinalarm_obj_t *self = MP_OBJ_TO_PTR(self_in); - mcu_pin_obj_t* pin = common_hal_alarm_pin_pinalarm_get_pin(self); + mcu_pin_obj_t *pin = common_hal_alarm_pin_pinalarm_get_pin(self); if (pin == NULL) { return mp_const_none; } diff --git a/shared-bindings/alarm/time/TimeAlarm.c b/shared-bindings/alarm/time/TimeAlarm.c index 1c9b8d37c5..46d6234897 100644 --- a/shared-bindings/alarm/time/TimeAlarm.c +++ b/shared-bindings/alarm/time/TimeAlarm.c @@ -57,7 +57,7 @@ mp_obj_t MP_WEAK rtc_get_time_source_time(void) { //| ... //| STATIC mp_obj_t alarm_time_timealarm_make_new(const mp_obj_type_t *type, - mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { alarm_time_timealarm_obj_t *self = m_new_obj(alarm_time_timealarm_obj_t); self->base.type = &alarm_time_timealarm_type; @@ -85,20 +85,20 @@ STATIC mp_obj_t alarm_time_timealarm_make_new(const mp_obj_type_t *type, mp_float_t monotonic_time_now = common_hal_time_monotonic_ms() / 1000.0; if (have_epoch) { -#if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE + #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE mp_raise_ValueError(translate("epoch_time not supported on this board")); -#else + #else mp_uint_t epoch_time_secs = mp_obj_int_get_checked(args[ARG_epoch_time].u_obj); timeutils_struct_time_t tm; struct_time_to_tm(rtc_get_time_source_time(), &tm); mp_uint_t epoch_secs_now = timeutils_seconds_since_epoch(tm.tm_year, tm.tm_mon, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec); + tm.tm_hour, tm.tm_min, tm.tm_sec); // How far in the future (in secs) is the requested time? mp_int_t epoch_diff = epoch_time_secs - epoch_secs_now; // Convert it to a future monotonic time. monotonic_time = monotonic_time_now + epoch_diff; -#endif + #endif } if (monotonic_time < monotonic_time_now) { diff --git a/shared-bindings/alarm/touch/TouchAlarm.c b/shared-bindings/alarm/touch/TouchAlarm.c index 4259b71bdf..589229de8e 100644 --- a/shared-bindings/alarm/touch/TouchAlarm.c +++ b/shared-bindings/alarm/touch/TouchAlarm.c @@ -43,7 +43,7 @@ //| ... //| STATIC mp_obj_t alarm_touch_touchalarm_make_new(const mp_obj_type_t *type, - mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { alarm_touch_touchalarm_obj_t *self = m_new_obj(alarm_touch_touchalarm_obj_t); self->base.type = &alarm_touch_touchalarm_type; diff --git a/shared-bindings/analogio/AnalogIn.c b/shared-bindings/analogio/AnalogIn.c index 328466b0d6..a7756b617e 100644 --- a/shared-bindings/analogio/AnalogIn.c +++ b/shared-bindings/analogio/AnalogIn.c @@ -56,7 +56,7 @@ //| ... //| STATIC mp_obj_t analogio_analogin_make_new(const mp_obj_type_t *type, - mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { + mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { // check number of arguments mp_arg_check_num(n_args, kw_args, 1, 1, false); @@ -75,9 +75,9 @@ STATIC mp_obj_t analogio_analogin_make_new(const mp_obj_type_t *type, //| ... //| STATIC mp_obj_t analogio_analogin_deinit(mp_obj_t self_in) { - analogio_analogin_obj_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_analogio_analogin_deinit(self); - return mp_const_none; + analogio_analogin_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_analogio_analogin_deinit(self); + return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(analogio_analogin_deinit_obj, analogio_analogin_deinit); @@ -140,7 +140,7 @@ STATIC mp_obj_t analogio_analogin_obj_get_reference_voltage(mp_obj_t self_in) { } } MP_DEFINE_CONST_FUN_OBJ_1(analogio_analogin_get_reference_voltage_obj, - analogio_analogin_obj_get_reference_voltage); + analogio_analogin_obj_get_reference_voltage); const mp_obj_property_t analogio_analogin_reference_voltage_obj = { .base.type = &mp_type_property, diff --git a/shared-bindings/analogio/AnalogIn.h b/shared-bindings/analogio/AnalogIn.h index 32f11e08f5..9f80416267 100644 --- a/shared-bindings/analogio/AnalogIn.h +++ b/shared-bindings/analogio/AnalogIn.h @@ -32,10 +32,10 @@ extern const mp_obj_type_t analogio_analogin_type; -void common_hal_analogio_analogin_construct(analogio_analogin_obj_t* self, const mcu_pin_obj_t *pin); -void common_hal_analogio_analogin_deinit(analogio_analogin_obj_t* self); -bool common_hal_analogio_analogin_deinited(analogio_analogin_obj_t* self); -uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t* self); -float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t* self); +void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, const mcu_pin_obj_t *pin); +void common_hal_analogio_analogin_deinit(analogio_analogin_obj_t *self); +bool common_hal_analogio_analogin_deinited(analogio_analogin_obj_t *self); +uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self); +float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t *self); #endif // __MICROPY_INCLUDED_SHARED_BINDINGS_ANALOGIO_ANALOGIN_H__ diff --git a/shared-bindings/analogio/AnalogOut.c b/shared-bindings/analogio/AnalogOut.c index f3321a7250..f655228285 100644 --- a/shared-bindings/analogio/AnalogOut.c +++ b/shared-bindings/analogio/AnalogOut.c @@ -104,16 +104,16 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(analogio_analogout___exit___obj, 4, 4 //| resolution, the value is 16-bit.""" //| STATIC mp_obj_t analogio_analogout_obj_set_value(mp_obj_t self_in, mp_obj_t value) { - analogio_analogout_obj_t *self = MP_OBJ_TO_PTR(self_in); - if (common_hal_analogio_analogout_deinited(self)) { - raise_deinited_error(); - } - uint32_t v = mp_obj_get_int(value); - if (v >= (1 << 16)) { - mp_raise_ValueError(translate("AnalogOut is only 16 bits. Value must be less than 65536.")); - } - common_hal_analogio_analogout_set_value(self, v); - return mp_const_none; + analogio_analogout_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (common_hal_analogio_analogout_deinited(self)) { + raise_deinited_error(); + } + uint32_t v = mp_obj_get_int(value); + if (v >= (1 << 16)) { + mp_raise_ValueError(translate("AnalogOut is only 16 bits. Value must be less than 65536.")); + } + common_hal_analogio_analogout_set_value(self, v); + return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(analogio_analogout_set_value_obj, analogio_analogout_obj_set_value); diff --git a/shared-bindings/analogio/AnalogOut.h b/shared-bindings/analogio/AnalogOut.h index e4e94548b8..736afd0019 100644 --- a/shared-bindings/analogio/AnalogOut.h +++ b/shared-bindings/analogio/AnalogOut.h @@ -32,7 +32,7 @@ extern const mp_obj_type_t analogio_analogout_type; -void common_hal_analogio_analogout_construct(analogio_analogout_obj_t* self, const mcu_pin_obj_t *pin); +void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, const mcu_pin_obj_t *pin); void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self); bool common_hal_analogio_analogout_deinited(analogio_analogout_obj_t *self); void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, uint16_t value); diff --git a/shared-bindings/analogio/__init__.c b/shared-bindings/analogio/__init__.c index 1f059f3402..4e5aebf010 100644 --- a/shared-bindings/analogio/__init__.c +++ b/shared-bindings/analogio/__init__.c @@ -70,5 +70,5 @@ STATIC MP_DEFINE_CONST_DICT(analogio_module_globals, analogio_module_globals_tab const mp_obj_module_t analogio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&analogio_module_globals, + .globals = (mp_obj_dict_t *)&analogio_module_globals, }; diff --git a/shared-bindings/audiobusio/I2SOut.c b/shared-bindings/audiobusio/I2SOut.c index 25b536c344..b174cf3a57 100644 --- a/shared-bindings/audiobusio/I2SOut.c +++ b/shared-bindings/audiobusio/I2SOut.c @@ -91,10 +91,10 @@ //| ... //| STATIC mp_obj_t audiobusio_i2sout_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { -#if !CIRCUITPY_AUDIOBUSIO_I2SOUT + #if !CIRCUITPY_AUDIOBUSIO_I2SOUT mp_raise_NotImplementedError(translate("I2SOut not available")); return NULL; // Not reachable. -#else + #else enum { ARG_bit_clock, ARG_word_select, ARG_data, ARG_left_justified }; static const mp_arg_t allowed_args[] = { { MP_QSTR_bit_clock, MP_ARG_OBJ | MP_ARG_REQUIRED }, @@ -114,7 +114,7 @@ STATIC mp_obj_t audiobusio_i2sout_make_new(const mp_obj_type_t *type, size_t n_a common_hal_audiobusio_i2sout_construct(self, bit_clock, word_select, data, args[ARG_left_justified].u_bool); return MP_OBJ_FROM_PTR(self); -#endif + #endif } #if CIRCUITPY_AUDIOBUSIO_I2SOUT @@ -263,7 +263,7 @@ const mp_obj_property_t audiobusio_i2sout_paused_obj = { STATIC const mp_rom_map_elem_t audiobusio_i2sout_locals_dict_table[] = { // Methods -#if CIRCUITPY_AUDIOBUSIO_I2SOUT + #if CIRCUITPY_AUDIOBUSIO_I2SOUT { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiobusio_i2sout_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiobusio_i2sout_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, @@ -276,7 +276,7 @@ STATIC const mp_rom_map_elem_t audiobusio_i2sout_locals_dict_table[] = { // Properties { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiobusio_i2sout_playing_obj) }, { MP_ROM_QSTR(MP_QSTR_paused), MP_ROM_PTR(&audiobusio_i2sout_paused_obj) }, -#endif // CIRCUITPY_AUDIOBUSIO_I2SOUT + #endif // CIRCUITPY_AUDIOBUSIO_I2SOUT }; STATIC MP_DEFINE_CONST_DICT(audiobusio_i2sout_locals_dict, audiobusio_i2sout_locals_dict_table); @@ -284,5 +284,5 @@ const mp_obj_type_t audiobusio_i2sout_type = { { &mp_type_type }, .name = MP_QSTR_I2SOut, .make_new = audiobusio_i2sout_make_new, - .locals_dict = (mp_obj_dict_t*)&audiobusio_i2sout_locals_dict, + .locals_dict = (mp_obj_dict_t *)&audiobusio_i2sout_locals_dict, }; diff --git a/shared-bindings/audiobusio/I2SOut.h b/shared-bindings/audiobusio/I2SOut.h index 55527dc730..64dcc3bf68 100644 --- a/shared-bindings/audiobusio/I2SOut.h +++ b/shared-bindings/audiobusio/I2SOut.h @@ -35,18 +35,18 @@ extern const mp_obj_type_t audiobusio_i2sout_type; // Some boards don't have the I2SOut pins available. #if CIRCUITPY_AUDIOBUSIO_I2SOUT -void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t* self, - const mcu_pin_obj_t* bit_clock, const mcu_pin_obj_t* word_select, const mcu_pin_obj_t* data, +void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, + const mcu_pin_obj_t *bit_clock, const mcu_pin_obj_t *word_select, const mcu_pin_obj_t *data, bool left_justified); -void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t* self); -bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t* self); -void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t* self, mp_obj_t sample, bool loop); -void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t* self); -bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t* self); -void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t* self); -void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t* self); -bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t* self); +void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self); +bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t *self); +void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t *self); +bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t *self); +void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t *self); +void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t *self); +bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t *self); #endif // CIRCUITPY_AUDIOBUSIO_I2SOUT diff --git a/shared-bindings/audiobusio/PDMIn.c b/shared-bindings/audiobusio/PDMIn.c index a3cc8b07e9..5a648e1651 100644 --- a/shared-bindings/audiobusio/PDMIn.c +++ b/shared-bindings/audiobusio/PDMIn.c @@ -84,9 +84,9 @@ //| ... //| STATIC mp_obj_t audiobusio_pdmin_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { -#if !CIRCUITPY_AUDIOBUSIO_PDMIN + #if !CIRCUITPY_AUDIOBUSIO_PDMIN mp_raise_NotImplementedError(translate("PDMIn not available")); -#else + #else enum { ARG_clock_pin, ARG_data_pin, ARG_sample_rate, ARG_bit_depth, ARG_mono, ARG_oversample, ARG_startup_delay }; static const mp_arg_t allowed_args[] = { { MP_QSTR_clock_pin, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -129,13 +129,13 @@ STATIC mp_obj_t audiobusio_pdmin_make_new(const mp_obj_type_t *type, size_t n_ar } common_hal_audiobusio_pdmin_construct(self, clock_pin, data_pin, sample_rate, - bit_depth, mono, oversample); + bit_depth, mono, oversample); // Wait for the microphone to start up. Some start in 10 msecs; some take as much as 100 msecs. mp_hal_delay_ms(startup_delay * 1000); return MP_OBJ_FROM_PTR(self); -#endif + #endif } #if CIRCUITPY_AUDIOBUSIO_PDMIN @@ -248,7 +248,7 @@ const mp_obj_type_t audiobusio_pdmin_type = { { &mp_type_type }, .name = MP_QSTR_PDMIn, .make_new = audiobusio_pdmin_make_new, -#if CIRCUITPY_AUDIOBUSIO_PDMIN - .locals_dict = (mp_obj_dict_t*)&audiobusio_pdmin_locals_dict, -#endif + #if CIRCUITPY_AUDIOBUSIO_PDMIN + .locals_dict = (mp_obj_dict_t *)&audiobusio_pdmin_locals_dict, + #endif }; diff --git a/shared-bindings/audiobusio/PDMIn.h b/shared-bindings/audiobusio/PDMIn.h index e89fc7e232..0516bce619 100644 --- a/shared-bindings/audiobusio/PDMIn.h +++ b/shared-bindings/audiobusio/PDMIn.h @@ -34,15 +34,15 @@ extern const mp_obj_type_t audiobusio_pdmin_type; #if CIRCUITPY_AUDIOBUSIO_PDMIN -void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t* self, - const mcu_pin_obj_t* clock_pin, const mcu_pin_obj_t* data_pin, +void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, + const mcu_pin_obj_t *clock_pin, const mcu_pin_obj_t *data_pin, uint32_t sample_rate, uint8_t bit_depth, bool mono, uint8_t oversample); -void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t* self); -bool common_hal_audiobusio_pdmin_deinited(audiobusio_pdmin_obj_t* self); -uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t* self, - uint16_t* buffer, uint32_t length); -uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t* self); -uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t* self); +void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t *self); +bool common_hal_audiobusio_pdmin_deinited(audiobusio_pdmin_obj_t *self); +uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t *self, + uint16_t *buffer, uint32_t length); +uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t *self); +uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t *self); // TODO(tannewt): Add record to file #endif diff --git a/shared-bindings/audiobusio/__init__.c b/shared-bindings/audiobusio/__init__.c index 89ccbb88b5..23e246ec22 100644 --- a/shared-bindings/audiobusio/__init__.c +++ b/shared-bindings/audiobusio/__init__.c @@ -56,5 +56,5 @@ STATIC MP_DEFINE_CONST_DICT(audiobusio_module_globals, audiobusio_module_globals const mp_obj_module_t audiobusio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&audiobusio_module_globals, + .globals = (mp_obj_dict_t *)&audiobusio_module_globals, }; diff --git a/shared-bindings/audiocore/RawSample.c b/shared-bindings/audiocore/RawSample.c index df31ee2e07..23a2d3f0be 100644 --- a/shared-bindings/audiocore/RawSample.c +++ b/shared-bindings/audiocore/RawSample.c @@ -91,9 +91,9 @@ STATIC mp_obj_t audioio_rawsample_make_new(const mp_obj_type_t *type, size_t n_a } else if (bufinfo.typecode != 'b' && bufinfo.typecode != 'B' && bufinfo.typecode != BYTEARRAY_TYPECODE) { mp_raise_ValueError(translate("sample_source buffer must be a bytearray or array of type 'h', 'H', 'b' or 'B'")); } - common_hal_audioio_rawsample_construct(self, ((uint8_t*)bufinfo.buf), bufinfo.len, - bytes_per_sample, signed_samples, args[ARG_channel_count].u_int, - args[ARG_sample_rate].u_int); + common_hal_audioio_rawsample_construct(self, ((uint8_t *)bufinfo.buf), bufinfo.len, + bytes_per_sample, signed_samples, args[ARG_channel_count].u_int, + args[ARG_sample_rate].u_int); } else { mp_raise_TypeError(translate("buffer must be a bytes-like object")); } @@ -189,6 +189,6 @@ const mp_obj_type_t audioio_rawsample_type = { { &mp_type_type }, .name = MP_QSTR_RawSample, .make_new = audioio_rawsample_make_new, - .locals_dict = (mp_obj_dict_t*)&audioio_rawsample_locals_dict, + .locals_dict = (mp_obj_dict_t *)&audioio_rawsample_locals_dict, .protocol = &audioio_rawsample_proto, }; diff --git a/shared-bindings/audiocore/RawSample.h b/shared-bindings/audiocore/RawSample.h index 61f61a0662..b07add2dd1 100644 --- a/shared-bindings/audiocore/RawSample.h +++ b/shared-bindings/audiocore/RawSample.h @@ -32,15 +32,15 @@ extern const mp_obj_type_t audioio_rawsample_type; -void common_hal_audioio_rawsample_construct(audioio_rawsample_obj_t* self, - uint8_t* buffer, uint32_t len, uint8_t bytes_per_sample, bool samples_signed, +void common_hal_audioio_rawsample_construct(audioio_rawsample_obj_t *self, + uint8_t *buffer, uint32_t len, uint8_t bytes_per_sample, bool samples_signed, uint8_t channel_count, uint32_t sample_rate); -void common_hal_audioio_rawsample_deinit(audioio_rawsample_obj_t* self); -bool common_hal_audioio_rawsample_deinited(audioio_rawsample_obj_t* self); -uint32_t common_hal_audioio_rawsample_get_sample_rate(audioio_rawsample_obj_t* self); -uint8_t common_hal_audioio_rawsample_get_bits_per_sample(audioio_rawsample_obj_t* self); -uint8_t common_hal_audioio_rawsample_get_channel_count(audioio_rawsample_obj_t* self); -void common_hal_audioio_rawsample_set_sample_rate(audioio_rawsample_obj_t* self, uint32_t sample_rate); +void common_hal_audioio_rawsample_deinit(audioio_rawsample_obj_t *self); +bool common_hal_audioio_rawsample_deinited(audioio_rawsample_obj_t *self); +uint32_t common_hal_audioio_rawsample_get_sample_rate(audioio_rawsample_obj_t *self); +uint8_t common_hal_audioio_rawsample_get_bits_per_sample(audioio_rawsample_obj_t *self); +uint8_t common_hal_audioio_rawsample_get_channel_count(audioio_rawsample_obj_t *self); +void common_hal_audioio_rawsample_set_sample_rate(audioio_rawsample_obj_t *self, uint32_t sample_rate); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOIO_RAWSAMPLE_H diff --git a/shared-bindings/audiocore/WaveFile.c b/shared-bindings/audiocore/WaveFile.c index 3b4c9fd978..73943f980f 100644 --- a/shared-bindings/audiocore/WaveFile.c +++ b/shared-bindings/audiocore/WaveFile.c @@ -86,7 +86,7 @@ STATIC mp_obj_t audioio_wavefile_make_new(const mp_obj_type_t *type, size_t n_ar buffer_size = bufinfo.len; } common_hal_audioio_wavefile_construct(self, MP_OBJ_TO_PTR(args[0]), - buffer, buffer_size); + buffer, buffer_size); return MP_OBJ_FROM_PTR(self); } @@ -214,6 +214,6 @@ const mp_obj_type_t audioio_wavefile_type = { { &mp_type_type }, .name = MP_QSTR_WaveFile, .make_new = audioio_wavefile_make_new, - .locals_dict = (mp_obj_dict_t*)&audioio_wavefile_locals_dict, + .locals_dict = (mp_obj_dict_t *)&audioio_wavefile_locals_dict, .protocol = &audioio_wavefile_proto, }; diff --git a/shared-bindings/audiocore/WaveFile.h b/shared-bindings/audiocore/WaveFile.h index f4a1723192..29140b4a2b 100644 --- a/shared-bindings/audiocore/WaveFile.h +++ b/shared-bindings/audiocore/WaveFile.h @@ -34,14 +34,14 @@ extern const mp_obj_type_t audioio_wavefile_type; -void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t* self, - pyb_file_obj_t* file, uint8_t *buffer, size_t buffer_size); +void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t *self, + pyb_file_obj_t *file, uint8_t *buffer, size_t buffer_size); -void common_hal_audioio_wavefile_deinit(audioio_wavefile_obj_t* self); -bool common_hal_audioio_wavefile_deinited(audioio_wavefile_obj_t* self); -uint32_t common_hal_audioio_wavefile_get_sample_rate(audioio_wavefile_obj_t* self); -void common_hal_audioio_wavefile_set_sample_rate(audioio_wavefile_obj_t* self, uint32_t sample_rate); -uint8_t common_hal_audioio_wavefile_get_bits_per_sample(audioio_wavefile_obj_t* self); -uint8_t common_hal_audioio_wavefile_get_channel_count(audioio_wavefile_obj_t* self); +void common_hal_audioio_wavefile_deinit(audioio_wavefile_obj_t *self); +bool common_hal_audioio_wavefile_deinited(audioio_wavefile_obj_t *self); +uint32_t common_hal_audioio_wavefile_get_sample_rate(audioio_wavefile_obj_t *self); +void common_hal_audioio_wavefile_set_sample_rate(audioio_wavefile_obj_t *self, uint32_t sample_rate); +uint8_t common_hal_audioio_wavefile_get_bits_per_sample(audioio_wavefile_obj_t *self); +uint8_t common_hal_audioio_wavefile_get_channel_count(audioio_wavefile_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOIO_WAVEFILE_H diff --git a/shared-bindings/audiocore/__init__.c b/shared-bindings/audiocore/__init__.c index b400b94548..9fe4a81c4c 100644 --- a/shared-bindings/audiocore/__init__.c +++ b/shared-bindings/audiocore/__init__.c @@ -33,7 +33,7 @@ #include "shared-bindings/audiocore/__init__.h" #include "shared-bindings/audiocore/RawSample.h" #include "shared-bindings/audiocore/WaveFile.h" -//#include "shared-bindings/audiomixer/Mixer.h" +// #include "shared-bindings/audiomixer/Mixer.h" //| """Support for audio samples""" //| @@ -48,5 +48,5 @@ STATIC MP_DEFINE_CONST_DICT(audiocore_module_globals, audiocore_module_globals_t const mp_obj_module_t audiocore_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&audiocore_module_globals, + .globals = (mp_obj_dict_t *)&audiocore_module_globals, }; diff --git a/shared-bindings/audioio/AudioOut.c b/shared-bindings/audioio/AudioOut.c index 0d479be097..6a6aeea597 100644 --- a/shared-bindings/audioio/AudioOut.c +++ b/shared-bindings/audioio/AudioOut.c @@ -273,5 +273,5 @@ const mp_obj_type_t audioio_audioout_type = { { &mp_type_type }, .name = MP_QSTR_AudioOut, .make_new = audioio_audioout_make_new, - .locals_dict = (mp_obj_dict_t*)&audioio_audioout_locals_dict, + .locals_dict = (mp_obj_dict_t *)&audioio_audioout_locals_dict, }; diff --git a/shared-bindings/audioio/AudioOut.h b/shared-bindings/audioio/AudioOut.h index 1076ac5ccc..163d7848b4 100644 --- a/shared-bindings/audioio/AudioOut.h +++ b/shared-bindings/audioio/AudioOut.h @@ -34,16 +34,16 @@ extern const mp_obj_type_t audioio_audioout_type; // left_channel will always be non-NULL but right_channel may be for mono output. -void common_hal_audioio_audioout_construct(audioio_audioout_obj_t* self, - const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t default_value); +void common_hal_audioio_audioout_construct(audioio_audioout_obj_t *self, + const mcu_pin_obj_t *left_channel, const mcu_pin_obj_t *right_channel, uint16_t default_value); -void common_hal_audioio_audioout_deinit(audioio_audioout_obj_t* self); -bool common_hal_audioio_audioout_deinited(audioio_audioout_obj_t* self); -void common_hal_audioio_audioout_play(audioio_audioout_obj_t* self, mp_obj_t sample, bool loop); -void common_hal_audioio_audioout_stop(audioio_audioout_obj_t* self); -bool common_hal_audioio_audioout_get_playing(audioio_audioout_obj_t* self); -void common_hal_audioio_audioout_pause(audioio_audioout_obj_t* self); -void common_hal_audioio_audioout_resume(audioio_audioout_obj_t* self); -bool common_hal_audioio_audioout_get_paused(audioio_audioout_obj_t* self); +void common_hal_audioio_audioout_deinit(audioio_audioout_obj_t *self); +bool common_hal_audioio_audioout_deinited(audioio_audioout_obj_t *self); +void common_hal_audioio_audioout_play(audioio_audioout_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audioio_audioout_stop(audioio_audioout_obj_t *self); +bool common_hal_audioio_audioout_get_playing(audioio_audioout_obj_t *self); +void common_hal_audioio_audioout_pause(audioio_audioout_obj_t *self); +void common_hal_audioio_audioout_resume(audioio_audioout_obj_t *self); +bool common_hal_audioio_audioout_get_paused(audioio_audioout_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOIO_AUDIOOUT_H diff --git a/shared-bindings/audioio/__init__.c b/shared-bindings/audioio/__init__.c index a9c58e8645..426f756d44 100644 --- a/shared-bindings/audioio/__init__.c +++ b/shared-bindings/audioio/__init__.c @@ -59,5 +59,5 @@ STATIC MP_DEFINE_CONST_DICT(audioio_module_globals, audioio_module_globals_table const mp_obj_module_t audioio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&audioio_module_globals, + .globals = (mp_obj_dict_t *)&audioio_module_globals, }; diff --git a/shared-bindings/audiomixer/Mixer.c b/shared-bindings/audiomixer/Mixer.c index 293b19b055..95619ca956 100644 --- a/shared-bindings/audiomixer/Mixer.c +++ b/shared-bindings/audiomixer/Mixer.c @@ -112,9 +112,9 @@ STATIC mp_obj_t audiomixer_mixer_make_new(const mp_obj_type_t *type, size_t n_ar self->base.type = &audiomixer_mixer_type; common_hal_audiomixer_mixer_construct(self, voice_count, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); - for(int v=0; vvoice[v] = audiomixer_mixervoice_type.make_new(&audiomixer_mixervoice_type, 0, 0, NULL); - common_hal_audiomixer_mixervoice_set_parent(self->voice[v], self); + for (int v = 0; v < voice_count; v++) { + self->voice[v] = audiomixer_mixervoice_type.make_new(&audiomixer_mixervoice_type, 0, 0, NULL); + common_hal_audiomixer_mixervoice_set_parent(self->voice[v], self); } self->voice_tuple = mp_obj_new_tuple(self->voice_count, self->voice); @@ -280,7 +280,7 @@ STATIC const mp_rom_map_elem_t audiomixer_mixer_locals_dict_table[] = { // Properties { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiomixer_mixer_playing_obj) }, { MP_ROM_QSTR(MP_QSTR_sample_rate), MP_ROM_PTR(&audiomixer_mixer_sample_rate_obj) }, - { MP_ROM_QSTR(MP_QSTR_voice), MP_ROM_PTR(&audiomixer_mixer_voice_obj) } + { MP_ROM_QSTR(MP_QSTR_voice), MP_ROM_PTR(&audiomixer_mixer_voice_obj) } }; STATIC MP_DEFINE_CONST_DICT(audiomixer_mixer_locals_dict, audiomixer_mixer_locals_dict_table); @@ -298,6 +298,6 @@ const mp_obj_type_t audiomixer_mixer_type = { { &mp_type_type }, .name = MP_QSTR_Mixer, .make_new = audiomixer_mixer_make_new, - .locals_dict = (mp_obj_dict_t*)&audiomixer_mixer_locals_dict, + .locals_dict = (mp_obj_dict_t *)&audiomixer_mixer_locals_dict, .protocol = &audiomixer_mixer_proto, }; diff --git a/shared-bindings/audiomixer/Mixer.h b/shared-bindings/audiomixer/Mixer.h index a99e1bf62a..88592a1cb3 100644 --- a/shared-bindings/audiomixer/Mixer.h +++ b/shared-bindings/audiomixer/Mixer.h @@ -34,20 +34,20 @@ extern const mp_obj_type_t audiomixer_mixer_type; extern const mp_obj_type_t audiomixer_mixervoice_type; -void common_hal_audiomixer_mixer_construct(audiomixer_mixer_obj_t* self, - uint8_t voice_count, - uint32_t buffer_size, - uint8_t bits_per_sample, - bool samples_signed, - uint8_t channel_count, - uint32_t sample_rate); +void common_hal_audiomixer_mixer_construct(audiomixer_mixer_obj_t *self, + uint8_t voice_count, + uint32_t buffer_size, + uint8_t bits_per_sample, + bool samples_signed, + uint8_t channel_count, + uint32_t sample_rate); -void common_hal_audiomixer_mixer_deinit(audiomixer_mixer_obj_t* self); -bool common_hal_audiomixer_mixer_deinited(audiomixer_mixer_obj_t* self); +void common_hal_audiomixer_mixer_deinit(audiomixer_mixer_obj_t *self); +bool common_hal_audiomixer_mixer_deinited(audiomixer_mixer_obj_t *self); -bool common_hal_audiomixer_mixer_get_playing(audiomixer_mixer_obj_t* self); -uint32_t common_hal_audiomixer_mixer_get_sample_rate(audiomixer_mixer_obj_t* self); -uint8_t common_hal_audiomixer_mixer_get_channel_count(audiomixer_mixer_obj_t* self); -uint8_t common_hal_audiomixer_mixer_get_bits_per_sample(audiomixer_mixer_obj_t* self); +bool common_hal_audiomixer_mixer_get_playing(audiomixer_mixer_obj_t *self); +uint32_t common_hal_audiomixer_mixer_get_sample_rate(audiomixer_mixer_obj_t *self); +uint8_t common_hal_audiomixer_mixer_get_channel_count(audiomixer_mixer_obj_t *self); +uint8_t common_hal_audiomixer_mixer_get_bits_per_sample(audiomixer_mixer_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOMIXER_MIXER_H diff --git a/shared-bindings/audiomixer/MixerVoice.c b/shared-bindings/audiomixer/MixerVoice.c index af00e10551..c519f7ac40 100644 --- a/shared-bindings/audiomixer/MixerVoice.c +++ b/shared-bindings/audiomixer/MixerVoice.c @@ -117,7 +117,7 @@ STATIC mp_obj_t audiomixer_mixervoice_obj_set_level(size_t n_args, const mp_obj_ mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - float level = mp_obj_get_float(args[ARG_level].u_obj); + float level = mp_obj_get_float(args[ARG_level].u_obj); if (level > 1 || level < 0) { mp_raise_ValueError(translate("level must be between 0 and 1")); @@ -170,5 +170,5 @@ const mp_obj_type_t audiomixer_mixervoice_type = { { &mp_type_type }, .name = MP_QSTR_MixerVoice, .make_new = audiomixer_mixervoice_make_new, - .locals_dict = (mp_obj_dict_t*)&audiomixer_mixervoice_locals_dict, + .locals_dict = (mp_obj_dict_t *)&audiomixer_mixervoice_locals_dict, }; diff --git a/shared-bindings/audiomixer/MixerVoice.h b/shared-bindings/audiomixer/MixerVoice.h index 83098bc9dd..bce4632760 100644 --- a/shared-bindings/audiomixer/MixerVoice.h +++ b/shared-bindings/audiomixer/MixerVoice.h @@ -36,12 +36,12 @@ extern const mp_obj_type_t audiomixer_mixer_type; extern const mp_obj_type_t audiomixer_mixervoice_type; void common_hal_audiomixer_mixervoice_construct(audiomixer_mixervoice_obj_t *self); -void common_hal_audiomixer_mixervoice_set_parent(audiomixer_mixervoice_obj_t* self, audiomixer_mixer_obj_t *parent); -void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t* self, mp_obj_t sample, bool loop); -void common_hal_audiomixer_mixervoice_stop(audiomixer_mixervoice_obj_t* self); -float common_hal_audiomixer_mixervoice_get_level(audiomixer_mixervoice_obj_t* self); -void common_hal_audiomixer_mixervoice_set_level(audiomixer_mixervoice_obj_t* self, float gain); +void common_hal_audiomixer_mixervoice_set_parent(audiomixer_mixervoice_obj_t *self, audiomixer_mixer_obj_t *parent); +void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiomixer_mixervoice_stop(audiomixer_mixervoice_obj_t *self); +float common_hal_audiomixer_mixervoice_get_level(audiomixer_mixervoice_obj_t *self); +void common_hal_audiomixer_mixervoice_set_level(audiomixer_mixervoice_obj_t *self, float gain); -bool common_hal_audiomixer_mixervoice_get_playing(audiomixer_mixervoice_obj_t* self); +bool common_hal_audiomixer_mixervoice_get_playing(audiomixer_mixervoice_obj_t *self); #endif /* SHARED_BINDINGS_AUDIOMIXER_MIXERVOICE_H_ */ diff --git a/shared-bindings/audiomixer/__init__.c b/shared-bindings/audiomixer/__init__.c index 1146bb7981..9d0bf676fc 100644 --- a/shared-bindings/audiomixer/__init__.c +++ b/shared-bindings/audiomixer/__init__.c @@ -44,5 +44,5 @@ STATIC MP_DEFINE_CONST_DICT(audiomixer_module_globals, audiomixer_module_globals const mp_obj_module_t audiomixer_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&audiomixer_module_globals, + .globals = (mp_obj_dict_t *)&audiomixer_module_globals, }; diff --git a/shared-bindings/audiomp3/MP3Decoder.c b/shared-bindings/audiomp3/MP3Decoder.c index 85073bf89c..bdbd14e9e0 100644 --- a/shared-bindings/audiomp3/MP3Decoder.c +++ b/shared-bindings/audiomp3/MP3Decoder.c @@ -84,7 +84,7 @@ STATIC mp_obj_t audiomp3_mp3file_make_new(const mp_obj_type_t *type, size_t n_ar buffer_size = bufinfo.len; } common_hal_audiomp3_mp3file_construct(self, MP_OBJ_TO_PTR(args[0]), - buffer, buffer_size); + buffer, buffer_size); return MP_OBJ_FROM_PTR(self); } @@ -262,6 +262,6 @@ const mp_obj_type_t audiomp3_mp3file_type = { { &mp_type_type }, .name = MP_QSTR_MP3Decoder, .make_new = audiomp3_mp3file_make_new, - .locals_dict = (mp_obj_dict_t*)&audiomp3_mp3file_locals_dict, + .locals_dict = (mp_obj_dict_t *)&audiomp3_mp3file_locals_dict, .protocol = &audiomp3_mp3file_proto, }; diff --git a/shared-bindings/audiomp3/MP3Decoder.h b/shared-bindings/audiomp3/MP3Decoder.h index 36d525e938..2428cedf16 100644 --- a/shared-bindings/audiomp3/MP3Decoder.h +++ b/shared-bindings/audiomp3/MP3Decoder.h @@ -35,16 +35,16 @@ extern const mp_obj_type_t audiomp3_mp3file_type; -void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t* self, - pyb_file_obj_t* file, uint8_t *buffer, size_t buffer_size); +void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t *self, + pyb_file_obj_t *file, uint8_t *buffer, size_t buffer_size); -void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t* self, pyb_file_obj_t* file); -void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t* self); -bool common_hal_audiomp3_mp3file_deinited(audiomp3_mp3file_obj_t* self); -uint32_t common_hal_audiomp3_mp3file_get_sample_rate(audiomp3_mp3file_obj_t* self); -void common_hal_audiomp3_mp3file_set_sample_rate(audiomp3_mp3file_obj_t* self, uint32_t sample_rate); -uint8_t common_hal_audiomp3_mp3file_get_bits_per_sample(audiomp3_mp3file_obj_t* self); -uint8_t common_hal_audiomp3_mp3file_get_channel_count(audiomp3_mp3file_obj_t* self); -float common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t* self); +void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t *self, pyb_file_obj_t *file); +void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t *self); +bool common_hal_audiomp3_mp3file_deinited(audiomp3_mp3file_obj_t *self); +uint32_t common_hal_audiomp3_mp3file_get_sample_rate(audiomp3_mp3file_obj_t *self); +void common_hal_audiomp3_mp3file_set_sample_rate(audiomp3_mp3file_obj_t *self, uint32_t sample_rate); +uint8_t common_hal_audiomp3_mp3file_get_bits_per_sample(audiomp3_mp3file_obj_t *self); +uint8_t common_hal_audiomp3_mp3file_get_channel_count(audiomp3_mp3file_obj_t *self); +float common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOIO_MP3FILE_H diff --git a/shared-bindings/audiomp3/__init__.c b/shared-bindings/audiomp3/__init__.c index 62e5f56cbb..29bdd0bb21 100644 --- a/shared-bindings/audiomp3/__init__.c +++ b/shared-bindings/audiomp3/__init__.c @@ -43,5 +43,5 @@ STATIC MP_DEFINE_CONST_DICT(audiomp3_module_globals, audiomp3_module_globals_tab const mp_obj_module_t audiomp3_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&audiomp3_module_globals, + .globals = (mp_obj_dict_t *)&audiomp3_module_globals, }; diff --git a/shared-bindings/audiopwmio/PWMAudioOut.c b/shared-bindings/audiopwmio/PWMAudioOut.c index 06571fae1e..fbe64fba78 100644 --- a/shared-bindings/audiopwmio/PWMAudioOut.c +++ b/shared-bindings/audiopwmio/PWMAudioOut.c @@ -275,5 +275,5 @@ const mp_obj_type_t audiopwmio_pwmaudioout_type = { { &mp_type_type }, .name = MP_QSTR_PWMAudioOut, .make_new = audiopwmio_pwmaudioout_make_new, - .locals_dict = (mp_obj_dict_t*)&audiopwmio_pwmaudioout_locals_dict, + .locals_dict = (mp_obj_dict_t *)&audiopwmio_pwmaudioout_locals_dict, }; diff --git a/shared-bindings/audiopwmio/PWMAudioOut.h b/shared-bindings/audiopwmio/PWMAudioOut.h index 22afc70d38..15d1fa940c 100644 --- a/shared-bindings/audiopwmio/PWMAudioOut.h +++ b/shared-bindings/audiopwmio/PWMAudioOut.h @@ -34,16 +34,16 @@ extern const mp_obj_type_t audiopwmio_pwmaudioout_type; // left_channel will always be non-NULL but right_channel may be for mono output. -void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t* self, - const mcu_pin_obj_t* left_channel, const mcu_pin_obj_t* right_channel, uint16_t default_value); +void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t *self, + const mcu_pin_obj_t *left_channel, const mcu_pin_obj_t *right_channel, uint16_t default_value); -void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t* self); -bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t* self); -void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t* self, mp_obj_t sample, bool loop); -void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t* self); -bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t* self); -void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t* self); -void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t* self); -bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t* self); +void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t *self); +bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t *self); +void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t *self); +bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t *self); +void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t *self); +void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t *self); +bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_AUDIOPWMIO_AUDIOOUT_H diff --git a/shared-bindings/audiopwmio/__init__.c b/shared-bindings/audiopwmio/__init__.c index 5caea14209..2bafb608a4 100644 --- a/shared-bindings/audiopwmio/__init__.c +++ b/shared-bindings/audiopwmio/__init__.c @@ -55,5 +55,5 @@ STATIC MP_DEFINE_CONST_DICT(audiopwmio_module_globals, audiopwmio_module_globals const mp_obj_module_t audiopwmio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&audiopwmio_module_globals, + .globals = (mp_obj_dict_t *)&audiopwmio_module_globals, }; diff --git a/shared-bindings/bitbangio/I2C.c b/shared-bindings/bitbangio/I2C.c index 17005f63a8..f6be845473 100644 --- a/shared-bindings/bitbangio/I2C.c +++ b/shared-bindings/bitbangio/I2C.c @@ -70,8 +70,8 @@ STATIC mp_obj_t bitbangio_i2c_make_new(const mp_obj_type_t *type, size_t n_args, mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* scl = validate_obj_is_free_pin(args[ARG_scl].u_obj); - const mcu_pin_obj_t* sda = validate_obj_is_free_pin(args[ARG_sda].u_obj); + const mcu_pin_obj_t *scl = validate_obj_is_free_pin(args[ARG_scl].u_obj); + const mcu_pin_obj_t *sda = validate_obj_is_free_pin(args[ARG_sda].u_obj); bitbangio_i2c_obj_t *self = m_new_obj(bitbangio_i2c_obj_t); self->base.type = &bitbangio_i2c_type; @@ -135,7 +135,7 @@ STATIC mp_obj_t bitbangio_i2c_scan(mp_obj_t self_in) { for (int addr = 0x08; addr < 0x78; ++addr) { bool success = shared_module_bitbangio_i2c_probe(self, addr); if (success) { - mp_obj_list_append(list, MP_OBJ_NEW_SMALL_INT(addr)); + mp_obj_list_append(list, MP_OBJ_NEW_SMALL_INT(addr)); } } return list; @@ -191,7 +191,7 @@ STATIC void readfrom(bitbangio_i2c_obj_t *self, mp_int_t address, mp_obj_t buffe mp_raise_ValueError(translate("Buffer must be at least length 1")); } - uint8_t status = shared_module_bitbangio_i2c_read(self, address, ((uint8_t*)bufinfo.buf) + start, length); + uint8_t status = shared_module_bitbangio_i2c_read(self, address, ((uint8_t *)bufinfo.buf) + start, length); if (status != 0) { mp_raise_OSError(status); } @@ -212,7 +212,7 @@ STATIC mp_obj_t bitbangio_i2c_readfrom_into(size_t n_args, const mp_obj_t *pos_a mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); readfrom(self, args[ARG_address].u_int, args[ARG_buffer].u_obj, args[ARG_start].u_int, - args[ARG_end].u_int); + args[ARG_end].u_int); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(bitbangio_i2c_readfrom_into_obj, 3, bitbangio_i2c_readfrom_into); @@ -246,8 +246,8 @@ STATIC void writeto(bitbangio_i2c_obj_t *self, mp_int_t address, mp_obj_t buffer // do the transfer uint8_t status = shared_module_bitbangio_i2c_write(self, address, - ((uint8_t*) bufinfo.buf) + start, length, - stop); + ((uint8_t *)bufinfo.buf) + start, length, + stop); if (status != 0) { mp_raise_OSError(status); } @@ -268,7 +268,7 @@ STATIC mp_obj_t bitbangio_i2c_writeto(size_t n_args, const mp_obj_t *pos_args, m mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); writeto(self, args[ARG_address].u_int, args[ARG_buffer].u_obj, args[ARG_start].u_int, - args[ARG_end].u_int, true); + args[ARG_end].u_int, true); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(bitbangio_i2c_writeto_obj, 1, bitbangio_i2c_writeto); @@ -309,9 +309,9 @@ STATIC mp_obj_t bitbangio_i2c_writeto_then_readfrom(size_t n_args, const mp_obj_ mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); writeto(self, args[ARG_address].u_int, args[ARG_out_buffer].u_obj, args[ARG_out_start].u_int, - args[ARG_out_end].u_int, false); + args[ARG_out_end].u_int, false); readfrom(self, args[ARG_address].u_int, args[ARG_in_buffer].u_obj, args[ARG_in_start].u_int, - args[ARG_in_end].u_int); + args[ARG_in_end].u_int); return mp_const_none; } @@ -337,5 +337,5 @@ const mp_obj_type_t bitbangio_i2c_type = { { &mp_type_type }, .name = MP_QSTR_I2C, .make_new = bitbangio_i2c_make_new, - .locals_dict = (mp_obj_dict_t*)&bitbangio_i2c_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bitbangio_i2c_locals_dict, }; diff --git a/shared-bindings/bitbangio/I2C.h b/shared-bindings/bitbangio/I2C.h index 97dd4580de..d950180a23 100644 --- a/shared-bindings/bitbangio/I2C.h +++ b/shared-bindings/bitbangio/I2C.h @@ -37,10 +37,10 @@ extern const mp_obj_type_t bitbangio_i2c_type; // Initializes the hardware peripheral. extern void shared_module_bitbangio_i2c_construct(bitbangio_i2c_obj_t *self, - const mcu_pin_obj_t * scl, - const mcu_pin_obj_t * sda, - uint32_t frequency, - uint32_t us_timeout); + const mcu_pin_obj_t *scl, + const mcu_pin_obj_t *sda, + uint32_t frequency, + uint32_t us_timeout); extern void shared_module_bitbangio_i2c_deinit(bitbangio_i2c_obj_t *self); extern bool shared_module_bitbangio_i2c_deinited(bitbangio_i2c_obj_t *self); @@ -53,13 +53,13 @@ extern void shared_module_bitbangio_i2c_unlock(bitbangio_i2c_obj_t *self); extern bool shared_module_bitbangio_i2c_probe(bitbangio_i2c_obj_t *self, uint8_t addr); extern uint8_t shared_module_bitbangio_i2c_write(bitbangio_i2c_obj_t *self, - uint16_t address, - const uint8_t * data, size_t len, - bool stop); + uint16_t address, + const uint8_t *data, size_t len, + bool stop); // Reads memory of the i2c device picking up where it left off. extern uint8_t shared_module_bitbangio_i2c_read(bitbangio_i2c_obj_t *self, - uint16_t address, - uint8_t * data, size_t len); + uint16_t address, + uint8_t *data, size_t len); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_BITBANGIO_I2C_H diff --git a/shared-bindings/bitbangio/OneWire.c b/shared-bindings/bitbangio/OneWire.c index da94a393e3..15cf833242 100644 --- a/shared-bindings/bitbangio/OneWire.c +++ b/shared-bindings/bitbangio/OneWire.c @@ -69,7 +69,7 @@ STATIC mp_obj_t bitbangio_onewire_make_new(const mp_obj_type_t *type, size_t n_a mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); + const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); bitbangio_onewire_obj_t *self = m_new_obj(bitbangio_onewire_obj_t); self->base.type = &bitbangio_onewire_type; @@ -168,5 +168,5 @@ const mp_obj_type_t bitbangio_onewire_type = { { &mp_type_type }, .name = MP_QSTR_OneWire, .make_new = bitbangio_onewire_make_new, - .locals_dict = (mp_obj_dict_t*)&bitbangio_onewire_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bitbangio_onewire_locals_dict, }; diff --git a/shared-bindings/bitbangio/OneWire.h b/shared-bindings/bitbangio/OneWire.h index da665b50d5..0dbc975122 100644 --- a/shared-bindings/bitbangio/OneWire.h +++ b/shared-bindings/bitbangio/OneWire.h @@ -32,12 +32,12 @@ extern const mp_obj_type_t bitbangio_onewire_type; -extern void shared_module_bitbangio_onewire_construct(bitbangio_onewire_obj_t* self, - const mcu_pin_obj_t* pin); -extern void shared_module_bitbangio_onewire_deinit(bitbangio_onewire_obj_t* self); -extern bool shared_module_bitbangio_onewire_deinited(bitbangio_onewire_obj_t* self); -extern bool shared_module_bitbangio_onewire_reset(bitbangio_onewire_obj_t* self); -extern bool shared_module_bitbangio_onewire_read_bit(bitbangio_onewire_obj_t* self); -extern void shared_module_bitbangio_onewire_write_bit(bitbangio_onewire_obj_t* self, bool bit); +extern void shared_module_bitbangio_onewire_construct(bitbangio_onewire_obj_t *self, + const mcu_pin_obj_t *pin); +extern void shared_module_bitbangio_onewire_deinit(bitbangio_onewire_obj_t *self); +extern bool shared_module_bitbangio_onewire_deinited(bitbangio_onewire_obj_t *self); +extern bool shared_module_bitbangio_onewire_reset(bitbangio_onewire_obj_t *self); +extern bool shared_module_bitbangio_onewire_read_bit(bitbangio_onewire_obj_t *self); +extern void shared_module_bitbangio_onewire_write_bit(bitbangio_onewire_obj_t *self, bool bit); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_BITBANGIO_ONEWIRE_H diff --git a/shared-bindings/bitbangio/SPI.c b/shared-bindings/bitbangio/SPI.c index fea88bbd40..e0fc6682e4 100644 --- a/shared-bindings/bitbangio/SPI.c +++ b/shared-bindings/bitbangio/SPI.c @@ -73,16 +73,16 @@ STATIC mp_obj_t bitbangio_spi_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_clock, ARG_MOSI, ARG_MISO, ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits, ARG_firstbit }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_clock, MP_ARG_REQUIRED | MP_ARG_OBJ }, - { MP_QSTR_MOSI, MP_ARG_OBJ, {.u_obj = mp_const_none} }, - { MP_QSTR_MISO, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_clock, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_MOSI, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_MISO, MP_ARG_OBJ, {.u_obj = mp_const_none} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* clock = validate_obj_is_free_pin(args[ARG_clock].u_obj); - const mcu_pin_obj_t* mosi = validate_obj_is_free_pin_or_none(args[ARG_MOSI].u_obj); - const mcu_pin_obj_t* miso = validate_obj_is_free_pin_or_none(args[ARG_MISO].u_obj); + const mcu_pin_obj_t *clock = validate_obj_is_free_pin(args[ARG_clock].u_obj); + const mcu_pin_obj_t *mosi = validate_obj_is_free_pin_or_none(args[ARG_MOSI].u_obj); + const mcu_pin_obj_t *miso = validate_obj_is_free_pin_or_none(args[ARG_MISO].u_obj); bitbangio_spi_obj_t *self = m_new_obj(bitbangio_spi_obj_t); self->base.type = &bitbangio_spi_type; @@ -299,9 +299,9 @@ STATIC mp_obj_t bitbangio_spi_write_readinto(size_t n_args, const mp_obj_t *pos_ } bool ok = shared_module_bitbangio_spi_transfer(self, - ((uint8_t*)buf_out_info.buf) + out_start, - ((uint8_t*)buf_in_info.buf) + in_start, - out_length); + ((uint8_t *)buf_out_info.buf) + out_start, + ((uint8_t *)buf_in_info.buf) + in_start, + out_length); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -328,5 +328,5 @@ const mp_obj_type_t bitbangio_spi_type = { { &mp_type_type }, .name = MP_QSTR_SPI, .make_new = bitbangio_spi_make_new, - .locals_dict = (mp_obj_dict_t*)&bitbangio_spi_locals_dict, + .locals_dict = (mp_obj_dict_t *)&bitbangio_spi_locals_dict, }; diff --git a/shared-bindings/bitbangio/SPI.h b/shared-bindings/bitbangio/SPI.h index 645f1a39c8..b2a6445754 100644 --- a/shared-bindings/bitbangio/SPI.h +++ b/shared-bindings/bitbangio/SPI.h @@ -37,8 +37,8 @@ extern const mp_obj_type_t bitbangio_spi_type; // Construct an underlying SPI object. extern void shared_module_bitbangio_spi_construct(bitbangio_spi_obj_t *self, - const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, - const mcu_pin_obj_t * miso); + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso); extern void shared_module_bitbangio_spi_deinit(bitbangio_spi_obj_t *self); extern bool shared_module_bitbangio_spi_deinited(bitbangio_spi_obj_t *self); diff --git a/shared-bindings/bitbangio/__init__.c b/shared-bindings/bitbangio/__init__.c index 3e4d2c08ef..81e9d91a37 100644 --- a/shared-bindings/bitbangio/__init__.c +++ b/shared-bindings/bitbangio/__init__.c @@ -80,5 +80,5 @@ STATIC MP_DEFINE_CONST_DICT(bitbangio_module_globals, bitbangio_module_globals_t const mp_obj_module_t bitbangio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&bitbangio_module_globals, + .globals = (mp_obj_dict_t *)&bitbangio_module_globals, }; diff --git a/shared-bindings/bitmaptools/__init__.c b/shared-bindings/bitmaptools/__init__.c index 118564ff85..cb30a46f80 100644 --- a/shared-bindings/bitmaptools/__init__.c +++ b/shared-bindings/bitmaptools/__init__.c @@ -37,7 +37,7 @@ STATIC int16_t validate_point(mp_obj_t point, int16_t default_value) { // Checks if point is None and returns default_value, otherwise decodes integer value - if ( point == mp_const_none ) { + if (point == mp_const_none) { return default_value; } return mp_obj_get_int(point); @@ -46,13 +46,13 @@ STATIC int16_t validate_point(mp_obj_t point, int16_t default_value) { STATIC void extract_tuple(mp_obj_t xy_tuple, int16_t *x, int16_t *y, int16_t x_default, int16_t y_default) { // Helper function for rotozoom // Extract x,y values from a tuple or default if None - if ( xy_tuple == mp_const_none ) { + if (xy_tuple == mp_const_none) { *x = x_default; *y = y_default; - } else if ( !MP_OBJ_IS_OBJ(xy_tuple) ) { + } else if (!MP_OBJ_IS_OBJ(xy_tuple)) { mp_raise_ValueError(translate("clip point must be (x,y) tuple")); } else { - mp_obj_t* items; + mp_obj_t *items; mp_obj_get_array_fixed_n(xy_tuple, 2, &items); *x = mp_obj_get_int(items[0]); *y = mp_obj_get_int(items[1]); @@ -60,7 +60,7 @@ STATIC void extract_tuple(mp_obj_t xy_tuple, int16_t *x, int16_t *y, int16_t x_d } STATIC void validate_clip_region(displayio_bitmap_t *bitmap, mp_obj_t clip0_tuple, int16_t *clip0_x, int16_t *clip0_y, - mp_obj_t clip1_tuple, int16_t *clip1_x, int16_t *clip1_y) { + mp_obj_t clip1_tuple, int16_t *clip1_x, int16_t *clip1_y) { // Helper function for rotozoom // 1. Extract the clip x,y points from the two clip tuples // 2. Rearrange values such that clip0_ < clip1_ @@ -70,12 +70,12 @@ STATIC void validate_clip_region(displayio_bitmap_t *bitmap, mp_obj_t clip0_tupl extract_tuple(clip1_tuple, clip1_x, clip1_y, bitmap->width, bitmap->height); // Ensure the value for clip0 is less than clip1 (for both x and y) - if ( *clip0_x > *clip1_x ) { + if (*clip0_x > *clip1_x) { int16_t temp_value = *clip0_x; // swap values *clip0_x = *clip1_x; *clip1_x = temp_value; } - if ( *clip0_y > *clip1_y ) { + if (*clip0_y > *clip1_y) { int16_t temp_value = *clip0_y; // swap values *clip0_y = *clip1_y; *clip1_y = temp_value; @@ -143,11 +143,11 @@ STATIC void validate_clip_region(displayio_bitmap_t *bitmap, mp_obj_t clip0_tupl //| set to None to copy all pixels""" //| ... //| -STATIC mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args){ +STATIC mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum {ARG_dest_bitmap, ARG_source_bitmap, - ARG_ox, ARG_oy, ARG_dest_clip0, ARG_dest_clip1, - ARG_px, ARG_py, ARG_source_clip0, ARG_source_clip1, - ARG_angle, ARG_scale, ARG_skip_index}; + ARG_ox, ARG_oy, ARG_dest_clip0, ARG_dest_clip1, + ARG_px, ARG_py, ARG_source_clip0, ARG_source_clip1, + ARG_angle, ARG_scale, ARG_skip_index}; static const mp_arg_t allowed_args[] = { {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, @@ -165,7 +165,7 @@ STATIC mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_args {MP_QSTR_angle, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to 0.0 {MP_QSTR_scale, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to 1.0 - {MP_QSTR_skip_index, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj=mp_const_none} }, + {MP_QSTR_skip_index, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -182,35 +182,35 @@ STATIC mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_args // Confirm the destination location target (ox,oy); if None, default to bitmap midpoint int16_t ox, oy; - ox = validate_point(args[ARG_ox].u_obj, destination->width / 2); + ox = validate_point(args[ARG_ox].u_obj, destination->width / 2); oy = validate_point(args[ARG_oy].u_obj, destination->height / 2); // Confirm the source location target (px,py); if None, default to bitmap midpoint int16_t px, py; - px = validate_point(args[ARG_px].u_obj, source->width / 2); + px = validate_point(args[ARG_px].u_obj, source->width / 2); py = validate_point(args[ARG_py].u_obj, source->height / 2); // Validate the clipping regions for the destination bitmap int16_t dest_clip0_x, dest_clip0_y, dest_clip1_x, dest_clip1_y; validate_clip_region(destination, args[ARG_dest_clip0].u_obj, &dest_clip0_x, &dest_clip0_y, - args[ARG_dest_clip1].u_obj, &dest_clip1_x, &dest_clip1_y); + args[ARG_dest_clip1].u_obj, &dest_clip1_x, &dest_clip1_y); // Validate the clipping regions for the source bitmap int16_t source_clip0_x, source_clip0_y, source_clip1_x, source_clip1_y; validate_clip_region(source, args[ARG_source_clip0].u_obj, &source_clip0_x, &source_clip0_y, - args[ARG_source_clip1].u_obj, &source_clip1_x, &source_clip1_y); + args[ARG_source_clip1].u_obj, &source_clip1_x, &source_clip1_y); // Confirm the angle value - float angle=0.0; - if ( args[ARG_angle].u_obj != mp_const_none ) { + float angle = 0.0; + if (args[ARG_angle].u_obj != mp_const_none) { angle = mp_obj_get_float(args[ARG_angle].u_obj); } // Confirm the scale value - float scale=1.0; - if ( args[ARG_scale].u_obj != mp_const_none ) { + float scale = 1.0; + if (args[ARG_scale].u_obj != mp_const_none) { scale = mp_obj_get_float(args[ARG_scale].u_obj); } if (scale < 0) { // ensure scale >= 0 @@ -219,7 +219,7 @@ STATIC mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_args uint32_t skip_index; bool skip_index_none; // Flag whether input skip_value was None - if (args[ARG_skip_index].u_obj == mp_const_none ) { + if (args[ARG_skip_index].u_obj == mp_const_none) { skip_index = 0; skip_index_none = true; } else { @@ -228,14 +228,14 @@ STATIC mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_args } common_hal_bitmaptools_rotozoom(destination, ox, oy, - dest_clip0_x, dest_clip0_y, - dest_clip1_x, dest_clip1_y, - source, px, py, - source_clip0_x, source_clip0_y, - source_clip1_x, source_clip1_y, - angle, - scale, - skip_index, skip_index_none); + dest_clip0_x, dest_clip0_y, + dest_clip1_x, dest_clip1_y, + source, px, py, + source_clip0_x, source_clip0_y, + source_clip1_x, source_clip1_y, + angle, + scale, + skip_index, skip_index_none); return mp_const_none; } @@ -261,7 +261,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_rotozoom_obj, 0, bitmaptools_obj_rotozoom //| fill region in the destination bitmap""" //| ... //| -STATIC mp_obj_t bitmaptools_obj_fill_region(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args){ +STATIC mp_obj_t bitmaptools_obj_fill_region(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum {ARG_dest_bitmap, ARG_x1, ARG_y1, ARG_x2, ARG_y2, ARG_value}; static const mp_arg_t allowed_args[] = { @@ -281,8 +281,8 @@ STATIC mp_obj_t bitmaptools_obj_fill_region(size_t n_args, const mp_obj_t *pos_a value = args[ARG_value].u_int; color_depth = (1 << destination->bits_per_value); if (color_depth <= value) { - mp_raise_ValueError(translate("out of range of target")); - } + mp_raise_ValueError(translate("out of range of target")); + } int16_t x1 = args[ARG_x1].u_int; int16_t y1 = args[ARG_y1].u_int; @@ -314,7 +314,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_fill_region_obj, 0, bitmaptools_obj_fill_ //| line in the destination bitmap""" //| ... //| -STATIC mp_obj_t bitmaptools_obj_draw_line(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args){ +STATIC mp_obj_t bitmaptools_obj_draw_line(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum {ARG_dest_bitmap, ARG_x1, ARG_y1, ARG_x2, ARG_y2, ARG_value}; static const mp_arg_t allowed_args[] = { @@ -334,8 +334,8 @@ STATIC mp_obj_t bitmaptools_obj_draw_line(size_t n_args, const mp_obj_t *pos_arg value = args[ARG_value].u_int; color_depth = (1 << destination->bits_per_value); if (color_depth <= value) { - mp_raise_ValueError(translate("out of range of target")); - } + mp_raise_ValueError(translate("out of range of target")); + } int16_t x1 = args[ARG_x1].u_int; int16_t y1 = args[ARG_y1].u_int; @@ -343,9 +343,9 @@ STATIC mp_obj_t bitmaptools_obj_draw_line(size_t n_args, const mp_obj_t *pos_arg int16_t y2 = args[ARG_y2].u_int; // verify points are within the bitmap boundary (inclusive) - if ( (x1 < 0) || (x2 < 0) || (y1 < 0) || (y2 < 0) || - (x1 >= destination->width) || (x2 >= destination->width) || - (y1 >= destination->height) || (y2 >= destination->height) ) { + if ((x1 < 0) || (x2 < 0) || (y1 < 0) || (y2 < 0) || + (x1 >= destination->width) || (x2 >= destination->width) || + (y1 >= destination->height) || (y2 >= destination->height)) { mp_raise_ValueError(translate("out of range of target")); } @@ -366,5 +366,5 @@ STATIC MP_DEFINE_CONST_DICT(bitmaptools_module_globals, bitmaptools_module_globa const mp_obj_module_t bitmaptools_module = { .base = {&mp_type_module }, - .globals = (mp_obj_dict_t*)&bitmaptools_module_globals, + .globals = (mp_obj_dict_t *)&bitmaptools_module_globals, }; diff --git a/shared-bindings/bitmaptools/__init__.h b/shared-bindings/bitmaptools/__init__.h index 1ab6e41293..42f111b020 100644 --- a/shared-bindings/bitmaptools/__init__.h +++ b/shared-bindings/bitmaptools/__init__.h @@ -30,23 +30,23 @@ #include "py/obj.h" void common_hal_bitmaptools_rotozoom(displayio_bitmap_t *self, int16_t ox, int16_t oy, - int16_t dest_clip0_x, int16_t dest_clip0_y, - int16_t dest_clip1_x, int16_t dest_clip1_y, - displayio_bitmap_t *source, int16_t px, int16_t py, - int16_t source_clip0_x, int16_t source_clip0_y, - int16_t source_clip1_x, int16_t source_clip1_y, - float angle, - float scale, - uint32_t skip_index, bool skip_index_none); + int16_t dest_clip0_x, int16_t dest_clip0_y, + int16_t dest_clip1_x, int16_t dest_clip1_y, + displayio_bitmap_t *source, int16_t px, int16_t py, + int16_t source_clip0_x, int16_t source_clip0_y, + int16_t source_clip1_x, int16_t source_clip1_y, + float angle, + float scale, + uint32_t skip_index, bool skip_index_none); void common_hal_bitmaptools_fill_region(displayio_bitmap_t *destination, - int16_t x1, int16_t y1, - int16_t x2, int16_t y2, - uint32_t value); + int16_t x1, int16_t y1, + int16_t x2, int16_t y2, + uint32_t value); void common_hal_bitmaptools_draw_line(displayio_bitmap_t *destination, - int16_t x0, int16_t y0, - int16_t x1, int16_t y1, - uint32_t value); + int16_t x0, int16_t y0, + int16_t x1, int16_t y1, + uint32_t value); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_BITMAPTOOLS__INIT__H diff --git a/shared-bindings/bitops/__init__.c b/shared-bindings/bitops/__init__.c index 3c567b8ed9..913c8bc836 100644 --- a/shared-bindings/bitops/__init__.c +++ b/shared-bindings/bitops/__init__.c @@ -97,5 +97,5 @@ STATIC MP_DEFINE_CONST_DICT(bitops_module_globals, bitops_module_globals_table); const mp_obj_module_t bitops_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&bitops_module_globals, + .globals = (mp_obj_dict_t *)&bitops_module_globals, }; diff --git a/shared-bindings/board/__init__.c b/shared-bindings/board/__init__.c index 717698408a..06b3a899d8 100644 --- a/shared-bindings/board/__init__.c +++ b/shared-bindings/board/__init__.c @@ -122,5 +122,5 @@ MP_DEFINE_CONST_FUN_OBJ_0(board_uart_obj, board_uart); const mp_obj_module_t board_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&board_module_globals, + .globals = (mp_obj_dict_t *)&board_module_globals, }; diff --git a/shared-bindings/busio/I2C.c b/shared-bindings/busio/I2C.c index 8b456dbd35..56a6e1b8ae 100644 --- a/shared-bindings/busio/I2C.c +++ b/shared-bindings/busio/I2C.c @@ -76,8 +76,8 @@ STATIC mp_obj_t busio_i2c_make_new(const mp_obj_type_t *type, size_t n_args, con mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* scl = validate_obj_is_free_pin(args[ARG_scl].u_obj); - const mcu_pin_obj_t* sda = validate_obj_is_free_pin(args[ARG_sda].u_obj); + const mcu_pin_obj_t *scl = validate_obj_is_free_pin(args[ARG_scl].u_obj); + const mcu_pin_obj_t *sda = validate_obj_is_free_pin(args[ARG_sda].u_obj); common_hal_busio_i2c_construct(self, scl, sda, args[ARG_frequency].u_int, args[ARG_timeout].u_int); return (mp_obj_t)self; @@ -119,7 +119,7 @@ STATIC mp_obj_t busio_i2c_obj___exit__(size_t n_args, const mp_obj_t *args) { STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(busio_i2c___exit___obj, 4, 4, busio_i2c_obj___exit__); static void check_lock(busio_i2c_obj_t *self) { - asm(""); + asm (""); if (!common_hal_busio_i2c_has_lock(self)) { mp_raise_RuntimeError(translate("Function requires lock")); } @@ -201,7 +201,7 @@ STATIC void readfrom(busio_i2c_obj_t *self, mp_int_t address, mp_obj_t buffer, i mp_raise_ValueError(translate("Buffer must be at least length 1")); } - uint8_t status = common_hal_busio_i2c_read(self, address, ((uint8_t*)bufinfo.buf) + start, length); + uint8_t status = common_hal_busio_i2c_read(self, address, ((uint8_t *)bufinfo.buf) + start, length); if (status != 0) { mp_raise_OSError(status); } @@ -222,7 +222,7 @@ STATIC mp_obj_t busio_i2c_readfrom_into(size_t n_args, const mp_obj_t *pos_args, mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); readfrom(self, args[ARG_address].u_int, args[ARG_buffer].u_obj, args[ARG_start].u_int, - args[ARG_end].u_int); + args[ARG_end].u_int); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(busio_i2c_readfrom_into_obj, 3, busio_i2c_readfrom_into); @@ -254,8 +254,8 @@ STATIC void writeto(busio_i2c_obj_t *self, mp_int_t address, mp_obj_t buffer, in normalize_buffer_bounds(&start, end, &length); // do the transfer - uint8_t status = common_hal_busio_i2c_write(self, address, ((uint8_t*) bufinfo.buf) + start, - length, stop); + uint8_t status = common_hal_busio_i2c_write(self, address, ((uint8_t *)bufinfo.buf) + start, + length, stop); if (status != 0) { mp_raise_OSError(status); } @@ -276,7 +276,7 @@ STATIC mp_obj_t busio_i2c_writeto(size_t n_args, const mp_obj_t *pos_args, mp_ma mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); writeto(self, args[ARG_address].u_int, args[ARG_buffer].u_obj, args[ARG_start].u_int, - args[ARG_end].u_int, true); + args[ARG_end].u_int, true); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(busio_i2c_writeto_obj, 1, busio_i2c_writeto); @@ -317,9 +317,9 @@ STATIC mp_obj_t busio_i2c_writeto_then_readfrom(size_t n_args, const mp_obj_t *p mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); writeto(self, args[ARG_address].u_int, args[ARG_out_buffer].u_obj, args[ARG_out_start].u_int, - args[ARG_out_end].u_int, false); + args[ARG_out_end].u_int, false); readfrom(self, args[ARG_address].u_int, args[ARG_in_buffer].u_obj, args[ARG_in_start].u_int, - args[ARG_in_end].u_int); + args[ARG_in_end].u_int); return mp_const_none; } @@ -342,8 +342,8 @@ STATIC const mp_rom_map_elem_t busio_i2c_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(busio_i2c_locals_dict, busio_i2c_locals_dict_table); const mp_obj_type_t busio_i2c_type = { - { &mp_type_type }, - .name = MP_QSTR_I2C, - .make_new = busio_i2c_make_new, - .locals_dict = (mp_obj_dict_t*)&busio_i2c_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_I2C, + .make_new = busio_i2c_make_new, + .locals_dict = (mp_obj_dict_t *)&busio_i2c_locals_dict, }; diff --git a/shared-bindings/busio/I2C.h b/shared-bindings/busio/I2C.h index a2d5dbf507..08701938c9 100644 --- a/shared-bindings/busio/I2C.h +++ b/shared-bindings/busio/I2C.h @@ -44,10 +44,10 @@ extern const mp_obj_type_t busio_i2c_type; // Initializes the hardware peripheral. extern void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, - const mcu_pin_obj_t * scl, - const mcu_pin_obj_t * sda, - uint32_t frequency, - uint32_t timeout); + const mcu_pin_obj_t *scl, + const mcu_pin_obj_t *sda, + uint32_t frequency, + uint32_t timeout); extern void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self); extern bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self); @@ -61,13 +61,13 @@ extern bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr); // Write to the device and return 0 on success or an appropriate error code from mperrno.h extern uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t address, - const uint8_t * data, size_t len, - bool stop); + const uint8_t *data, size_t len, + bool stop); // Reads memory of the i2c device picking up where it left off and return 0 on // success or an appropriate error code from mperrno.h extern uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t address, - uint8_t * data, size_t len); + uint8_t *data, size_t len); // This is used by the supervisor to claim I2C devices indefinitely. extern void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self); diff --git a/shared-bindings/busio/OneWire.c b/shared-bindings/busio/OneWire.c index 1fae391819..026e1ee968 100644 --- a/shared-bindings/busio/OneWire.c +++ b/shared-bindings/busio/OneWire.c @@ -68,7 +68,7 @@ STATIC mp_obj_t busio_onewire_make_new(const mp_obj_type_t *type, size_t n_args, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); + const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); busio_onewire_obj_t *self = m_new_obj(busio_onewire_obj_t); self->base.type = &busio_onewire_type; @@ -170,5 +170,5 @@ const mp_obj_type_t busio_onewire_type = { { &mp_type_type }, .name = MP_QSTR_OneWire, .make_new = busio_onewire_make_new, - .locals_dict = (mp_obj_dict_t*)&busio_onewire_locals_dict, + .locals_dict = (mp_obj_dict_t *)&busio_onewire_locals_dict, }; diff --git a/shared-bindings/busio/OneWire.h b/shared-bindings/busio/OneWire.h index 9ee5f639b1..a270bab5c9 100644 --- a/shared-bindings/busio/OneWire.h +++ b/shared-bindings/busio/OneWire.h @@ -32,12 +32,12 @@ extern const mp_obj_type_t busio_onewire_type; -extern void common_hal_busio_onewire_construct(busio_onewire_obj_t* self, - const mcu_pin_obj_t* pin); -extern void common_hal_busio_onewire_deinit(busio_onewire_obj_t* self); -extern bool common_hal_busio_onewire_deinited(busio_onewire_obj_t* self); -extern bool common_hal_busio_onewire_reset(busio_onewire_obj_t* self); -extern bool common_hal_busio_onewire_read_bit(busio_onewire_obj_t* self); -extern void common_hal_busio_onewire_write_bit(busio_onewire_obj_t* self, bool bit); +extern void common_hal_busio_onewire_construct(busio_onewire_obj_t *self, + const mcu_pin_obj_t *pin); +extern void common_hal_busio_onewire_deinit(busio_onewire_obj_t *self); +extern bool common_hal_busio_onewire_deinited(busio_onewire_obj_t *self); +extern bool common_hal_busio_onewire_reset(busio_onewire_obj_t *self); +extern bool common_hal_busio_onewire_read_bit(busio_onewire_obj_t *self); +extern void common_hal_busio_onewire_write_bit(busio_onewire_obj_t *self, bool bit); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_BUSIO_ONEWIRE_H diff --git a/shared-bindings/busio/SPI.c b/shared-bindings/busio/SPI.c index cbc6b5c088..e64f17b145 100644 --- a/shared-bindings/busio/SPI.c +++ b/shared-bindings/busio/SPI.c @@ -92,9 +92,9 @@ STATIC mp_obj_t busio_spi_make_new(const mp_obj_type_t *type, size_t n_args, con mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* clock = validate_obj_is_free_pin(args[ARG_clock].u_obj); - const mcu_pin_obj_t* mosi = validate_obj_is_free_pin_or_none(args[ARG_MOSI].u_obj); - const mcu_pin_obj_t* miso = validate_obj_is_free_pin_or_none(args[ARG_MISO].u_obj); + const mcu_pin_obj_t *clock = validate_obj_is_free_pin(args[ARG_clock].u_obj); + const mcu_pin_obj_t *mosi = validate_obj_is_free_pin_or_none(args[ARG_MOSI].u_obj); + const mcu_pin_obj_t *miso = validate_obj_is_free_pin_or_none(args[ARG_MISO].u_obj); if (!miso && !mosi) { mp_raise_ValueError(translate("Must provide MISO or MOSI pin")); @@ -134,7 +134,7 @@ STATIC mp_obj_t busio_spi_obj___exit__(size_t n_args, const mp_obj_t *args) { STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(busio_spi_obj___exit___obj, 4, 4, busio_spi_obj___exit__); STATIC void check_lock(busio_spi_obj_t *self) { - asm(""); + asm (""); if (!common_hal_busio_spi_has_lock(self)) { mp_raise_RuntimeError(translate("Function requires lock")); } @@ -198,7 +198,7 @@ STATIC mp_obj_t busio_spi_configure(size_t n_args, const mp_obj_t *pos_args, mp_ } if (!common_hal_busio_spi_configure(self, args[ARG_baudrate].u_int, - polarity, phase, bits)) { + polarity, phase, bits)) { mp_raise_OSError(MP_EIO); } return mp_const_none; @@ -265,7 +265,7 @@ STATIC mp_obj_t busio_spi_write(size_t n_args, const mp_obj_t *pos_args, mp_map_ return mp_const_none; } - bool ok = common_hal_busio_spi_write(self, ((uint8_t*)bufinfo.buf) + start, length); + bool ok = common_hal_busio_spi_write(self, ((uint8_t *)bufinfo.buf) + start, length); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -310,7 +310,7 @@ STATIC mp_obj_t busio_spi_readinto(size_t n_args, const mp_obj_t *pos_args, mp_m return mp_const_none; } - bool ok = common_hal_busio_spi_read(self, ((uint8_t*)bufinfo.buf) + start, length, args[ARG_write_value].u_int); + bool ok = common_hal_busio_spi_read(self, ((uint8_t *)bufinfo.buf) + start, length, args[ARG_write_value].u_int); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -371,9 +371,9 @@ STATIC mp_obj_t busio_spi_write_readinto(size_t n_args, const mp_obj_t *pos_args } bool ok = common_hal_busio_spi_transfer(self, - ((uint8_t*)buf_out_info.buf) + out_start, - ((uint8_t*)buf_in_info.buf) + in_start, - out_length); + ((uint8_t *)buf_out_info.buf) + out_start, + ((uint8_t *)buf_in_info.buf) + in_start, + out_length); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -417,10 +417,10 @@ STATIC const mp_rom_map_elem_t busio_spi_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(busio_spi_locals_dict, busio_spi_locals_dict_table); const mp_obj_type_t busio_spi_type = { - { &mp_type_type }, - .name = MP_QSTR_SPI, - .make_new = busio_spi_make_new, - .locals_dict = (mp_obj_dict_t*)&busio_spi_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_SPI, + .make_new = busio_spi_make_new, + .locals_dict = (mp_obj_dict_t *)&busio_spi_locals_dict, }; busio_spi_obj_t *validate_obj_is_spi_bus(mp_obj_t obj) { diff --git a/shared-bindings/busio/SPI.h b/shared-bindings/busio/SPI.h index 3a8b6dbc1d..67ca752bab 100644 --- a/shared-bindings/busio/SPI.h +++ b/shared-bindings/busio/SPI.h @@ -37,8 +37,8 @@ extern const mp_obj_type_t busio_spi_type; // Construct an underlying SPI object. extern void common_hal_busio_spi_construct(busio_spi_obj_t *self, - const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, - const mcu_pin_obj_t * miso); + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso); extern void common_hal_busio_spi_deinit(busio_spi_obj_t *self); extern bool common_hal_busio_spi_deinited(busio_spi_obj_t *self); @@ -59,13 +59,13 @@ extern bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size extern bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len); // Return actual SPI bus frequency. -uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t* self); +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self); // Return SPI bus phase. -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t* self); +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self); // Return SPI bus polarity. -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t* self); +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self); // This is used by the supervisor to claim SPI devices indefinitely. extern void common_hal_busio_spi_never_reset(busio_spi_obj_t *self); diff --git a/shared-bindings/busio/UART.c b/shared-bindings/busio/UART.c index 06647e779e..05c3addd3e 100644 --- a/shared-bindings/busio/UART.c +++ b/shared-bindings/busio/UART.c @@ -72,7 +72,7 @@ extern const busio_uart_parity_obj_t busio_uart_parity_even_obj; extern const busio_uart_parity_obj_t busio_uart_parity_odd_obj; STATIC void validate_timeout(mp_float_t timeout) { - if (timeout < (mp_float_t) 0.0f || timeout > (mp_float_t) 100.0f) { + if (timeout < (mp_float_t)0.0f || timeout > (mp_float_t)100.0f) { mp_raise_ValueError(translate("timeout must be 0.0-100.0 seconds")); } } @@ -103,10 +103,10 @@ STATIC mp_obj_t busio_uart_make_new(const mp_obj_type_t *type, size_t n_args, co mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* rx = validate_obj_is_free_pin_or_none(args[ARG_rx].u_obj); - const mcu_pin_obj_t* tx = validate_obj_is_free_pin_or_none(args[ARG_tx].u_obj); + const mcu_pin_obj_t *rx = validate_obj_is_free_pin_or_none(args[ARG_rx].u_obj); + const mcu_pin_obj_t *tx = validate_obj_is_free_pin_or_none(args[ARG_tx].u_obj); - if ( (tx == NULL) && (rx == NULL) ) { + if ((tx == NULL) && (rx == NULL)) { mp_raise_ValueError(translate("tx and rx cannot both be None")); } @@ -130,15 +130,15 @@ STATIC mp_obj_t busio_uart_make_new(const mp_obj_type_t *type, size_t n_args, co mp_float_t timeout = mp_obj_get_float(args[ARG_timeout].u_obj); validate_timeout(timeout); - const mcu_pin_obj_t* rts = validate_obj_is_free_pin_or_none(args[ARG_rts].u_obj); - const mcu_pin_obj_t* cts = validate_obj_is_free_pin_or_none(args[ARG_cts].u_obj); - const mcu_pin_obj_t* rs485_dir = validate_obj_is_free_pin_or_none(args[ARG_rs485_dir].u_obj); + const mcu_pin_obj_t *rts = validate_obj_is_free_pin_or_none(args[ARG_rts].u_obj); + const mcu_pin_obj_t *cts = validate_obj_is_free_pin_or_none(args[ARG_cts].u_obj); + const mcu_pin_obj_t *rs485_dir = validate_obj_is_free_pin_or_none(args[ARG_rs485_dir].u_obj); const bool rs485_invert = args[ARG_rs485_invert].u_bool; common_hal_busio_uart_construct(self, tx, rx, rts, cts, rs485_dir, rs485_invert, - args[ARG_baudrate].u_int, bits, parity, stop, timeout, - args[ARG_receiver_buffer_size].u_int, NULL, false); + args[ARG_baudrate].u_int, bits, parity, stop, timeout, + args[ARG_receiver_buffer_size].u_int, NULL, false); return (mp_obj_t)self; } @@ -427,5 +427,5 @@ const mp_obj_type_t busio_uart_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &uart_stream_p, - .locals_dict = (mp_obj_dict_t*)&busio_uart_locals_dict, + .locals_dict = (mp_obj_dict_t *)&busio_uart_locals_dict, }; diff --git a/shared-bindings/busio/UART.h b/shared-bindings/busio/UART.h index ce8da1445c..31b062aee5 100644 --- a/shared-bindings/busio/UART.h +++ b/shared-bindings/busio/UART.h @@ -41,11 +41,11 @@ typedef enum { // Construct an underlying UART object. extern void common_hal_busio_uart_construct(busio_uart_obj_t *self, - const mcu_pin_obj_t * tx, const mcu_pin_obj_t * rx, - const mcu_pin_obj_t * rts, const mcu_pin_obj_t * cts, - const mcu_pin_obj_t * rs485_dir, bool rs485_invert, + const mcu_pin_obj_t *tx, const mcu_pin_obj_t *rx, + const mcu_pin_obj_t *rts, const mcu_pin_obj_t *cts, + const mcu_pin_obj_t *rs485_dir, bool rs485_invert, uint32_t baudrate, uint8_t bits, busio_uart_parity_t parity, uint8_t stop, - mp_float_t timeout, uint16_t receiver_buffer_size, byte* receiver_buffer, + mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled); extern void common_hal_busio_uart_deinit(busio_uart_obj_t *self); @@ -57,7 +57,7 @@ extern size_t common_hal_busio_uart_read(busio_uart_obj_t *self, // Write characters. len is in characters NOT bytes! extern size_t common_hal_busio_uart_write(busio_uart_obj_t *self, - const uint8_t *data, size_t len, int *errcode); + const uint8_t *data, size_t len, int *errcode); extern uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self); extern void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrate); diff --git a/shared-bindings/busio/__init__.c b/shared-bindings/busio/__init__.c index 04632c2f4a..e7df331c12 100644 --- a/shared-bindings/busio/__init__.c +++ b/shared-bindings/busio/__init__.c @@ -81,5 +81,5 @@ STATIC MP_DEFINE_CONST_DICT(busio_module_globals, busio_module_globals_table); const mp_obj_module_t busio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&busio_module_globals, + .globals = (mp_obj_dict_t *)&busio_module_globals, }; diff --git a/shared-bindings/camera/Camera.c b/shared-bindings/camera/Camera.c index fd88ccab00..a588965005 100644 --- a/shared-bindings/camera/Camera.c +++ b/shared-bindings/camera/Camera.c @@ -125,8 +125,8 @@ STATIC const mp_rom_map_elem_t camera_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(camera_locals_dict, camera_locals_dict_table); const mp_obj_type_t camera_type = { - { &mp_type_type }, - .name = MP_QSTR_Camera, - .make_new = camera_make_new, - .locals_dict = (mp_obj_dict_t*)&camera_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_Camera, + .make_new = camera_make_new, + .locals_dict = (mp_obj_dict_t *)&camera_locals_dict, }; diff --git a/shared-bindings/camera/__init__.c b/shared-bindings/camera/__init__.c index 080516d51c..dfe1093a40 100644 --- a/shared-bindings/camera/__init__.c +++ b/shared-bindings/camera/__init__.c @@ -46,5 +46,5 @@ STATIC MP_DEFINE_CONST_DICT(camera_module_globals, camera_module_globals_table); const mp_obj_module_t camera_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&camera_module_globals, + .globals = (mp_obj_dict_t *)&camera_module_globals, }; diff --git a/shared-bindings/canio/CAN.c b/shared-bindings/canio/CAN.c index 13066764e3..e2d21c1df7 100644 --- a/shared-bindings/canio/CAN.c +++ b/shared-bindings/canio/CAN.c @@ -74,7 +74,7 @@ STATIC mp_obj_t canio_can_make_new(const mp_obj_type_t *type, size_t n_args, con { MP_QSTR_auto_restart, MP_ARG_BOOL, {.u_bool = false} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -244,7 +244,7 @@ STATIC mp_obj_t canio_can_listen(size_t n_args, const mp_obj_t *pos_args, mp_map { MP_QSTR_timeout, MP_ARG_OBJ, {.u_obj = 0} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -256,7 +256,7 @@ STATIC mp_obj_t canio_can_listen(size_t n_args, const mp_obj_t *pos_args, mp_map } canio_match_obj_t *matches[nmatch]; - for (size_t i=0; iname); diff --git a/shared-bindings/canio/Listener.c b/shared-bindings/canio/Listener.c index 8a39f0f2ae..370c61ad80 100644 --- a/shared-bindings/canio/Listener.c +++ b/shared-bindings/canio/Listener.c @@ -174,5 +174,5 @@ const mp_obj_type_t canio_listener_type = { .name = MP_QSTR_Listener, .getiter = mp_identity_getiter, .iternext = canio_iternext, - .locals_dict = (mp_obj_dict_t*)&canio_listener_locals_dict, + .locals_dict = (mp_obj_dict_t *)&canio_listener_locals_dict, }; diff --git a/shared-bindings/canio/Match.c b/shared-bindings/canio/Match.c index 6039631fad..cddb85c26a 100644 --- a/shared-bindings/canio/Match.c +++ b/shared-bindings/canio/Match.c @@ -50,7 +50,7 @@ STATIC mp_obj_t canio_match_make_new(const mp_obj_type_t *type, size_t n_args, c { MP_QSTR_extended, MP_ARG_BOOL, {.u_bool = false} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -135,5 +135,5 @@ const mp_obj_type_t canio_match_type = { { &mp_type_type }, .name = MP_QSTR_Match, .make_new = canio_match_make_new, - .locals_dict = (mp_obj_dict_t*)&canio_match_locals_dict, + .locals_dict = (mp_obj_dict_t *)&canio_match_locals_dict, }; diff --git a/shared-bindings/canio/Message.c b/shared-bindings/canio/Message.c index 04fa8fc6c2..7b85f17220 100644 --- a/shared-bindings/canio/Message.c +++ b/shared-bindings/canio/Message.c @@ -50,7 +50,7 @@ STATIC mp_obj_t canio_message_make_new(const mp_obj_type_t *type, size_t n_args, { MP_QSTR_extended, MP_ARG_BOOL, {.u_bool = false} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -95,7 +95,7 @@ STATIC const mp_obj_property_t canio_message_id_obj = { //| STATIC mp_obj_t canio_message_data_get(const mp_obj_t self_in) { canio_message_obj_t *self = self_in; - return mp_obj_new_bytes((const byte*)common_hal_canio_message_get_data(self), common_hal_canio_message_get_length(self)); + return mp_obj_new_bytes((const byte *)common_hal_canio_message_get_data(self), common_hal_canio_message_get_length(self)); } MP_DEFINE_CONST_FUN_OBJ_1(canio_message_data_get_obj, canio_message_data_get); diff --git a/shared-bindings/canio/RemoteTransmissionRequest.c b/shared-bindings/canio/RemoteTransmissionRequest.c index fcd2590340..7f8a8fb96d 100644 --- a/shared-bindings/canio/RemoteTransmissionRequest.c +++ b/shared-bindings/canio/RemoteTransmissionRequest.c @@ -50,7 +50,7 @@ STATIC mp_obj_t canio_remote_transmission_request_make_new(const mp_obj_type_t * { MP_QSTR_extended, MP_ARG_BOOL, {.u_bool = false} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); diff --git a/shared-bindings/canio/__init__.c b/shared-bindings/canio/__init__.c index f29d3ab8ac..d9863e8a21 100644 --- a/shared-bindings/canio/__init__.c +++ b/shared-bindings/canio/__init__.c @@ -121,5 +121,5 @@ STATIC MP_DEFINE_CONST_DICT(canio_module_globals, canio_module_globals_table); const mp_obj_module_t canio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&canio_module_globals, + .globals = (mp_obj_dict_t *)&canio_module_globals, }; diff --git a/shared-bindings/countio/Counter.c b/shared-bindings/countio/Counter.c index 820db5ea94..e03665d636 100644 --- a/shared-bindings/countio/Counter.c +++ b/shared-bindings/countio/Counter.c @@ -41,7 +41,7 @@ STATIC mp_obj_t countio_counter_make_new(const mp_obj_type_t *type, size_t n_arg mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* pin_a = validate_obj_is_free_pin(args[ARG_pin_a].u_obj); + const mcu_pin_obj_t *pin_a = validate_obj_is_free_pin(args[ARG_pin_a].u_obj); countio_counter_obj_t *self = m_new_obj(countio_counter_obj_t); @@ -115,12 +115,12 @@ const mp_obj_property_t countio_counter_count_obj = { //| def reset(self) -> None: //| """Resets the count back to 0.""" //| -STATIC mp_obj_t countio_counter_reset(mp_obj_t self_in){ - countio_counter_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self); - //set the position to zero for reset - common_hal_countio_counter_reset(self); - return mp_const_none; +STATIC mp_obj_t countio_counter_reset(mp_obj_t self_in) { + countio_counter_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + // set the position to zero for reset + common_hal_countio_counter_reset(self); + return mp_const_none; } @@ -140,5 +140,5 @@ const mp_obj_type_t countio_counter_type = { { &mp_type_type }, .name = MP_QSTR_Counter, .make_new = countio_counter_make_new, - .locals_dict = (mp_obj_dict_t*)&countio_counter_locals_dict, + .locals_dict = (mp_obj_dict_t *)&countio_counter_locals_dict, }; diff --git a/shared-bindings/countio/Counter.h b/shared-bindings/countio/Counter.h index 15adbbe2ac..a9eced41a3 100644 --- a/shared-bindings/countio/Counter.h +++ b/shared-bindings/countio/Counter.h @@ -6,13 +6,13 @@ extern const mp_obj_type_t countio_counter_type; -extern void common_hal_countio_counter_construct(countio_counter_obj_t* self, - const mcu_pin_obj_t* pin_a); -extern void common_hal_countio_counter_deinit(countio_counter_obj_t* self); -extern bool common_hal_countio_counter_deinited(countio_counter_obj_t* self); -extern mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t* self); -extern void common_hal_countio_counter_set_count(countio_counter_obj_t* self, +extern void common_hal_countio_counter_construct(countio_counter_obj_t *self, + const mcu_pin_obj_t *pin_a); +extern void common_hal_countio_counter_deinit(countio_counter_obj_t *self); +extern bool common_hal_countio_counter_deinited(countio_counter_obj_t *self); +extern mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t *self); +extern void common_hal_countio_counter_set_count(countio_counter_obj_t *self, mp_int_t new_count); -extern void common_hal_countio_counter_reset(countio_counter_obj_t* self); +extern void common_hal_countio_counter_reset(countio_counter_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_COUNTIO_COUNTER_H diff --git a/shared-bindings/countio/__init__.c b/shared-bindings/countio/__init__.c index 7046a5e721..f6c0a4221c 100644 --- a/shared-bindings/countio/__init__.c +++ b/shared-bindings/countio/__init__.c @@ -32,5 +32,5 @@ STATIC MP_DEFINE_CONST_DICT(countio_module_globals, countio_module_globals_table const mp_obj_module_t countio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&countio_module_globals, + .globals = (mp_obj_dict_t *)&countio_module_globals, }; diff --git a/shared-bindings/digitalio/DigitalInOut.c b/shared-bindings/digitalio/DigitalInOut.c index 351e122e0a..0874bed550 100644 --- a/shared-bindings/digitalio/DigitalInOut.c +++ b/shared-bindings/digitalio/DigitalInOut.c @@ -59,7 +59,7 @@ //| ... //| STATIC mp_obj_t digitalio_digitalinout_make_new(const mp_obj_type_t *type, - mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { + mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { mp_arg_check_num(n_args, kw_args, 1, 1, false); digitalio_digitalinout_obj_t *self = m_new_obj(digitalio_digitalinout_obj_t); @@ -170,7 +170,7 @@ STATIC mp_obj_t digitalio_digitalinout_switch_to_input(size_t n_args, const mp_o digitalio_pull_t pull = PULL_NONE; if (args[ARG_pull].u_rom_obj == &digitalio_pull_up_obj) { pull = PULL_UP; - }else if (args[ARG_pull].u_rom_obj == &digitalio_pull_down_obj) { + } else if (args[ARG_pull].u_rom_obj == &digitalio_pull_down_obj) { pull = PULL_DOWN; } // do the transfer diff --git a/shared-bindings/digitalio/DigitalInOut.h b/shared-bindings/digitalio/DigitalInOut.h index 3d1f9c7cb3..ebc94fa1a6 100644 --- a/shared-bindings/digitalio/DigitalInOut.h +++ b/shared-bindings/digitalio/DigitalInOut.h @@ -41,18 +41,18 @@ typedef enum { DIGITALINOUT_INPUT_ONLY } digitalinout_result_t; -digitalinout_result_t common_hal_digitalio_digitalinout_construct(digitalio_digitalinout_obj_t* self, const mcu_pin_obj_t* pin); -void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t* self); -bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t* self); -void common_hal_digitalio_digitalinout_switch_to_input(digitalio_digitalinout_obj_t* self, digitalio_pull_t pull); -digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output(digitalio_digitalinout_obj_t* self, bool value, digitalio_drive_mode_t drive_mode); -digitalio_direction_t common_hal_digitalio_digitalinout_get_direction(digitalio_digitalinout_obj_t* self); -void common_hal_digitalio_digitalinout_set_value(digitalio_digitalinout_obj_t* self, bool value); -bool common_hal_digitalio_digitalinout_get_value(digitalio_digitalinout_obj_t* self); -digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode(digitalio_digitalinout_obj_t* self, digitalio_drive_mode_t drive_mode); -digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode(digitalio_digitalinout_obj_t* self); -void common_hal_digitalio_digitalinout_set_pull(digitalio_digitalinout_obj_t* self, digitalio_pull_t pull); -digitalio_pull_t common_hal_digitalio_digitalinout_get_pull(digitalio_digitalinout_obj_t* self); +digitalinout_result_t common_hal_digitalio_digitalinout_construct(digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin); +void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self); +bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self); +void common_hal_digitalio_digitalinout_switch_to_input(digitalio_digitalinout_obj_t *self, digitalio_pull_t pull); +digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output(digitalio_digitalinout_obj_t *self, bool value, digitalio_drive_mode_t drive_mode); +digitalio_direction_t common_hal_digitalio_digitalinout_get_direction(digitalio_digitalinout_obj_t *self); +void common_hal_digitalio_digitalinout_set_value(digitalio_digitalinout_obj_t *self, bool value); +bool common_hal_digitalio_digitalinout_get_value(digitalio_digitalinout_obj_t *self); +digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode(digitalio_digitalinout_obj_t *self, digitalio_drive_mode_t drive_mode); +digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode(digitalio_digitalinout_obj_t *self); +void common_hal_digitalio_digitalinout_set_pull(digitalio_digitalinout_obj_t *self, digitalio_pull_t pull); +digitalio_pull_t common_hal_digitalio_digitalinout_get_pull(digitalio_digitalinout_obj_t *self); void common_hal_digitalio_digitalinout_never_reset(digitalio_digitalinout_obj_t *self); digitalio_digitalinout_obj_t *assert_digitalinout(mp_obj_t obj); diff --git a/shared-bindings/digitalio/__init__.c b/shared-bindings/digitalio/__init__.c index f8f45b158b..52ce377e37 100644 --- a/shared-bindings/digitalio/__init__.c +++ b/shared-bindings/digitalio/__init__.c @@ -88,5 +88,5 @@ STATIC MP_DEFINE_CONST_DICT(digitalio_module_globals, digitalio_module_globals_t const mp_obj_module_t digitalio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&digitalio_module_globals, + .globals = (mp_obj_dict_t *)&digitalio_module_globals, }; diff --git a/shared-bindings/displayio/Bitmap.c b/shared-bindings/displayio/Bitmap.c index b9f06fe143..f906be2f97 100644 --- a/shared-bindings/displayio/Bitmap.c +++ b/shared-bindings/displayio/Bitmap.c @@ -150,7 +150,7 @@ STATIC mp_obj_t bitmap_subscr(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t val x = i % width; y = i / width; } else { - mp_obj_t* items; + mp_obj_t *items; mp_obj_get_array_fixed_n(index_obj, 2, &items); x = mp_obj_get_int(items[0]); y = mp_obj_get_int(items[1]); @@ -189,7 +189,7 @@ STATIC mp_obj_t bitmap_subscr(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t val //| set to None to copy all pixels""" //| ... //| -STATIC mp_obj_t displayio_bitmap_obj_blit(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args){ +STATIC mp_obj_t displayio_bitmap_obj_blit(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum {ARG_x, ARG_y, ARG_source, ARG_x1, ARG_y1, ARG_x2, ARG_y2, ARG_skip_index}; static const mp_arg_t allowed_args[] = { {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_INT}, @@ -199,7 +199,7 @@ STATIC mp_obj_t displayio_bitmap_obj_blit(size_t n_args, const mp_obj_t *pos_arg {MP_QSTR_y1, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, {MP_QSTR_x2, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to source->width {MP_QSTR_y2, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, // None convert to source->height - {MP_QSTR_skip_index, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj=mp_const_none} }, + {MP_QSTR_skip_index, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -220,46 +220,46 @@ STATIC mp_obj_t displayio_bitmap_obj_blit(size_t n_args, const mp_obj_t *pos_arg int16_t y1 = args[ARG_y1].u_int; int16_t x2, y2; // if x2 or y2 is None, then set as the maximum size of the source bitmap - if ( args[ARG_x2].u_obj == mp_const_none ) { + if (args[ARG_x2].u_obj == mp_const_none) { x2 = source->width; } else { x2 = mp_obj_get_int(args[ARG_x2].u_obj); } - //int16_t y2; - if ( args[ARG_y2].u_obj == mp_const_none ) { + // int16_t y2; + if (args[ARG_y2].u_obj == mp_const_none) { y2 = source->height; } else { y2 = mp_obj_get_int(args[ARG_y2].u_obj); } // Check x,y are within self (target) bitmap boundary - if ( (x < 0) || (y < 0) || (x > self->width) || (y > self->height) ) { - mp_raise_ValueError(translate("out of range of target")); + if ((x < 0) || (y < 0) || (x > self->width) || (y > self->height)) { + mp_raise_ValueError(translate("out of range of target")); } // Check x1,y1,x2,y2 are within source bitmap boundary - if ( (x1 < 0) || (x1 > source->width) || + if ((x1 < 0) || (x1 > source->width) || (y1 < 0) || (y1 > source->height) || - (x2 < 0) || (x2 > source->width) || - (y2 < 0) || (y2 > source->height) ) { - mp_raise_ValueError(translate("out of range of source")); + (x2 < 0) || (x2 > source->width) || + (y2 < 0) || (y2 > source->height)) { + mp_raise_ValueError(translate("out of range of source")); } // Ensure x1 < x2 and y1 < y2 if (x1 > x2) { - int16_t temp=x2; - x2=x1; - x1=temp; + int16_t temp = x2; + x2 = x1; + x1 = temp; } if (y1 > y2) { - int16_t temp=y2; - y2=y1; - y1=temp; + int16_t temp = y2; + y2 = y1; + y1 = temp; } uint32_t skip_index; bool skip_index_none; // flag whether skip_value was None - if (args[ARG_skip_index].u_obj == mp_const_none ) { + if (args[ARG_skip_index].u_obj == mp_const_none) { skip_index = 0; skip_index_none = true; } else { @@ -283,7 +283,7 @@ STATIC mp_obj_t displayio_bitmap_obj_fill(mp_obj_t self_in, mp_obj_t value_obj) mp_uint_t value = (mp_uint_t)mp_obj_get_int(value_obj); if ((value >> common_hal_displayio_bitmap_get_bits_per_value(self)) != 0) { - mp_raise_ValueError(translate("pixel value requires too many bits")); + mp_raise_ValueError(translate("pixel value requires too many bits")); } common_hal_displayio_bitmap_fill(self, value); @@ -305,5 +305,5 @@ const mp_obj_type_t displayio_bitmap_type = { .name = MP_QSTR_Bitmap, .make_new = displayio_bitmap_make_new, .subscr = bitmap_subscr, - .locals_dict = (mp_obj_dict_t*)&displayio_bitmap_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_bitmap_locals_dict, }; diff --git a/shared-bindings/displayio/Bitmap.h b/shared-bindings/displayio/Bitmap.h index 00cd98b0a9..1f74c31fc5 100644 --- a/shared-bindings/displayio/Bitmap.h +++ b/shared-bindings/displayio/Bitmap.h @@ -34,15 +34,15 @@ extern const mp_obj_type_t displayio_bitmap_type; void common_hal_displayio_bitmap_construct(displayio_bitmap_t *self, uint32_t width, uint32_t height, uint32_t bits_per_value); -void common_hal_displayio_bitmap_load_row(displayio_bitmap_t *self, uint16_t y, uint8_t* data, - uint16_t len); +void common_hal_displayio_bitmap_load_row(displayio_bitmap_t *self, uint16_t y, uint8_t *data, + uint16_t len); uint16_t common_hal_displayio_bitmap_get_height(displayio_bitmap_t *self); uint16_t common_hal_displayio_bitmap_get_width(displayio_bitmap_t *self); uint32_t common_hal_displayio_bitmap_get_bits_per_value(displayio_bitmap_t *self); void common_hal_displayio_bitmap_set_pixel(displayio_bitmap_t *bitmap, int16_t x, int16_t y, uint32_t value); void common_hal_displayio_bitmap_blit(displayio_bitmap_t *self, int16_t x, int16_t y, displayio_bitmap_t *source, - int16_t x1, int16_t y1, int16_t x2, int16_t y2, - uint32_t skip_index, bool skip_index_none); + int16_t x1, int16_t y1, int16_t x2, int16_t y2, + uint32_t skip_index, bool skip_index_none); uint32_t common_hal_displayio_bitmap_get_pixel(displayio_bitmap_t *bitmap, int16_t x, int16_t y); void common_hal_displayio_bitmap_fill(displayio_bitmap_t *bitmap, uint32_t value); diff --git a/shared-bindings/displayio/ColorConverter.c b/shared-bindings/displayio/ColorConverter.c index 88d3a1ba8f..d102d7f9d1 100644 --- a/shared-bindings/displayio/ColorConverter.c +++ b/shared-bindings/displayio/ColorConverter.c @@ -146,5 +146,5 @@ const mp_obj_type_t displayio_colorconverter_type = { { &mp_type_type }, .name = MP_QSTR_ColorConverter, .make_new = displayio_colorconverter_make_new, - .locals_dict = (mp_obj_dict_t*)&displayio_colorconverter_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_colorconverter_locals_dict, }; diff --git a/shared-bindings/displayio/ColorConverter.h b/shared-bindings/displayio/ColorConverter.h index 441f7c7aee..d5a5d05243 100644 --- a/shared-bindings/displayio/ColorConverter.h +++ b/shared-bindings/displayio/ColorConverter.h @@ -33,13 +33,13 @@ extern const mp_obj_type_t displayio_colorconverter_type; -void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t* self, bool dither); -void common_hal_displayio_colorconverter_convert(displayio_colorconverter_t *colorconverter, const _displayio_colorspace_t* colorspace, uint32_t input_color, uint32_t* output_color); +void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t *self, bool dither); +void common_hal_displayio_colorconverter_convert(displayio_colorconverter_t *colorconverter, const _displayio_colorspace_t *colorspace, uint32_t input_color, uint32_t *output_color); -void common_hal_displayio_colorconverter_set_dither(displayio_colorconverter_t* self, bool dither); -bool common_hal_displayio_colorconverter_get_dither(displayio_colorconverter_t* self); +void common_hal_displayio_colorconverter_set_dither(displayio_colorconverter_t *self, bool dither); +bool common_hal_displayio_colorconverter_get_dither(displayio_colorconverter_t *self); -void common_hal_displayio_colorconverter_make_transparent(displayio_colorconverter_t* self, uint32_t transparent_color); -void common_hal_displayio_colorconverter_make_opaque(displayio_colorconverter_t* self, uint32_t transparent_color); +void common_hal_displayio_colorconverter_make_transparent(displayio_colorconverter_t *self, uint32_t transparent_color); +void common_hal_displayio_colorconverter_make_opaque(displayio_colorconverter_t *self, uint32_t transparent_color); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_COLORCONVERTER_H diff --git a/shared-bindings/displayio/Display.c b/shared-bindings/displayio/Display.c index 8d1a888fe7..9d8f8298f6 100644 --- a/shared-bindings/displayio/Display.c +++ b/shared-bindings/displayio/Display.c @@ -114,15 +114,15 @@ //| ... //| STATIC mp_obj_t displayio_display_make_new(const mp_obj_type_t *type, size_t n_args, - const mp_obj_t *pos_args, mp_map_t *kw_args) { + const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_display_bus, ARG_init_sequence, ARG_width, ARG_height, ARG_colstart, ARG_rowstart, - ARG_rotation, ARG_color_depth, ARG_grayscale, ARG_pixels_in_byte_share_row, - ARG_bytes_per_cell, ARG_reverse_pixels_in_byte, ARG_reverse_bytes_in_word, - ARG_set_column_command, ARG_set_row_command, ARG_write_ram_command, - ARG_set_vertical_scroll, ARG_backlight_pin, ARG_brightness_command, - ARG_brightness, ARG_auto_brightness, ARG_single_byte_bounds, ARG_data_as_commands, - ARG_auto_refresh, ARG_native_frames_per_second, ARG_backlight_on_high, - ARG_SH1107_addressing }; + ARG_rotation, ARG_color_depth, ARG_grayscale, ARG_pixels_in_byte_share_row, + ARG_bytes_per_cell, ARG_reverse_pixels_in_byte, ARG_reverse_bytes_in_word, + ARG_set_column_command, ARG_set_row_command, ARG_write_ram_command, + ARG_set_vertical_scroll, ARG_backlight_pin, ARG_brightness_command, + ARG_brightness, ARG_auto_brightness, ARG_single_byte_bounds, ARG_data_as_commands, + ARG_auto_refresh, ARG_native_frames_per_second, ARG_backlight_on_high, + ARG_SH1107_addressing }; static const mp_arg_t allowed_args[] = { { MP_QSTR_display_bus, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_init_sequence, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -160,7 +160,7 @@ STATIC mp_obj_t displayio_display_make_new(const mp_obj_type_t *type, size_t n_a mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[ARG_init_sequence].u_obj, &bufinfo, MP_BUFFER_READ); - const mcu_pin_obj_t* backlight_pin = validate_obj_is_free_pin_or_none(args[ARG_backlight_pin].u_obj); + const mcu_pin_obj_t *backlight_pin = validate_obj_is_free_pin_or_none(args[ARG_backlight_pin].u_obj); mp_float_t brightness = mp_obj_get_float(args[ARG_brightness].u_obj); @@ -170,7 +170,8 @@ STATIC mp_obj_t displayio_display_make_new(const mp_obj_type_t *type, size_t n_a } primary_display_t *disp = allocate_display_or_raise(); - displayio_display_obj_t *self = &disp->display;; + displayio_display_obj_t *self = &disp->display; + ; self->base.type = &displayio_display_type; common_hal_displayio_display_construct( self, @@ -200,7 +201,7 @@ STATIC mp_obj_t displayio_display_make_new(const mp_obj_type_t *type, size_t n_a } // Helper to ensure we have the native super class instead of a subclass. -static displayio_display_obj_t* native_display(mp_obj_t display_obj) { +static displayio_display_obj_t *native_display(mp_obj_t display_obj) { mp_obj_t native_display = mp_instance_cast_to_native_base(display_obj, &displayio_display_type); mp_obj_assert_native_inited(native_display); return MP_OBJ_TO_PTR(native_display); @@ -215,7 +216,7 @@ static displayio_display_obj_t* native_display(mp_obj_t display_obj) { //| STATIC mp_obj_t displayio_display_obj_show(mp_obj_t self_in, mp_obj_t group_in) { displayio_display_obj_t *self = native_display(self_in); - displayio_group_t* group = NULL; + displayio_group_t *group = NULL; if (group_in != mp_const_none) { group = MP_OBJ_TO_PTR(native_group(group_in)); } @@ -268,8 +269,7 @@ STATIC mp_obj_t displayio_display_obj_refresh(size_t n_args, const mp_obj_t *pos uint32_t target_ms_per_frame; if (args[ARG_target_frames_per_second].u_obj == mp_const_none) { target_ms_per_frame = 0xffffffff; - } - else { + } else { target_ms_per_frame = 1000 / mp_obj_get_int(args[ARG_target_frames_per_second].u_obj); } @@ -467,40 +467,40 @@ STATIC mp_obj_t displayio_display_obj_fill_row(size_t n_args, const mp_obj_t *po mp_get_buffer_raise(result, &bufinfo, MP_BUFFER_WRITE); if (bufinfo.typecode != BYTEARRAY_TYPECODE) { - mp_raise_ValueError(translate("Buffer is not a bytearray.")); + mp_raise_ValueError(translate("Buffer is not a bytearray.")); } if (self->core.colorspace.depth != 16) { - mp_raise_ValueError(translate("Display must have a 16 bit colorspace.")); + mp_raise_ValueError(translate("Display must have a 16 bit colorspace.")); } displayio_area_t area = { - .x1 = 0, - .y1 = y, - .x2 = self->core.width, - .y2 = y + 1 + .x1 = 0, + .y1 = y, + .x2 = self->core.width, + .y2 = y + 1 }; uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth; uint16_t buffer_size = self->core.width / pixels_per_word; uint16_t pixels_per_buffer = displayio_area_size(&area); if (pixels_per_buffer % pixels_per_word) { - buffer_size += 1; + buffer_size += 1; } uint32_t *result_buffer = bufinfo.buf; size_t result_buffer_size = bufinfo.len; if (result_buffer_size >= (buffer_size * 4)) { - volatile uint32_t mask_length = (pixels_per_buffer / 32) + 1; - uint32_t mask[mask_length]; + volatile uint32_t mask_length = (pixels_per_buffer / 32) + 1; + uint32_t mask[mask_length]; - for (uint16_t k = 0; k < mask_length; k++) { - mask[k] = 0x00000000; - } + for (uint16_t k = 0; k < mask_length; k++) { + mask[k] = 0x00000000; + } - displayio_display_core_fill_area(&self->core, &area, mask, result_buffer); - return result; + displayio_display_core_fill_area(&self->core, &area, mask, result_buffer); + return result; } else { - mp_raise_ValueError(translate("Buffer is too small")); + mp_raise_ValueError(translate("Buffer is too small")); } } MP_DEFINE_CONST_FUN_OBJ_KW(displayio_display_fill_row_obj, 1, displayio_display_obj_fill_row); @@ -526,5 +526,5 @@ const mp_obj_type_t displayio_display_type = { { &mp_type_type }, .name = MP_QSTR_Display, .make_new = displayio_display_make_new, - .locals_dict = (mp_obj_dict_t*)&displayio_display_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_display_locals_dict, }; diff --git a/shared-bindings/displayio/Display.h b/shared-bindings/displayio/Display.h index f9fbc157c0..36015cd56f 100644 --- a/shared-bindings/displayio/Display.h +++ b/shared-bindings/displayio/Display.h @@ -38,39 +38,39 @@ extern const mp_obj_type_t displayio_display_type; #define NO_BRIGHTNESS_COMMAND 0x100 -void common_hal_displayio_display_construct(displayio_display_obj_t* self, +void common_hal_displayio_display_construct(displayio_display_obj_t *self, mp_obj_t bus, uint16_t width, uint16_t height, int16_t colstart, int16_t rowstart, uint16_t rotation, uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word, uint8_t set_column_command, uint8_t set_row_command, uint8_t write_ram_command, uint8_t set_vertical_scroll, - uint8_t* init_sequence, uint16_t init_sequence_len, const mcu_pin_obj_t* backlight_pin, uint16_t brightness_command, + uint8_t *init_sequence, uint16_t init_sequence_len, const mcu_pin_obj_t *backlight_pin, uint16_t brightness_command, mp_float_t brightness, bool auto_brightness, bool single_byte_bounds, bool data_as_commands, bool auto_refresh, uint16_t native_frames_per_second, bool backlight_on_high, bool SH1107_addressing); -bool common_hal_displayio_display_show(displayio_display_obj_t* self, - displayio_group_t* root_group); +bool common_hal_displayio_display_show(displayio_display_obj_t *self, + displayio_group_t *root_group); -bool common_hal_displayio_display_refresh(displayio_display_obj_t* self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame); +bool common_hal_displayio_display_refresh(displayio_display_obj_t *self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame); -bool common_hal_displayio_display_get_auto_refresh(displayio_display_obj_t* self); -void common_hal_displayio_display_set_auto_refresh(displayio_display_obj_t* self, bool auto_refresh); +bool common_hal_displayio_display_get_auto_refresh(displayio_display_obj_t *self); +void common_hal_displayio_display_set_auto_refresh(displayio_display_obj_t *self, bool auto_refresh); -uint16_t common_hal_displayio_display_get_width(displayio_display_obj_t* self); -uint16_t common_hal_displayio_display_get_height(displayio_display_obj_t* self); -uint16_t common_hal_displayio_display_get_rotation(displayio_display_obj_t* self); -void common_hal_displayio_display_set_rotation(displayio_display_obj_t* self, int rotation); +uint16_t common_hal_displayio_display_get_width(displayio_display_obj_t *self); +uint16_t common_hal_displayio_display_get_height(displayio_display_obj_t *self); +uint16_t common_hal_displayio_display_get_rotation(displayio_display_obj_t *self); +void common_hal_displayio_display_set_rotation(displayio_display_obj_t *self, int rotation); -bool common_hal_displayio_display_get_auto_brightness(displayio_display_obj_t* self); -void common_hal_displayio_display_set_auto_brightness(displayio_display_obj_t* self, bool auto_brightness); +bool common_hal_displayio_display_get_auto_brightness(displayio_display_obj_t *self); +void common_hal_displayio_display_set_auto_brightness(displayio_display_obj_t *self, bool auto_brightness); -bool common_hal_displayio_display_get_dither(displayio_display_obj_t* self); -void common_hal_displayio_display_set_dither(displayio_display_obj_t* self, bool dither); +bool common_hal_displayio_display_get_dither(displayio_display_obj_t *self); +void common_hal_displayio_display_set_dither(displayio_display_obj_t *self, bool dither); -mp_float_t common_hal_displayio_display_get_brightness(displayio_display_obj_t* self); -bool common_hal_displayio_display_set_brightness(displayio_display_obj_t* self, mp_float_t brightness); +mp_float_t common_hal_displayio_display_get_brightness(displayio_display_obj_t *self); +bool common_hal_displayio_display_set_brightness(displayio_display_obj_t *self, mp_float_t brightness); -mp_obj_t common_hal_displayio_display_get_bus(displayio_display_obj_t* self); +mp_obj_t common_hal_displayio_display_get_bus(displayio_display_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_DISPLAY_H diff --git a/shared-bindings/displayio/EPaperDisplay.c b/shared-bindings/displayio/EPaperDisplay.c index 4f5c47acab..6a7c089c9d 100644 --- a/shared-bindings/displayio/EPaperDisplay.c +++ b/shared-bindings/displayio/EPaperDisplay.c @@ -148,7 +148,7 @@ STATIC mp_obj_t displayio_epaperdisplay_make_new(const mp_obj_type_t *type, size mp_get_buffer_raise(args[ARG_stop_sequence].u_obj, &stop_bufinfo, MP_BUFFER_READ); - const mcu_pin_obj_t* busy_pin = validate_obj_is_free_pin_or_none(args[ARG_busy_pin].u_obj); + const mcu_pin_obj_t *busy_pin = validate_obj_is_free_pin_or_none(args[ARG_busy_pin].u_obj); mp_int_t rotation = args[ARG_rotation].u_int; if (rotation % 90 != 0) { @@ -156,7 +156,8 @@ STATIC mp_obj_t displayio_epaperdisplay_make_new(const mp_obj_type_t *type, size } primary_display_t *disp = allocate_display_or_raise(); - displayio_epaperdisplay_obj_t *self = &disp->epaper_display;; + displayio_epaperdisplay_obj_t *self = &disp->epaper_display; + ; mp_float_t refresh_time = mp_obj_get_float(args[ARG_refresh_time].u_obj); mp_float_t seconds_per_frame = mp_obj_get_float(args[ARG_seconds_per_frame].u_obj); @@ -186,7 +187,7 @@ STATIC mp_obj_t displayio_epaperdisplay_make_new(const mp_obj_type_t *type, size } // Helper to ensure we have the native super class instead of a subclass. -static displayio_epaperdisplay_obj_t* native_display(mp_obj_t display_obj) { +static displayio_epaperdisplay_obj_t *native_display(mp_obj_t display_obj) { mp_obj_t native_display = mp_instance_cast_to_native_base(display_obj, &displayio_epaperdisplay_type); mp_obj_assert_native_inited(native_display); return MP_OBJ_TO_PTR(native_display); @@ -201,7 +202,7 @@ static displayio_epaperdisplay_obj_t* native_display(mp_obj_t display_obj) { //| STATIC mp_obj_t displayio_epaperdisplay_obj_show(mp_obj_t self_in, mp_obj_t group_in) { displayio_epaperdisplay_obj_t *self = native_display(self_in); - displayio_group_t* group = NULL; + displayio_group_t *group = NULL; if (group_in != mp_const_none) { group = MP_OBJ_TO_PTR(native_group(group_in)); } @@ -351,5 +352,5 @@ const mp_obj_type_t displayio_epaperdisplay_type = { { &mp_type_type }, .name = MP_QSTR_EPaperDisplay, .make_new = displayio_epaperdisplay_make_new, - .locals_dict = (mp_obj_dict_t*)&displayio_epaperdisplay_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_epaperdisplay_locals_dict, }; diff --git a/shared-bindings/displayio/EPaperDisplay.h b/shared-bindings/displayio/EPaperDisplay.h index 14d4f6aa9a..7c2b302ce5 100644 --- a/shared-bindings/displayio/EPaperDisplay.h +++ b/shared-bindings/displayio/EPaperDisplay.h @@ -38,27 +38,27 @@ extern const mp_obj_type_t displayio_epaperdisplay_type; #define NO_COMMAND 0x100 -void common_hal_displayio_epaperdisplay_construct(displayio_epaperdisplay_obj_t* self, - mp_obj_t bus, const uint8_t* start_sequence, uint16_t start_sequence_len, const uint8_t* stop_sequence, uint16_t stop_sequence_len, - uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t rotation, - uint16_t set_column_window_command, uint16_t set_row_window_command, - uint16_t set_current_column_command, uint16_t set_current_row_command, - uint16_t write_black_ram_command, bool black_bits_inverted, uint16_t write_color_ram_command, bool color_bits_inverted, uint32_t highlight_color, uint16_t refresh_display_command, mp_float_t refresh_time, - const mcu_pin_obj_t* busy_pin, bool busy_state, mp_float_t seconds_per_frame, bool always_toggle_chip_select, bool grayscale); +void common_hal_displayio_epaperdisplay_construct(displayio_epaperdisplay_obj_t *self, + mp_obj_t bus, const uint8_t *start_sequence, uint16_t start_sequence_len, const uint8_t *stop_sequence, uint16_t stop_sequence_len, + uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t rotation, + uint16_t set_column_window_command, uint16_t set_row_window_command, + uint16_t set_current_column_command, uint16_t set_current_row_command, + uint16_t write_black_ram_command, bool black_bits_inverted, uint16_t write_color_ram_command, bool color_bits_inverted, uint32_t highlight_color, uint16_t refresh_display_command, mp_float_t refresh_time, + const mcu_pin_obj_t *busy_pin, bool busy_state, mp_float_t seconds_per_frame, bool always_toggle_chip_select, bool grayscale); -bool common_hal_displayio_epaperdisplay_refresh(displayio_epaperdisplay_obj_t* self); +bool common_hal_displayio_epaperdisplay_refresh(displayio_epaperdisplay_obj_t *self); -bool common_hal_displayio_epaperdisplay_show(displayio_epaperdisplay_obj_t* self, displayio_group_t* root_group); +bool common_hal_displayio_epaperdisplay_show(displayio_epaperdisplay_obj_t *self, displayio_group_t *root_group); // Returns time in milliseconds. -uint32_t common_hal_displayio_epaperdisplay_get_time_to_refresh(displayio_epaperdisplay_obj_t* self); -bool common_hal_displayio_epaperdisplay_get_busy(displayio_epaperdisplay_obj_t* self); +uint32_t common_hal_displayio_epaperdisplay_get_time_to_refresh(displayio_epaperdisplay_obj_t *self); +bool common_hal_displayio_epaperdisplay_get_busy(displayio_epaperdisplay_obj_t *self); -uint16_t common_hal_displayio_epaperdisplay_get_width(displayio_epaperdisplay_obj_t* self); -uint16_t common_hal_displayio_epaperdisplay_get_height(displayio_epaperdisplay_obj_t* self); -uint16_t common_hal_displayio_epaperdisplay_get_rotation(displayio_epaperdisplay_obj_t* self); -void common_hal_displayio_epaperdisplay_set_rotation(displayio_epaperdisplay_obj_t* self, int rotation); +uint16_t common_hal_displayio_epaperdisplay_get_width(displayio_epaperdisplay_obj_t *self); +uint16_t common_hal_displayio_epaperdisplay_get_height(displayio_epaperdisplay_obj_t *self); +uint16_t common_hal_displayio_epaperdisplay_get_rotation(displayio_epaperdisplay_obj_t *self); +void common_hal_displayio_epaperdisplay_set_rotation(displayio_epaperdisplay_obj_t *self, int rotation); -mp_obj_t common_hal_displayio_epaperdisplay_get_bus(displayio_epaperdisplay_obj_t* self); +mp_obj_t common_hal_displayio_epaperdisplay_get_bus(displayio_epaperdisplay_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_EPAPERDISPLAY_H diff --git a/shared-bindings/displayio/FourWire.c b/shared-bindings/displayio/FourWire.c index 455d22e725..d87f2421da 100644 --- a/shared-bindings/displayio/FourWire.c +++ b/shared-bindings/displayio/FourWire.c @@ -79,7 +79,7 @@ STATIC mp_obj_t displayio_fourwire_make_new(const mp_obj_type_t *type, size_t n_ mcu_pin_obj_t *reset = validate_obj_is_free_pin_or_none(args[ARG_reset].u_obj); mp_obj_t spi = args[ARG_spi_bus].u_obj; - displayio_fourwire_obj_t* self = &allocate_display_bus_or_raise()->fourwire_bus; + displayio_fourwire_obj_t *self = &allocate_display_bus_or_raise()->fourwire_bus; self->base.type = &displayio_fourwire_type; uint8_t polarity = args[ARG_polarity].u_int; @@ -144,7 +144,7 @@ STATIC mp_obj_t displayio_fourwire_obj_send(size_t n_args, const mp_obj_t *pos_a chip_select = CHIP_SELECT_TOGGLE_EVERY_BYTE; } common_hal_displayio_fourwire_send(self, DISPLAY_COMMAND, chip_select, &command, 1); - common_hal_displayio_fourwire_send(self, DISPLAY_DATA, chip_select, ((uint8_t*) bufinfo.buf), bufinfo.len); + common_hal_displayio_fourwire_send(self, DISPLAY_DATA, chip_select, ((uint8_t *)bufinfo.buf), bufinfo.len); common_hal_displayio_fourwire_end_transaction(self); return mp_const_none; @@ -161,5 +161,5 @@ const mp_obj_type_t displayio_fourwire_type = { { &mp_type_type }, .name = MP_QSTR_FourWire, .make_new = displayio_fourwire_make_new, - .locals_dict = (mp_obj_dict_t*)&displayio_fourwire_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_fourwire_locals_dict, }; diff --git a/shared-bindings/displayio/FourWire.h b/shared-bindings/displayio/FourWire.h index 6f6b528e72..300327f7a2 100644 --- a/shared-bindings/displayio/FourWire.h +++ b/shared-bindings/displayio/FourWire.h @@ -36,12 +36,12 @@ extern const mp_obj_type_t displayio_fourwire_type; -void common_hal_displayio_fourwire_construct(displayio_fourwire_obj_t* self, - busio_spi_obj_t* spi, const mcu_pin_obj_t* command, - const mcu_pin_obj_t* chip_select, const mcu_pin_obj_t* reset, uint32_t baudrate, +void common_hal_displayio_fourwire_construct(displayio_fourwire_obj_t *self, + busio_spi_obj_t *spi, const mcu_pin_obj_t *command, + const mcu_pin_obj_t *chip_select, const mcu_pin_obj_t *reset, uint32_t baudrate, uint8_t polarity, uint8_t phase); -void common_hal_displayio_fourwire_deinit(displayio_fourwire_obj_t* self); +void common_hal_displayio_fourwire_deinit(displayio_fourwire_obj_t *self); bool common_hal_displayio_fourwire_reset(mp_obj_t self); bool common_hal_displayio_fourwire_bus_free(mp_obj_t self); diff --git a/shared-bindings/displayio/Group.c b/shared-bindings/displayio/Group.c index c1c05504da..75e210db89 100644 --- a/shared-bindings/displayio/Group.c +++ b/shared-bindings/displayio/Group.c @@ -72,7 +72,7 @@ STATIC mp_obj_t displayio_group_make_new(const mp_obj_type_t *type, size_t n_arg } // Helper to ensure we have the native super class instead of a subclass. -displayio_group_t* native_group(mp_obj_t group_obj) { +displayio_group_t *native_group(mp_obj_t group_obj) { mp_obj_t native_group = mp_instance_cast_to_native_base(group_obj, &displayio_group_type); if (native_group == MP_OBJ_NULL) { mp_raise_ValueError_varg(translate("Must be a %q subclass."), MP_QSTR_Group); @@ -202,7 +202,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_append_obj, displayio_group_obj_append //| STATIC mp_obj_t displayio_group_obj_insert(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t layer) { displayio_group_t *self = native_group(self_in); - if ((size_t) MP_OBJ_SMALL_INT_VALUE(index_obj) == common_hal_displayio_group_get_len(self)){ + if ((size_t)MP_OBJ_SMALL_INT_VALUE(index_obj) == common_hal_displayio_group_get_len(self)) { return displayio_group_obj_append(self_in, layer); } size_t index = mp_get_index(&displayio_group_type, common_hal_displayio_group_get_len(self), index_obj, false); @@ -241,9 +241,9 @@ STATIC mp_obj_t displayio_group_obj_pop(size_t n_args, const mp_obj_t *pos_args, displayio_group_t *self = native_group(pos_args[0]); size_t index = mp_get_index(&displayio_group_type, - common_hal_displayio_group_get_len(self), - MP_OBJ_NEW_SMALL_INT(args[ARG_i].u_int), - false); + common_hal_displayio_group_get_len(self), + MP_OBJ_NEW_SMALL_INT(args[ARG_i].u_int), + false); return common_hal_displayio_group_pop(self, index); } MP_DEFINE_CONST_FUN_OBJ_KW(displayio_group_pop_obj, 1, displayio_group_obj_pop); @@ -273,9 +273,12 @@ STATIC mp_obj_t group_unary_op(mp_unary_op_t op, mp_obj_t self_in) { displayio_group_t *self = native_group(self_in); uint16_t len = common_hal_displayio_group_get_len(self); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -359,5 +362,5 @@ const mp_obj_type_t displayio_group_type = { .subscr = group_subscr, .unary_op = group_unary_op, .getiter = mp_obj_new_generic_iterator, - .locals_dict = (mp_obj_dict_t*)&displayio_group_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_group_locals_dict, }; diff --git a/shared-bindings/displayio/Group.h b/shared-bindings/displayio/Group.h index 69c73bf4dc..266fce959c 100644 --- a/shared-bindings/displayio/Group.h +++ b/shared-bindings/displayio/Group.h @@ -31,23 +31,23 @@ extern const mp_obj_type_t displayio_group_type; -displayio_group_t* native_group(mp_obj_t group_obj); +displayio_group_t *native_group(mp_obj_t group_obj); -void common_hal_displayio_group_construct(displayio_group_t* self, uint32_t scale, mp_int_t x, mp_int_t y); -uint32_t common_hal_displayio_group_get_scale(displayio_group_t* self); -void common_hal_displayio_group_set_scale(displayio_group_t* self, uint32_t scale); -bool common_hal_displayio_group_get_hidden(displayio_group_t* self); -void common_hal_displayio_group_set_hidden(displayio_group_t* self, bool hidden); -mp_int_t common_hal_displayio_group_get_x(displayio_group_t* self); -void common_hal_displayio_group_set_x(displayio_group_t* self, mp_int_t x); -mp_int_t common_hal_displayio_group_get_y(displayio_group_t* self); -void common_hal_displayio_group_set_y(displayio_group_t* self, mp_int_t y); -void common_hal_displayio_group_append(displayio_group_t* self, mp_obj_t layer); -void common_hal_displayio_group_insert(displayio_group_t* self, size_t index, mp_obj_t layer); -size_t common_hal_displayio_group_get_len(displayio_group_t* self); -mp_obj_t common_hal_displayio_group_pop(displayio_group_t* self, size_t index); -mp_int_t common_hal_displayio_group_index(displayio_group_t* self, mp_obj_t layer); -mp_obj_t common_hal_displayio_group_get(displayio_group_t* self, size_t index); -void common_hal_displayio_group_set(displayio_group_t* self, size_t index, mp_obj_t layer); +void common_hal_displayio_group_construct(displayio_group_t *self, uint32_t scale, mp_int_t x, mp_int_t y); +uint32_t common_hal_displayio_group_get_scale(displayio_group_t *self); +void common_hal_displayio_group_set_scale(displayio_group_t *self, uint32_t scale); +bool common_hal_displayio_group_get_hidden(displayio_group_t *self); +void common_hal_displayio_group_set_hidden(displayio_group_t *self, bool hidden); +mp_int_t common_hal_displayio_group_get_x(displayio_group_t *self); +void common_hal_displayio_group_set_x(displayio_group_t *self, mp_int_t x); +mp_int_t common_hal_displayio_group_get_y(displayio_group_t *self); +void common_hal_displayio_group_set_y(displayio_group_t *self, mp_int_t y); +void common_hal_displayio_group_append(displayio_group_t *self, mp_obj_t layer); +void common_hal_displayio_group_insert(displayio_group_t *self, size_t index, mp_obj_t layer); +size_t common_hal_displayio_group_get_len(displayio_group_t *self); +mp_obj_t common_hal_displayio_group_pop(displayio_group_t *self, size_t index); +mp_int_t common_hal_displayio_group_index(displayio_group_t *self, mp_obj_t layer); +mp_obj_t common_hal_displayio_group_get(displayio_group_t *self, size_t index); +void common_hal_displayio_group_set(displayio_group_t *self, size_t index, mp_obj_t layer); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_GROUP_H diff --git a/shared-bindings/displayio/I2CDisplay.c b/shared-bindings/displayio/I2CDisplay.c index 5dc4711b3b..2f27c7b5d7 100644 --- a/shared-bindings/displayio/I2CDisplay.c +++ b/shared-bindings/displayio/I2CDisplay.c @@ -68,7 +68,7 @@ STATIC mp_obj_t displayio_i2cdisplay_make_new(const mp_obj_type_t *type, size_t mcu_pin_obj_t *reset = validate_obj_is_free_pin_or_none(args[ARG_reset].u_obj); mp_obj_t i2c = args[ARG_i2c_bus].u_obj; - displayio_i2cdisplay_obj_t* self = &allocate_display_bus_or_raise()->i2cdisplay_bus; + displayio_i2cdisplay_obj_t *self = &allocate_display_bus_or_raise()->i2cdisplay_bus; self->base.type = &displayio_i2cdisplay_type; common_hal_displayio_i2cdisplay_construct(self, @@ -111,7 +111,7 @@ STATIC mp_obj_t displayio_i2cdisplay_obj_send(mp_obj_t self, mp_obj_t command_ob } uint8_t full_command[bufinfo.len + 1]; full_command[0] = command; - memcpy(full_command + 1, ((uint8_t*) bufinfo.buf), bufinfo.len); + memcpy(full_command + 1, ((uint8_t *)bufinfo.buf), bufinfo.len); common_hal_displayio_i2cdisplay_send(self, DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, full_command, bufinfo.len + 1); common_hal_displayio_i2cdisplay_end_transaction(self); @@ -129,5 +129,5 @@ const mp_obj_type_t displayio_i2cdisplay_type = { { &mp_type_type }, .name = MP_QSTR_I2CDisplay, .make_new = displayio_i2cdisplay_make_new, - .locals_dict = (mp_obj_dict_t*)&displayio_i2cdisplay_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_i2cdisplay_locals_dict, }; diff --git a/shared-bindings/displayio/I2CDisplay.h b/shared-bindings/displayio/I2CDisplay.h index 37520202e4..d40cd19d8d 100644 --- a/shared-bindings/displayio/I2CDisplay.h +++ b/shared-bindings/displayio/I2CDisplay.h @@ -34,10 +34,10 @@ extern const mp_obj_type_t displayio_i2cdisplay_type; -void common_hal_displayio_i2cdisplay_construct(displayio_i2cdisplay_obj_t* self, - busio_i2c_obj_t* i2c, uint16_t device_address, const mcu_pin_obj_t* reset); +void common_hal_displayio_i2cdisplay_construct(displayio_i2cdisplay_obj_t *self, + busio_i2c_obj_t *i2c, uint16_t device_address, const mcu_pin_obj_t *reset); -void common_hal_displayio_i2cdisplay_deinit(displayio_i2cdisplay_obj_t* self); +void common_hal_displayio_i2cdisplay_deinit(displayio_i2cdisplay_obj_t *self); bool common_hal_displayio_i2cdisplay_reset(mp_obj_t self); bool common_hal_displayio_i2cdisplay_bus_free(mp_obj_t self); diff --git a/shared-bindings/displayio/OnDiskBitmap.c b/shared-bindings/displayio/OnDiskBitmap.c index 938e408ab5..e41f54edfb 100644 --- a/shared-bindings/displayio/OnDiskBitmap.c +++ b/shared-bindings/displayio/OnDiskBitmap.c @@ -137,5 +137,5 @@ const mp_obj_type_t displayio_ondiskbitmap_type = { { &mp_type_type }, .name = MP_QSTR_OnDiskBitmap, .make_new = displayio_ondiskbitmap_make_new, - .locals_dict = (mp_obj_dict_t*)&displayio_ondiskbitmap_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_ondiskbitmap_locals_dict, }; diff --git a/shared-bindings/displayio/OnDiskBitmap.h b/shared-bindings/displayio/OnDiskBitmap.h index 9a6c81f8f1..aff3a19db2 100644 --- a/shared-bindings/displayio/OnDiskBitmap.h +++ b/shared-bindings/displayio/OnDiskBitmap.h @@ -32,7 +32,7 @@ extern const mp_obj_type_t displayio_ondiskbitmap_type; -void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, pyb_file_obj_t* file); +void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, pyb_file_obj_t *file); uint32_t common_hal_displayio_ondiskbitmap_get_pixel(displayio_ondiskbitmap_t *bitmap, int16_t x, int16_t y); diff --git a/shared-bindings/displayio/Palette.c b/shared-bindings/displayio/Palette.c index c868aea9cf..d5acf1ed60 100644 --- a/shared-bindings/displayio/Palette.c +++ b/shared-bindings/displayio/Palette.c @@ -74,10 +74,12 @@ STATIC mp_obj_t displayio_palette_make_new(const mp_obj_type_t *type, size_t n_a STATIC mp_obj_t group_unary_op(mp_unary_op_t op, mp_obj_t self_in) { displayio_palette_t *self = MP_OBJ_TO_PTR(self_in); switch (op) { - case MP_UNARY_OP_BOOL: return mp_const_true; + case MP_UNARY_OP_BOOL: + return mp_const_true; case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(common_hal_displayio_palette_get_len(self)); - default: return MP_OBJ_NULL; // op not supported + default: + return MP_OBJ_NULL; // op not supported } } @@ -130,7 +132,7 @@ STATIC mp_obj_t palette_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t val if (bufinfo.typecode != 'b' && bufinfo.typecode != 'B' && bufinfo.typecode != BYTEARRAY_TYPECODE) { mp_raise_ValueError(translate("color buffer must be a bytearray or array of type 'b' or 'B'")); } - uint8_t* buf = bufinfo.buf; + uint8_t *buf = bufinfo.buf; if (bufinfo.len == 3 || bufinfo.len == 4) { color = buf[0] << 16 | buf[1] << 8 | buf[2]; } else { @@ -191,5 +193,5 @@ const mp_obj_type_t displayio_palette_type = { .subscr = palette_subscr, .unary_op = group_unary_op, .getiter = mp_obj_new_generic_iterator, - .locals_dict = (mp_obj_dict_t*)&displayio_palette_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_palette_locals_dict, }; diff --git a/shared-bindings/displayio/Palette.h b/shared-bindings/displayio/Palette.h index 8c9fe11e38..62b8f36009 100644 --- a/shared-bindings/displayio/Palette.h +++ b/shared-bindings/displayio/Palette.h @@ -31,12 +31,12 @@ extern const mp_obj_type_t displayio_palette_type; -void common_hal_displayio_palette_construct(displayio_palette_t* self, uint16_t color_count); -void common_hal_displayio_palette_set_color(displayio_palette_t* self, uint32_t palette_index, uint32_t color); -uint32_t common_hal_displayio_palette_get_color(displayio_palette_t* self, uint32_t palette_index); -uint32_t common_hal_displayio_palette_get_len(displayio_palette_t* self); +void common_hal_displayio_palette_construct(displayio_palette_t *self, uint16_t color_count); +void common_hal_displayio_palette_set_color(displayio_palette_t *self, uint32_t palette_index, uint32_t color); +uint32_t common_hal_displayio_palette_get_color(displayio_palette_t *self, uint32_t palette_index); +uint32_t common_hal_displayio_palette_get_len(displayio_palette_t *self); -void common_hal_displayio_palette_make_opaque(displayio_palette_t* self, uint32_t palette_index); -void common_hal_displayio_palette_make_transparent(displayio_palette_t* self, uint32_t palette_index); +void common_hal_displayio_palette_make_opaque(displayio_palette_t *self, uint32_t palette_index); +void common_hal_displayio_palette_make_transparent(displayio_palette_t *self, uint32_t palette_index); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_PALETTE_H diff --git a/shared-bindings/displayio/ParallelBus.c b/shared-bindings/displayio/ParallelBus.c index 30c9d373c8..69483d5aa1 100644 --- a/shared-bindings/displayio/ParallelBus.c +++ b/shared-bindings/displayio/ParallelBus.c @@ -79,7 +79,7 @@ STATIC mp_obj_t displayio_parallelbus_make_new(const mp_obj_type_t *type, size_t mcu_pin_obj_t *read = validate_obj_is_free_pin(args[ARG_read].u_obj); mcu_pin_obj_t *reset = validate_obj_is_free_pin(args[ARG_reset].u_obj); - displayio_parallelbus_obj_t* self = &allocate_display_bus_or_raise()->parallel_bus; + displayio_parallelbus_obj_t *self = &allocate_display_bus_or_raise()->parallel_bus; self->base.type = &displayio_parallelbus_type; common_hal_displayio_parallelbus_construct(self, data0, command, chip_select, write, read, reset); @@ -121,7 +121,7 @@ STATIC mp_obj_t displayio_parallelbus_obj_send(mp_obj_t self, mp_obj_t command_o RUN_BACKGROUND_TASKS; } common_hal_displayio_parallelbus_send(self, DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, &command, 1); - common_hal_displayio_parallelbus_send(self, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, ((uint8_t*) bufinfo.buf), bufinfo.len); + common_hal_displayio_parallelbus_send(self, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, ((uint8_t *)bufinfo.buf), bufinfo.len); common_hal_displayio_parallelbus_end_transaction(self); return mp_const_none; @@ -138,5 +138,5 @@ const mp_obj_type_t displayio_parallelbus_type = { { &mp_type_type }, .name = MP_QSTR_ParallelBus, .make_new = displayio_parallelbus_make_new, - .locals_dict = (mp_obj_dict_t*)&displayio_parallelbus_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_parallelbus_locals_dict, }; diff --git a/shared-bindings/displayio/ParallelBus.h b/shared-bindings/displayio/ParallelBus.h index 1e74e3a0ac..24c973884d 100644 --- a/shared-bindings/displayio/ParallelBus.h +++ b/shared-bindings/displayio/ParallelBus.h @@ -35,11 +35,11 @@ extern const mp_obj_type_t displayio_parallelbus_type; -void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t* self, - const mcu_pin_obj_t* data0, const mcu_pin_obj_t* command, const mcu_pin_obj_t* chip_select, - const mcu_pin_obj_t* write, const mcu_pin_obj_t* read, const mcu_pin_obj_t* reset); +void common_hal_displayio_parallelbus_construct(displayio_parallelbus_obj_t *self, + const mcu_pin_obj_t *data0, const mcu_pin_obj_t *command, const mcu_pin_obj_t *chip_select, + const mcu_pin_obj_t *write, const mcu_pin_obj_t *read, const mcu_pin_obj_t *reset); -void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t* self); +void common_hal_displayio_parallelbus_deinit(displayio_parallelbus_obj_t *self); bool common_hal_displayio_parallelbus_reset(mp_obj_t self); bool common_hal_displayio_parallelbus_bus_free(mp_obj_t self); diff --git a/shared-bindings/displayio/Shape.c b/shared-bindings/displayio/Shape.c index 4d737ecae2..0126df8858 100644 --- a/shared-bindings/displayio/Shape.c +++ b/shared-bindings/displayio/Shape.c @@ -84,7 +84,7 @@ STATIC mp_obj_t displayio_shape_make_new(const mp_obj_type_t *type, size_t n_arg //| ... //| STATIC mp_obj_t displayio_shape_obj_set_boundary(size_t n_args, const mp_obj_t *args) { - (void) n_args; + (void)n_args; displayio_shape_t *self = MP_OBJ_TO_PTR(args[0]); mp_int_t y; if (!mp_obj_get_int_maybe(args[1], &y)) { @@ -113,5 +113,5 @@ const mp_obj_type_t displayio_shape_type = { { &mp_type_type }, .name = MP_QSTR_Shape, .make_new = displayio_shape_make_new, - .locals_dict = (mp_obj_dict_t*)&displayio_shape_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_shape_locals_dict, }; diff --git a/shared-bindings/displayio/Shape.h b/shared-bindings/displayio/Shape.h index d08a387822..961b57c674 100644 --- a/shared-bindings/displayio/Shape.h +++ b/shared-bindings/displayio/Shape.h @@ -35,7 +35,7 @@ void common_hal_displayio_shape_construct(displayio_shape_t *self, uint32_t widt uint32_t height, bool mirror_x, bool mirror_y); void common_hal_displayio_shape_set_boundary(displayio_shape_t *self, uint16_t y, uint16_t start_x, - uint16_t end_x); + uint16_t end_x); uint32_t common_hal_displayio_shape_get_pixel(void *shape, int16_t x, int16_t y); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_SHAPE_H diff --git a/shared-bindings/displayio/TileGrid.c b/shared-bindings/displayio/TileGrid.c index 73a08f5567..dee0d7a686 100644 --- a/shared-bindings/displayio/TileGrid.c +++ b/shared-bindings/displayio/TileGrid.c @@ -87,16 +87,16 @@ STATIC mp_obj_t displayio_tilegrid_make_new(const mp_obj_type_t *type, size_t n_ uint16_t bitmap_height; mp_obj_t native = mp_instance_cast_to_native_base(bitmap, &displayio_shape_type); if (native != MP_OBJ_NULL) { - displayio_shape_t* bmp = MP_OBJ_TO_PTR(native); + displayio_shape_t *bmp = MP_OBJ_TO_PTR(native); bitmap_width = bmp->width; bitmap_height = bmp->height; } else if (MP_OBJ_IS_TYPE(bitmap, &displayio_bitmap_type)) { - displayio_bitmap_t* bmp = MP_OBJ_TO_PTR(bitmap); + displayio_bitmap_t *bmp = MP_OBJ_TO_PTR(bitmap); native = bitmap; bitmap_width = bmp->width; bitmap_height = bmp->height; } else if (MP_OBJ_IS_TYPE(bitmap, &displayio_ondiskbitmap_type)) { - displayio_ondiskbitmap_t* bmp = MP_OBJ_TO_PTR(bitmap); + displayio_ondiskbitmap_t *bmp = MP_OBJ_TO_PTR(bitmap); native = bitmap; bitmap_width = bmp->width; bitmap_height = bmp->height; @@ -136,7 +136,7 @@ STATIC mp_obj_t displayio_tilegrid_make_new(const mp_obj_type_t *type, size_t n_ } // Helper to ensure we have the native super class instead of a subclass. -static displayio_tilegrid_t* native_tilegrid(mp_obj_t tilegrid_obj) { +static displayio_tilegrid_t *native_tilegrid(mp_obj_t tilegrid_obj) { mp_obj_t native_tilegrid = mp_instance_cast_to_native_base(tilegrid_obj, &displayio_tilegrid_type); mp_obj_assert_native_inited(native_tilegrid); return MP_OBJ_TO_PTR(native_tilegrid); @@ -354,13 +354,13 @@ STATIC mp_obj_t tilegrid_subscr(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t v x = i % width; y = i / width; } else { - mp_obj_t* items; + mp_obj_t *items; mp_obj_get_array_fixed_n(index_obj, 2, &items); x = mp_obj_get_int(items[0]); y = mp_obj_get_int(items[1]); } if (x >= common_hal_displayio_tilegrid_get_width(self) || - y >= common_hal_displayio_tilegrid_get_height(self)) { + y >= common_hal_displayio_tilegrid_get_height(self)) { mp_raise_IndexError(translate("Tile index out of bounds")); } @@ -397,5 +397,5 @@ const mp_obj_type_t displayio_tilegrid_type = { .name = MP_QSTR_TileGrid, .make_new = displayio_tilegrid_make_new, .subscr = tilegrid_subscr, - .locals_dict = (mp_obj_dict_t*)&displayio_tilegrid_locals_dict, + .locals_dict = (mp_obj_dict_t *)&displayio_tilegrid_locals_dict, }; diff --git a/shared-bindings/displayio/TileGrid.h b/shared-bindings/displayio/TileGrid.h index 0ee1c78836..7c8d8a605e 100644 --- a/shared-bindings/displayio/TileGrid.h +++ b/shared-bindings/displayio/TileGrid.h @@ -32,12 +32,12 @@ extern const mp_obj_type_t displayio_tilegrid_type; void common_hal_displayio_tilegrid_construct(displayio_tilegrid_t *self, mp_obj_t bitmap, - uint16_t bitmap_width_in_tiles, uint16_t bitmap_height_in_tiles, - mp_obj_t pixel_shader, uint16_t width, uint16_t height, - uint16_t tile_width, uint16_t tile_height, uint16_t x, uint16_t y, uint8_t default_tile); + uint16_t bitmap_width_in_tiles, uint16_t bitmap_height_in_tiles, + mp_obj_t pixel_shader, uint16_t width, uint16_t height, + uint16_t tile_width, uint16_t tile_height, uint16_t x, uint16_t y, uint8_t default_tile); -bool common_hal_displayio_tilegrid_get_hidden(displayio_tilegrid_t* self); -void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t* self, bool hidden); +bool common_hal_displayio_tilegrid_get_hidden(displayio_tilegrid_t *self); +void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t *self, bool hidden); mp_int_t common_hal_displayio_tilegrid_get_x(displayio_tilegrid_t *self); void common_hal_displayio_tilegrid_set_x(displayio_tilegrid_t *self, mp_int_t x); mp_int_t common_hal_displayio_tilegrid_get_y(displayio_tilegrid_t *self); diff --git a/shared-bindings/displayio/__init__.c b/shared-bindings/displayio/__init__.c index 16d068e2e5..bca4289b0e 100644 --- a/shared-bindings/displayio/__init__.c +++ b/shared-bindings/displayio/__init__.c @@ -88,5 +88,5 @@ STATIC MP_DEFINE_CONST_DICT(displayio_module_globals, displayio_module_globals_t const mp_obj_module_t displayio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&displayio_module_globals, + .globals = (mp_obj_dict_t *)&displayio_module_globals, }; diff --git a/shared-bindings/dualbank/__init__.c b/shared-bindings/dualbank/__init__.c index 8021ab18b9..3b267a56fa 100644 --- a/shared-bindings/dualbank/__init__.c +++ b/shared-bindings/dualbank/__init__.c @@ -111,5 +111,5 @@ STATIC MP_DEFINE_CONST_DICT(dualbank_module_globals, dualbank_module_globals_tab const mp_obj_module_t dualbank_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&dualbank_module_globals, + .globals = (mp_obj_dict_t *)&dualbank_module_globals, }; diff --git a/shared-bindings/fontio/BuiltinFont.c b/shared-bindings/fontio/BuiltinFont.c index 8ae2356bbf..29b124dc58 100644 --- a/shared-bindings/fontio/BuiltinFont.c +++ b/shared-bindings/fontio/BuiltinFont.c @@ -101,5 +101,5 @@ STATIC MP_DEFINE_CONST_DICT(fontio_builtinfont_locals_dict, fontio_builtinfont_l const mp_obj_type_t fontio_builtinfont_type = { { &mp_type_type }, .name = MP_QSTR_BuiltinFont, - .locals_dict = (mp_obj_dict_t*)&fontio_builtinfont_locals_dict, + .locals_dict = (mp_obj_dict_t *)&fontio_builtinfont_locals_dict, }; diff --git a/shared-bindings/fontio/__init__.c b/shared-bindings/fontio/__init__.c index f376f35035..c80d68a879 100644 --- a/shared-bindings/fontio/__init__.c +++ b/shared-bindings/fontio/__init__.c @@ -46,5 +46,5 @@ STATIC MP_DEFINE_CONST_DICT(fontio_module_globals, fontio_module_globals_table); const mp_obj_module_t fontio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&fontio_module_globals, + .globals = (mp_obj_dict_t *)&fontio_module_globals, }; diff --git a/shared-bindings/framebufferio/FramebufferDisplay.c b/shared-bindings/framebufferio/FramebufferDisplay.c index 8d1e2ac9c3..329e2a893f 100644 --- a/shared-bindings/framebufferio/FramebufferDisplay.c +++ b/shared-bindings/framebufferio/FramebufferDisplay.c @@ -62,7 +62,7 @@ STATIC mp_obj_t framebufferio_framebufferdisplay_make_new(const mp_obj_type_t *t { MP_QSTR_rotation, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_auto_refresh, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, }; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -87,7 +87,7 @@ STATIC mp_obj_t framebufferio_framebufferdisplay_make_new(const mp_obj_type_t *t } // Helper to ensure we have the native super class instead of a subclass. -static framebufferio_framebufferdisplay_obj_t* native_display(mp_obj_t display_obj) { +static framebufferio_framebufferdisplay_obj_t *native_display(mp_obj_t display_obj) { mp_obj_t native_display = mp_instance_cast_to_native_base(display_obj, &framebufferio_framebufferdisplay_type); mp_obj_assert_native_inited(native_display); return MP_OBJ_TO_PTR(native_display); @@ -102,7 +102,7 @@ static framebufferio_framebufferdisplay_obj_t* native_display(mp_obj_t display_o //| STATIC mp_obj_t framebufferio_framebufferdisplay_obj_show(mp_obj_t self_in, mp_obj_t group_in) { framebufferio_framebufferdisplay_obj_t *self = native_display(self_in); - displayio_group_t* group = NULL; + displayio_group_t *group = NULL; if (group_in != mp_const_none) { group = MP_OBJ_TO_PTR(native_group(group_in)); } @@ -339,40 +339,40 @@ STATIC mp_obj_t framebufferio_framebufferdisplay_obj_fill_row(size_t n_args, con mp_get_buffer_raise(result, &bufinfo, MP_BUFFER_WRITE); if (bufinfo.typecode != BYTEARRAY_TYPECODE) { - mp_raise_ValueError(translate("Buffer is not a bytearray.")); + mp_raise_ValueError(translate("Buffer is not a bytearray.")); } if (self->core.colorspace.depth != 16) { - mp_raise_ValueError(translate("Display must have a 16 bit colorspace.")); + mp_raise_ValueError(translate("Display must have a 16 bit colorspace.")); } displayio_area_t area = { - .x1 = 0, - .y1 = y, - .x2 = self->core.width, - .y2 = y + 1 + .x1 = 0, + .y1 = y, + .x2 = self->core.width, + .y2 = y + 1 }; uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth; uint16_t buffer_size = self->core.width / pixels_per_word; uint16_t pixels_per_buffer = displayio_area_size(&area); if (pixels_per_buffer % pixels_per_word) { - buffer_size += 1; + buffer_size += 1; } uint32_t *result_buffer = bufinfo.buf; size_t result_buffer_size = bufinfo.len; if (result_buffer_size >= (buffer_size * 4)) { - volatile uint32_t mask_length = (pixels_per_buffer / 32) + 1; - uint32_t mask[mask_length]; + volatile uint32_t mask_length = (pixels_per_buffer / 32) + 1; + uint32_t mask[mask_length]; - for (uint16_t k = 0; k < mask_length; k++) { - mask[k] = 0x00000000; - } + for (uint16_t k = 0; k < mask_length; k++) { + mask[k] = 0x00000000; + } - displayio_display_core_fill_area(&self->core, &area, mask, result_buffer); - return result; + displayio_display_core_fill_area(&self->core, &area, mask, result_buffer); + return result; } else { - mp_raise_ValueError(translate("Buffer is too small")); + mp_raise_ValueError(translate("Buffer is too small")); } } MP_DEFINE_CONST_FUN_OBJ_KW(framebufferio_framebufferdisplay_fill_row_obj, 1, framebufferio_framebufferdisplay_obj_fill_row); @@ -398,5 +398,5 @@ const mp_obj_type_t framebufferio_framebufferdisplay_type = { { &mp_type_type }, .name = MP_QSTR_FramebufferDisplay, .make_new = framebufferio_framebufferdisplay_make_new, - .locals_dict = (mp_obj_dict_t*)&framebufferio_framebufferdisplay_locals_dict, + .locals_dict = (mp_obj_dict_t *)&framebufferio_framebufferdisplay_locals_dict, }; diff --git a/shared-bindings/framebufferio/FramebufferDisplay.h b/shared-bindings/framebufferio/FramebufferDisplay.h index c41e041cea..b482666c26 100644 --- a/shared-bindings/framebufferio/FramebufferDisplay.h +++ b/shared-bindings/framebufferio/FramebufferDisplay.h @@ -39,31 +39,31 @@ extern const mp_obj_type_t framebufferio_framebufferdisplay_type; #define NO_BRIGHTNESS_COMMAND 0x100 -void common_hal_framebufferio_framebufferdisplay_construct(framebufferio_framebufferdisplay_obj_t* self, - mp_obj_t framebuffer, - uint16_t rotation, - bool auto_refresh); +void common_hal_framebufferio_framebufferdisplay_construct(framebufferio_framebufferdisplay_obj_t *self, + mp_obj_t framebuffer, + uint16_t rotation, + bool auto_refresh); -bool common_hal_framebufferio_framebufferdisplay_show(framebufferio_framebufferdisplay_obj_t* self, - displayio_group_t* root_group); +bool common_hal_framebufferio_framebufferdisplay_show(framebufferio_framebufferdisplay_obj_t *self, + displayio_group_t *root_group); -bool common_hal_framebufferio_framebufferdisplay_refresh(framebufferio_framebufferdisplay_obj_t* self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame); +bool common_hal_framebufferio_framebufferdisplay_refresh(framebufferio_framebufferdisplay_obj_t *self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame); -bool common_hal_framebufferio_framebufferdisplay_get_auto_refresh(framebufferio_framebufferdisplay_obj_t* self); -void common_hal_framebufferio_framebufferdisplay_set_auto_refresh(framebufferio_framebufferdisplay_obj_t* self, bool auto_refresh); +bool common_hal_framebufferio_framebufferdisplay_get_auto_refresh(framebufferio_framebufferdisplay_obj_t *self); +void common_hal_framebufferio_framebufferdisplay_set_auto_refresh(framebufferio_framebufferdisplay_obj_t *self, bool auto_refresh); -uint16_t common_hal_framebufferio_framebufferdisplay_get_width(framebufferio_framebufferdisplay_obj_t* self); -uint16_t common_hal_framebufferio_framebufferdisplay_get_height(framebufferio_framebufferdisplay_obj_t* self); -uint16_t common_hal_framebufferio_framebufferdisplay_get_rotation(framebufferio_framebufferdisplay_obj_t* self); -void common_hal_framebufferio_framebufferdisplay_set_rotation(framebufferio_framebufferdisplay_obj_t* self, int rotation); +uint16_t common_hal_framebufferio_framebufferdisplay_get_width(framebufferio_framebufferdisplay_obj_t *self); +uint16_t common_hal_framebufferio_framebufferdisplay_get_height(framebufferio_framebufferdisplay_obj_t *self); +uint16_t common_hal_framebufferio_framebufferdisplay_get_rotation(framebufferio_framebufferdisplay_obj_t *self); +void common_hal_framebufferio_framebufferdisplay_set_rotation(framebufferio_framebufferdisplay_obj_t *self, int rotation); -bool common_hal_framebufferio_framebufferdisplay_get_auto_brightness(framebufferio_framebufferdisplay_obj_t* self); -bool common_hal_framebufferio_framebufferdisplay_set_auto_brightness(framebufferio_framebufferdisplay_obj_t* self, bool auto_brightness); +bool common_hal_framebufferio_framebufferdisplay_get_auto_brightness(framebufferio_framebufferdisplay_obj_t *self); +bool common_hal_framebufferio_framebufferdisplay_set_auto_brightness(framebufferio_framebufferdisplay_obj_t *self, bool auto_brightness); -mp_float_t common_hal_framebufferio_framebufferdisplay_get_brightness(framebufferio_framebufferdisplay_obj_t* self); -bool common_hal_framebufferio_framebufferdisplay_set_brightness(framebufferio_framebufferdisplay_obj_t* self, mp_float_t brightness); +mp_float_t common_hal_framebufferio_framebufferdisplay_get_brightness(framebufferio_framebufferdisplay_obj_t *self); +bool common_hal_framebufferio_framebufferdisplay_set_brightness(framebufferio_framebufferdisplay_obj_t *self, mp_float_t brightness); -mp_obj_t common_hal_framebufferio_framebufferdisplay_framebuffer(framebufferio_framebufferdisplay_obj_t* self); +mp_obj_t common_hal_framebufferio_framebufferdisplay_framebuffer(framebufferio_framebufferdisplay_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_DISPLAYIO_FRAMEBUFFERDISPLAY_H diff --git a/shared-bindings/framebufferio/__init__.c b/shared-bindings/framebufferio/__init__.c index 3e58162bf2..ae0f3f906f 100644 --- a/shared-bindings/framebufferio/__init__.c +++ b/shared-bindings/framebufferio/__init__.c @@ -45,6 +45,6 @@ static const mp_rom_map_elem_t framebufferio_module_globals_table[] = { STATIC MP_DEFINE_CONST_DICT(framebufferio_module_globals, framebufferio_module_globals_table); const mp_obj_module_t framebufferio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&framebufferio_module_globals, + .globals = (mp_obj_dict_t *)&framebufferio_module_globals, }; #endif diff --git a/shared-bindings/frequencyio/FrequencyIn.c b/shared-bindings/frequencyio/FrequencyIn.c index 8b0e2b41c9..6a2ed02796 100644 --- a/shared-bindings/frequencyio/FrequencyIn.c +++ b/shared-bindings/frequencyio/FrequencyIn.c @@ -72,7 +72,7 @@ //| ... //| STATIC mp_obj_t frequencyio_frequencyin_make_new(const mp_obj_type_t *type, size_t n_args, - const mp_obj_t *pos_args, mp_map_t *kw_args) { + const mp_obj_t *pos_args, mp_map_t *kw_args) { mp_arg_check_num(n_args, kw_args, 1, 1, true); frequencyio_frequencyin_obj_t *self = m_new_obj(frequencyio_frequencyin_obj_t); @@ -85,7 +85,7 @@ STATIC mp_obj_t frequencyio_frequencyin_make_new(const mp_obj_type_t *type, size mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - mcu_pin_obj_t* pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); + mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); const uint16_t capture_period = args[ARG_capture_period].u_int; @@ -209,7 +209,7 @@ STATIC mp_obj_t frequencyio_frequencyin_obj_get_value(mp_obj_t self_in) { frequencyio_frequencyin_obj_t *self = MP_OBJ_TO_PTR(self_in); check_for_deinit(self); - //return MP_OBJ_NEW_SMALL_INT(common_hal_frequencyio_frequencyin_get_item(self)); + // return MP_OBJ_NEW_SMALL_INT(common_hal_frequencyio_frequencyin_get_item(self)); return mp_obj_new_int_from_float(common_hal_frequencyio_frequencyin_get_item(self)); } MP_DEFINE_CONST_FUN_OBJ_1(frequencyio_frequencyin_get_value_obj, frequencyio_frequencyin_obj_get_value); @@ -238,5 +238,5 @@ const mp_obj_type_t frequencyio_frequencyin_type = { { &mp_type_type }, .name = MP_QSTR_frequencyin, .make_new = frequencyio_frequencyin_make_new, - .locals_dict = (mp_obj_dict_t*)&frequencyio_frequencyin_locals_dict, + .locals_dict = (mp_obj_dict_t *)&frequencyio_frequencyin_locals_dict, }; diff --git a/shared-bindings/frequencyio/__init__.c b/shared-bindings/frequencyio/__init__.c index 031004d4b4..0ad8bbbe9b 100644 --- a/shared-bindings/frequencyio/__init__.c +++ b/shared-bindings/frequencyio/__init__.c @@ -70,5 +70,5 @@ STATIC MP_DEFINE_CONST_DICT(frequencyio_module_globals, frequencyio_module_globa const mp_obj_module_t frequencyio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&frequencyio_module_globals, + .globals = (mp_obj_dict_t *)&frequencyio_module_globals, }; diff --git a/shared-bindings/gamepad/GamePad.c b/shared-bindings/gamepad/GamePad.c index dca1eb1e89..367f1ccce4 100644 --- a/shared-bindings/gamepad/GamePad.c +++ b/shared-bindings/gamepad/GamePad.c @@ -102,14 +102,14 @@ //| ... //| STATIC mp_obj_t gamepad_make_new(const mp_obj_type_t *type, size_t n_args, - const mp_obj_t *args, mp_map_t *kw_args) { + const mp_obj_t *args, mp_map_t *kw_args) { if (n_args > 8 || n_args == 0) { mp_raise_TypeError(translate("argument num/types mismatch")); } for (size_t i = 0; i < n_args; ++i) { assert_digitalinout(args[i]); } - gamepad_obj_t* gamepad_singleton = MP_STATE_VM(gamepad_singleton); + gamepad_obj_t *gamepad_singleton = MP_STATE_VM(gamepad_singleton); if (!gamepad_singleton || !MP_OBJ_IS_TYPE(MP_OBJ_FROM_PTR(gamepad_singleton), &gamepad_type)) { gamepad_singleton = m_new_ll_obj(gamepad_obj_t); @@ -134,7 +134,7 @@ STATIC mp_obj_t gamepad_make_new(const mp_obj_type_t *type, size_t n_args, //| ... //| STATIC mp_obj_t gamepad_get_pressed(mp_obj_t self_in) { - gamepad_obj_t* gamepad_singleton = MP_STATE_VM(gamepad_singleton); + gamepad_obj_t *gamepad_singleton = MP_STATE_VM(gamepad_singleton); mp_obj_t pressed = MP_OBJ_NEW_SMALL_INT(gamepad_singleton->pressed); gamepad_singleton->pressed = gamepad_singleton->last; return pressed; @@ -162,5 +162,5 @@ const mp_obj_type_t gamepad_type = { { &mp_type_type }, .name = MP_QSTR_GamePad, .make_new = gamepad_make_new, - .locals_dict = (mp_obj_dict_t*)&gamepad_locals_dict, + .locals_dict = (mp_obj_dict_t *)&gamepad_locals_dict, }; diff --git a/shared-bindings/gamepad/__init__.c b/shared-bindings/gamepad/__init__.c index 557777f50b..273f109bf5 100644 --- a/shared-bindings/gamepad/__init__.c +++ b/shared-bindings/gamepad/__init__.c @@ -36,9 +36,9 @@ STATIC const mp_rom_map_elem_t gamepad_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_GamePad), MP_ROM_PTR(&gamepad_type)}, }; STATIC MP_DEFINE_CONST_DICT(gamepad_module_globals, - gamepad_module_globals_table); + gamepad_module_globals_table); const mp_obj_module_t gamepad_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&gamepad_module_globals, + .globals = (mp_obj_dict_t *)&gamepad_module_globals, }; diff --git a/shared-bindings/gamepadshift/GamePadShift.c b/shared-bindings/gamepadshift/GamePadShift.c index f6488bbd75..18f9876b77 100644 --- a/shared-bindings/gamepadshift/GamePadShift.c +++ b/shared-bindings/gamepadshift/GamePadShift.c @@ -51,7 +51,7 @@ //| ... //| STATIC mp_obj_t gamepadshift_make_new(const mp_obj_type_t *type, size_t n_args, - const mp_obj_t *pos_args, mp_map_t *kw_args) { + const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_clock, ARG_data, ARG_latch }; static const mp_arg_t allowed_args[] = { @@ -61,16 +61,16 @@ STATIC mp_obj_t gamepadshift_make_new(const mp_obj_type_t *type, size_t n_args, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), - allowed_args, args); + allowed_args, args); digitalio_digitalinout_obj_t *clock_pin = assert_digitalinout(args[ARG_clock].u_obj); digitalio_digitalinout_obj_t *data_pin = assert_digitalinout(args[ARG_data].u_obj); digitalio_digitalinout_obj_t *latch_pin = assert_digitalinout(args[ARG_latch].u_obj); - gamepadshift_obj_t* gamepad_singleton = MP_STATE_VM(gamepad_singleton); + gamepadshift_obj_t *gamepad_singleton = MP_STATE_VM(gamepad_singleton); if (!gamepad_singleton || !MP_OBJ_IS_TYPE(MP_OBJ_FROM_PTR(gamepad_singleton), - &gamepadshift_type)) { + &gamepadshift_type)) { gamepad_singleton = m_new_ll_obj(gamepadshift_obj_t); gamepad_singleton->base.type = &gamepadshift_type; if (!MP_STATE_VM(gamepad_singleton)) { @@ -93,7 +93,7 @@ STATIC mp_obj_t gamepadshift_make_new(const mp_obj_type_t *type, size_t n_args, //| ... //| STATIC mp_obj_t gamepadshift_get_pressed(mp_obj_t self_in) { - gamepadshift_obj_t* gamepad_singleton = MP_STATE_VM(gamepad_singleton); + gamepadshift_obj_t *gamepad_singleton = MP_STATE_VM(gamepad_singleton); mp_obj_t pressed = MP_OBJ_NEW_SMALL_INT(gamepad_singleton->pressed); gamepad_singleton->pressed = gamepad_singleton->last; return pressed; @@ -120,5 +120,5 @@ const mp_obj_type_t gamepadshift_type = { { &mp_type_type }, .name = MP_QSTR_GamePadShift, .make_new = gamepadshift_make_new, - .locals_dict = (mp_obj_dict_t*)&gamepadshift_locals_dict, + .locals_dict = (mp_obj_dict_t *)&gamepadshift_locals_dict, }; diff --git a/shared-bindings/gamepadshift/GamePadShift.h b/shared-bindings/gamepadshift/GamePadShift.h index 3e8ea9693d..8856e133ac 100644 --- a/shared-bindings/gamepadshift/GamePadShift.h +++ b/shared-bindings/gamepadshift/GamePadShift.h @@ -33,9 +33,9 @@ extern const mp_obj_type_t gamepadshift_type; void common_hal_gamepadshift_gamepadshift_init(gamepadshift_obj_t *gamepadshift, - digitalio_digitalinout_obj_t *clock_pin, - digitalio_digitalinout_obj_t *data_pin, - digitalio_digitalinout_obj_t *latch_pin); + digitalio_digitalinout_obj_t *clock_pin, + digitalio_digitalinout_obj_t *data_pin, + digitalio_digitalinout_obj_t *latch_pin); void common_hal_gamepadshift_gamepadshift_deinit(gamepadshift_obj_t *gamepadshift); diff --git a/shared-bindings/gamepadshift/__init__.c b/shared-bindings/gamepadshift/__init__.c index f171358930..1b25d342a7 100644 --- a/shared-bindings/gamepadshift/__init__.c +++ b/shared-bindings/gamepadshift/__init__.c @@ -40,5 +40,5 @@ STATIC MP_DEFINE_CONST_DICT(gamepadshift_module_globals, gamepadshift_module_glo const mp_obj_module_t gamepadshift_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&gamepadshift_module_globals, + .globals = (mp_obj_dict_t *)&gamepadshift_module_globals, }; diff --git a/shared-bindings/gnss/GNSS.c b/shared-bindings/gnss/GNSS.c index 087c353953..a3563b7fd6 100644 --- a/shared-bindings/gnss/GNSS.c +++ b/shared-bindings/gnss/GNSS.c @@ -198,8 +198,8 @@ STATIC const mp_rom_map_elem_t gnss_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(gnss_locals_dict, gnss_locals_dict_table); const mp_obj_type_t gnss_type = { - { &mp_type_type }, - .name = MP_QSTR_GNSS, - .make_new = gnss_make_new, - .locals_dict = (mp_obj_dict_t*)&gnss_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_GNSS, + .make_new = gnss_make_new, + .locals_dict = (mp_obj_dict_t *)&gnss_locals_dict, }; diff --git a/shared-bindings/gnss/__init__.c b/shared-bindings/gnss/__init__.c index 4b0d312ae6..80901a8c5a 100644 --- a/shared-bindings/gnss/__init__.c +++ b/shared-bindings/gnss/__init__.c @@ -27,5 +27,5 @@ STATIC MP_DEFINE_CONST_DICT(gnss_module_globals, gnss_module_globals_table); const mp_obj_module_t gnss_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&gnss_module_globals, + .globals = (mp_obj_dict_t *)&gnss_module_globals, }; diff --git a/shared-bindings/i2cperipheral/I2CPeripheral.c b/shared-bindings/i2cperipheral/I2CPeripheral.c index b5c268eb5c..9192d61ec5 100644 --- a/shared-bindings/i2cperipheral/I2CPeripheral.c +++ b/shared-bindings/i2cperipheral/I2CPeripheral.c @@ -76,8 +76,8 @@ STATIC mp_obj_t i2cperipheral_i2c_peripheral_make_new(const mp_obj_type_t *type, mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* scl = validate_obj_is_free_pin(args[ARG_scl].u_obj); - const mcu_pin_obj_t* sda = validate_obj_is_free_pin(args[ARG_sda].u_obj); + const mcu_pin_obj_t *scl = validate_obj_is_free_pin(args[ARG_scl].u_obj); + const mcu_pin_obj_t *sda = validate_obj_is_free_pin(args[ARG_sda].u_obj); mp_obj_iter_buf_t iter_buf; mp_obj_t iterable = mp_getiter(args[ARG_addresses].u_obj, &iter_buf); @@ -144,7 +144,7 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(i2cperipheral_i2c_peripheral___exit__ STATIC mp_obj_t i2cperipheral_i2c_peripheral_request(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { mp_check_self(MP_OBJ_IS_TYPE(pos_args[0], &i2cperipheral_i2c_peripheral_type)); i2cperipheral_i2c_peripheral_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); - if(common_hal_i2cperipheral_i2c_peripheral_deinited(self)) { + if (common_hal_i2cperipheral_i2c_peripheral_deinited(self)) { raise_deinited_error(); } enum { ARG_timeout }; @@ -220,10 +220,10 @@ STATIC const mp_rom_map_elem_t i2cperipheral_i2c_peripheral_locals_dict_table[] STATIC MP_DEFINE_CONST_DICT(i2cperipheral_i2c_peripheral_locals_dict, i2cperipheral_i2c_peripheral_locals_dict_table); const mp_obj_type_t i2cperipheral_i2c_peripheral_type = { - { &mp_type_type }, - .name = MP_QSTR_I2CPeripheral, - .make_new = i2cperipheral_i2c_peripheral_make_new, - .locals_dict = (mp_obj_dict_t*)&i2cperipheral_i2c_peripheral_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_I2CPeripheral, + .make_new = i2cperipheral_i2c_peripheral_make_new, + .locals_dict = (mp_obj_dict_t *)&i2cperipheral_i2c_peripheral_locals_dict, }; //| class I2CPeripheralRequest: @@ -429,8 +429,8 @@ STATIC const mp_rom_map_elem_t i2cperipheral_i2c_peripheral_request_locals_dict_ STATIC MP_DEFINE_CONST_DICT(i2cperipheral_i2c_peripheral_request_locals_dict, i2cperipheral_i2c_peripheral_request_locals_dict_table); const mp_obj_type_t i2cperipheral_i2c_peripheral_request_type = { - { &mp_type_type }, - .name = MP_QSTR_I2CPeripheralRequest, - .make_new = i2cperipheral_i2c_peripheral_request_make_new, - .locals_dict = (mp_obj_dict_t*)&i2cperipheral_i2c_peripheral_request_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_I2CPeripheralRequest, + .make_new = i2cperipheral_i2c_peripheral_request_make_new, + .locals_dict = (mp_obj_dict_t *)&i2cperipheral_i2c_peripheral_request_locals_dict, }; diff --git a/shared-bindings/i2cperipheral/I2CPeripheral.h b/shared-bindings/i2cperipheral/I2CPeripheral.h index 3035cfbfe7..d3db1b96c9 100644 --- a/shared-bindings/i2cperipheral/I2CPeripheral.h +++ b/shared-bindings/i2cperipheral/I2CPeripheral.h @@ -45,13 +45,13 @@ extern const mp_obj_type_t i2cperipheral_i2c_peripheral_request_type; extern const mp_obj_type_t i2cperipheral_i2c_peripheral_type; extern void common_hal_i2cperipheral_i2c_peripheral_construct(i2cperipheral_i2c_peripheral_obj_t *self, - const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, - uint8_t *addresses, unsigned int num_addresses, bool smbus); + const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, + uint8_t *addresses, unsigned int num_addresses, bool smbus); extern void common_hal_i2cperipheral_i2c_peripheral_deinit(i2cperipheral_i2c_peripheral_obj_t *self); extern bool common_hal_i2cperipheral_i2c_peripheral_deinited(i2cperipheral_i2c_peripheral_obj_t *self); extern int common_hal_i2cperipheral_i2c_peripheral_is_addressed(i2cperipheral_i2c_peripheral_obj_t *self, - uint8_t *address, bool *is_read, bool *is_restart); + uint8_t *address, bool *is_read, bool *is_restart); extern int common_hal_i2cperipheral_i2c_peripheral_read_byte(i2cperipheral_i2c_peripheral_obj_t *self, uint8_t *data); extern int common_hal_i2cperipheral_i2c_peripheral_write_byte(i2cperipheral_i2c_peripheral_obj_t *self, uint8_t data); extern void common_hal_i2cperipheral_i2c_peripheral_ack(i2cperipheral_i2c_peripheral_obj_t *self, bool ack); diff --git a/shared-bindings/i2cperipheral/__init__.c b/shared-bindings/i2cperipheral/__init__.c index e2cb8509d6..183b8511c0 100644 --- a/shared-bindings/i2cperipheral/__init__.c +++ b/shared-bindings/i2cperipheral/__init__.c @@ -30,7 +30,7 @@ #include "py/runtime.h" #include "shared-bindings/microcontroller/Pin.h" -//#include "shared-bindings/i2cperipheral/__init__.h" +// #include "shared-bindings/i2cperipheral/__init__.h" #include "shared-bindings/i2cperipheral/I2CPeripheral.h" #include "py/runtime.h" @@ -102,5 +102,5 @@ STATIC MP_DEFINE_CONST_DICT(i2cperipheral_module_globals, i2cperipheral_module_g const mp_obj_module_t i2cperipheral_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&i2cperipheral_module_globals, + .globals = (mp_obj_dict_t *)&i2cperipheral_module_globals, }; diff --git a/shared-bindings/ipaddress/IPv4Address.c b/shared-bindings/ipaddress/IPv4Address.c index e027f32d65..62a54560ef 100644 --- a/shared-bindings/ipaddress/IPv4Address.c +++ b/shared-bindings/ipaddress/IPv4Address.c @@ -57,13 +57,13 @@ STATIC mp_obj_t ipaddress_ipv4address_make_new(const mp_obj_type_t *type, size_t const mp_obj_t address = args[ARG_address].u_obj; uint32_t value; - uint8_t* buf = NULL; - if (mp_obj_get_int_maybe(address, (mp_int_t*) &value)) { + uint8_t *buf = NULL; + if (mp_obj_get_int_maybe(address, (mp_int_t *)&value)) { // We're done. - buf = (uint8_t*) value; + buf = (uint8_t *)value; } else if (MP_OBJ_IS_STR(address)) { GET_STR_DATA_LEN(address, str_data, str_len); - if (!ipaddress_parse_ipv4address((const char*) str_data, str_len, &value)) { + if (!ipaddress_parse_ipv4address((const char *)str_data, str_len, &value)) { mp_raise_ValueError(translate("Not a valid IP string")); } } else { @@ -139,7 +139,7 @@ STATIC mp_obj_t ipaddress_ipv4address_binary_op(mp_binary_op_t op, mp_obj_t lhs_ ipaddress_ipv4address_obj_t *rhs = MP_OBJ_TO_PTR(rhs_in); return mp_obj_new_bool( mp_obj_equal(common_hal_ipaddress_ipv4address_get_packed(lhs), - common_hal_ipaddress_ipv4address_get_packed(rhs))); + common_hal_ipaddress_ipv4address_get_packed(rhs))); } else { return mp_const_false; @@ -177,7 +177,7 @@ STATIC void ipaddress_ipv4address_print(const mp_print_t *print, mp_obj_t self_i mp_obj_t address_bytes = common_hal_ipaddress_ipv4address_get_packed(self); mp_get_buffer_raise(address_bytes, &buf_info, MP_BUFFER_READ); - const uint8_t *buf = (uint8_t *) buf_info.buf; + const uint8_t *buf = (uint8_t *)buf_info.buf; mp_printf(print, "%d.%d.%d.%d", buf[0], buf[1], buf[2], buf[3]); } @@ -194,5 +194,5 @@ const mp_obj_type_t ipaddress_ipv4address_type = { .print = ipaddress_ipv4address_print, .unary_op = ipaddress_ipv4address_unary_op, .binary_op = ipaddress_ipv4address_binary_op, - .locals_dict = (mp_obj_dict_t*)&ipaddress_ipv4address_locals_dict + .locals_dict = (mp_obj_dict_t *)&ipaddress_ipv4address_locals_dict }; diff --git a/shared-bindings/ipaddress/IPv4Address.h b/shared-bindings/ipaddress/IPv4Address.h index b45cf3bacb..46a52a0b23 100644 --- a/shared-bindings/ipaddress/IPv4Address.h +++ b/shared-bindings/ipaddress/IPv4Address.h @@ -32,7 +32,7 @@ extern const mp_obj_type_t ipaddress_ipv4address_type; mp_obj_t common_hal_ipaddress_new_ipv4address(uint32_t value); -void common_hal_ipaddress_ipv4address_construct(ipaddress_ipv4address_obj_t* self, uint8_t* buf, size_t len); -mp_obj_t common_hal_ipaddress_ipv4address_get_packed(ipaddress_ipv4address_obj_t* self); +void common_hal_ipaddress_ipv4address_construct(ipaddress_ipv4address_obj_t *self, uint8_t *buf, size_t len); +mp_obj_t common_hal_ipaddress_ipv4address_get_packed(ipaddress_ipv4address_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_IPADDRESS_IPV4ADDRESS_H diff --git a/shared-bindings/ipaddress/__init__.c b/shared-bindings/ipaddress/__init__.c index 7ec2984ef7..f768ec0ba6 100644 --- a/shared-bindings/ipaddress/__init__.c +++ b/shared-bindings/ipaddress/__init__.c @@ -38,7 +38,7 @@ //| -bool ipaddress_parse_ipv4address(const char* str_data, size_t str_len, uint32_t* ip_out) { +bool ipaddress_parse_ipv4address(const char *str_data, size_t str_len, uint32_t *ip_out) { size_t period_count = 0; size_t period_index[4] = {0, 0, 0, str_len}; for (size_t i = 0; i < str_len; i++) { @@ -62,7 +62,7 @@ bool ipaddress_parse_ipv4address(const char* str_data, size_t str_len, uint32_t* nlr_buf_t nlr; mp_obj_t octet; if (nlr_push(&nlr) == 0) { - octet = mp_parse_num_integer((const char*) str_data + last_period, period_index[i] - last_period, 10, NULL); + octet = mp_parse_num_integer((const char *)str_data + last_period, period_index[i] - last_period, 10, NULL); nlr_pop(); } else { return false; @@ -83,11 +83,11 @@ bool ipaddress_parse_ipv4address(const char* str_data, size_t str_len, uint32_t* STATIC mp_obj_t ipaddress_ip_address(mp_obj_t ip_in) { uint32_t value; - if (mp_obj_get_int_maybe(ip_in, (mp_int_t*) &value)) { + if (mp_obj_get_int_maybe(ip_in, (mp_int_t *)&value)) { // We're done. } else if (MP_OBJ_IS_STR(ip_in)) { GET_STR_DATA_LEN(ip_in, str_data, str_len); - if (!ipaddress_parse_ipv4address((const char*) str_data, str_len, &value)) { + if (!ipaddress_parse_ipv4address((const char *)str_data, str_len, &value)) { mp_raise_ValueError(translate("Not a valid IP string")); } } else { @@ -109,5 +109,5 @@ STATIC MP_DEFINE_CONST_DICT(ipaddress_module_globals, ipaddress_module_globals_t const mp_obj_module_t ipaddress_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&ipaddress_module_globals, + .globals = (mp_obj_dict_t *)&ipaddress_module_globals, }; diff --git a/shared-bindings/ipaddress/__init__.h b/shared-bindings/ipaddress/__init__.h index a1c31775f9..7c2e5c1819 100644 --- a/shared-bindings/ipaddress/__init__.h +++ b/shared-bindings/ipaddress/__init__.h @@ -29,7 +29,7 @@ #include "shared-module/ipaddress/__init__.h" -bool ipaddress_parse_ipv4address(const char* ip_str, size_t len, uint32_t* ip_out); +bool ipaddress_parse_ipv4address(const char *ip_str, size_t len, uint32_t *ip_out); mp_obj_t common_hal_ipaddress_new_ipv4address(uint32_t value); diff --git a/shared-bindings/math/__init__.c b/shared-bindings/math/__init__.c index 3883c03c11..f5a8ca9cb3 100644 --- a/shared-bindings/math/__init__.c +++ b/shared-bindings/math/__init__.c @@ -49,30 +49,30 @@ STATIC NORETURN void math_error(void) { } #define MATH_FUN_1(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \ + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_2(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj, mp_obj_t y_obj) { return mp_obj_new_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj), mp_obj_get_float(y_obj))); } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj, mp_obj_t y_obj) { return mp_obj_new_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj), mp_obj_get_float(y_obj))); } \ + STATIC MP_DEFINE_CONST_FUN_OBJ_2(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_1_TO_BOOL(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_bool(c_name(mp_obj_get_float(x_obj))); } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_bool(c_name(mp_obj_get_float(x_obj))); } \ + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_1_TO_INT(py_name, c_name) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { return mp_obj_new_int_from_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { return mp_obj_new_int_from_float(MICROPY_FLOAT_C_FUN(c_name)(mp_obj_get_float(x_obj))); } \ + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #define MATH_FUN_1_ERRCOND(py_name, c_name, error_condition) \ - STATIC mp_obj_t mp_math_ ## py_name(mp_obj_t x_obj) { \ + STATIC mp_obj_t mp_math_##py_name(mp_obj_t x_obj) { \ mp_float_t x = mp_obj_get_float(x_obj); \ if (error_condition) { \ math_error(); \ } \ return mp_obj_new_float(MICROPY_FLOAT_C_FUN(c_name)(x)); \ } \ - STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_## py_name ## _obj, mp_math_ ## py_name); + STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_##py_name##_obj, mp_math_##py_name); #ifdef MP_NEED_LOG2 // 1.442695040888963407354163704 is 1/_M_LN2 @@ -184,7 +184,7 @@ STATIC NORETURN void math_error(void) { //| """Return an integer, being ``x`` rounded towards 0.""" //| ... //| - MATH_FUN_1_ERRCOND(sqrt, sqrt, (x < (mp_float_t)0.0)) +MATH_FUN_1_ERRCOND(sqrt, sqrt, (x < (mp_float_t)0.0)) MATH_FUN_2(pow, pow) @@ -265,7 +265,7 @@ MATH_FUN_2(copysign, copysign) MATH_FUN_1(fabs, fabs) -MATH_FUN_1_TO_INT(floor, floor) //TODO: delegate to x.__floor__() if x is not a float +MATH_FUN_1_TO_INT(floor, floor) // TODO: delegate to x.__floor__() if x is not a float MATH_FUN_2(fmod, fmod) @@ -304,7 +304,7 @@ MATH_FUN_1(gamma, tgamma) //| MATH_FUN_1(lgamma, lgamma) #endif -//TODO: factorial, fsum +// TODO: factorial, fsum // Function that takes a variable number of arguments @@ -322,10 +322,10 @@ STATIC mp_obj_t mp_math_log(size_t n_args, const mp_obj_t *args) { if (base <= (mp_float_t)0.0) { math_error(); // Turn off warning when comparing exactly with integral value 1.0 -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wfloat-equal" + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" } else if (base == (mp_float_t)1.0) { -#pragma GCC diagnostic pop + #pragma GCC diagnostic pop mp_raise_msg(&mp_type_ZeroDivisionError, translate("division by zero")); } return mp_obj_new_float(l / MICROPY_FLOAT_C_FUN(log)(base)); @@ -424,7 +424,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_math_globals, mp_module_math_globals_table const mp_obj_module_t math_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_math_globals, + .globals = (mp_obj_dict_t *)&mp_module_math_globals, }; #endif // MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_MATH diff --git a/shared-bindings/memorymonitor/AllocationAlarm.c b/shared-bindings/memorymonitor/AllocationAlarm.c index 7de8c12874..f7684b51a7 100644 --- a/shared-bindings/memorymonitor/AllocationAlarm.c +++ b/shared-bindings/memorymonitor/AllocationAlarm.c @@ -133,5 +133,5 @@ const mp_obj_type_t memorymonitor_allocationalarm_type = { { &mp_type_type }, .name = MP_QSTR_AllocationAlarm, .make_new = memorymonitor_allocationalarm_make_new, - .locals_dict = (mp_obj_dict_t*)&memorymonitor_allocationalarm_locals_dict, + .locals_dict = (mp_obj_dict_t *)&memorymonitor_allocationalarm_locals_dict, }; diff --git a/shared-bindings/memorymonitor/AllocationAlarm.h b/shared-bindings/memorymonitor/AllocationAlarm.h index 304b9c5a72..0a62971821 100644 --- a/shared-bindings/memorymonitor/AllocationAlarm.h +++ b/shared-bindings/memorymonitor/AllocationAlarm.h @@ -31,9 +31,9 @@ extern const mp_obj_type_t memorymonitor_allocationalarm_type; -void common_hal_memorymonitor_allocationalarm_construct(memorymonitor_allocationalarm_obj_t* self, size_t minimum_block_count); -void common_hal_memorymonitor_allocationalarm_pause(memorymonitor_allocationalarm_obj_t* self); -void common_hal_memorymonitor_allocationalarm_resume(memorymonitor_allocationalarm_obj_t* self); -void common_hal_memorymonitor_allocationalarm_set_ignore(memorymonitor_allocationalarm_obj_t* self, mp_int_t count); +void common_hal_memorymonitor_allocationalarm_construct(memorymonitor_allocationalarm_obj_t *self, size_t minimum_block_count); +void common_hal_memorymonitor_allocationalarm_pause(memorymonitor_allocationalarm_obj_t *self); +void common_hal_memorymonitor_allocationalarm_resume(memorymonitor_allocationalarm_obj_t *self); +void common_hal_memorymonitor_allocationalarm_set_ignore(memorymonitor_allocationalarm_obj_t *self, mp_int_t count); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_MEMORYMONITOR_ALLOCATIONALARM_H diff --git a/shared-bindings/memorymonitor/AllocationSize.c b/shared-bindings/memorymonitor/AllocationSize.c index b35bae3602..ea6a1db3ce 100644 --- a/shared-bindings/memorymonitor/AllocationSize.c +++ b/shared-bindings/memorymonitor/AllocationSize.c @@ -125,9 +125,12 @@ STATIC mp_obj_t memorymonitor_allocationsize_unary_op(mp_unary_op_t op, mp_obj_t memorymonitor_allocationsize_obj_t *self = MP_OBJ_TO_PTR(self_in); uint16_t len = common_hal_memorymonitor_allocationsize_get_len(self); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -179,5 +182,5 @@ const mp_obj_type_t memorymonitor_allocationsize_type = { .subscr = memorymonitor_allocationsize_subscr, .unary_op = memorymonitor_allocationsize_unary_op, .getiter = mp_obj_new_generic_iterator, - .locals_dict = (mp_obj_dict_t*)&memorymonitor_allocationsize_locals_dict, + .locals_dict = (mp_obj_dict_t *)&memorymonitor_allocationsize_locals_dict, }; diff --git a/shared-bindings/memorymonitor/AllocationSize.h b/shared-bindings/memorymonitor/AllocationSize.h index bcd9514bf2..c677c1a5b6 100644 --- a/shared-bindings/memorymonitor/AllocationSize.h +++ b/shared-bindings/memorymonitor/AllocationSize.h @@ -31,12 +31,12 @@ extern const mp_obj_type_t memorymonitor_allocationsize_type; -extern void common_hal_memorymonitor_allocationsize_construct(memorymonitor_allocationsize_obj_t* self); -extern void common_hal_memorymonitor_allocationsize_pause(memorymonitor_allocationsize_obj_t* self); -extern void common_hal_memorymonitor_allocationsize_resume(memorymonitor_allocationsize_obj_t* self); -extern void common_hal_memorymonitor_allocationsize_clear(memorymonitor_allocationsize_obj_t* self); -extern size_t common_hal_memorymonitor_allocationsize_get_bytes_per_block(memorymonitor_allocationsize_obj_t* self); -extern uint16_t common_hal_memorymonitor_allocationsize_get_len(memorymonitor_allocationsize_obj_t* self); -extern uint16_t common_hal_memorymonitor_allocationsize_get_item(memorymonitor_allocationsize_obj_t* self, int16_t index); +extern void common_hal_memorymonitor_allocationsize_construct(memorymonitor_allocationsize_obj_t *self); +extern void common_hal_memorymonitor_allocationsize_pause(memorymonitor_allocationsize_obj_t *self); +extern void common_hal_memorymonitor_allocationsize_resume(memorymonitor_allocationsize_obj_t *self); +extern void common_hal_memorymonitor_allocationsize_clear(memorymonitor_allocationsize_obj_t *self); +extern size_t common_hal_memorymonitor_allocationsize_get_bytes_per_block(memorymonitor_allocationsize_obj_t *self); +extern uint16_t common_hal_memorymonitor_allocationsize_get_len(memorymonitor_allocationsize_obj_t *self); +extern uint16_t common_hal_memorymonitor_allocationsize_get_item(memorymonitor_allocationsize_obj_t *self, int16_t index); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_MEMORYMONITOR_ALLOCATIONSIZE_H diff --git a/shared-bindings/memorymonitor/__init__.c b/shared-bindings/memorymonitor/__init__.c index c101ba5e0d..f6546c25d5 100644 --- a/shared-bindings/memorymonitor/__init__.c +++ b/shared-bindings/memorymonitor/__init__.c @@ -41,7 +41,7 @@ //| ... MP_DEFINE_MEMORYMONITOR_EXCEPTION(AllocationError, Exception) -NORETURN void mp_raise_memorymonitor_AllocationError(const compressed_string_t* fmt, ...) { +NORETURN void mp_raise_memorymonitor_AllocationError(const compressed_string_t *fmt, ...) { va_list argptr; va_start(argptr,fmt); mp_obj_t exception = mp_obj_new_exception_msg_vlist(&mp_type_memorymonitor_AllocationError, fmt, argptr); @@ -72,5 +72,5 @@ void memorymonitor_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_pr const mp_obj_module_t memorymonitor_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&memorymonitor_module_globals, + .globals = (mp_obj_dict_t *)&memorymonitor_module_globals, }; diff --git a/shared-bindings/memorymonitor/__init__.h b/shared-bindings/memorymonitor/__init__.h index 60fcdc3f62..5d9dfddbe2 100644 --- a/shared-bindings/memorymonitor/__init__.h +++ b/shared-bindings/memorymonitor/__init__.h @@ -33,17 +33,17 @@ void memorymonitor_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind); #define MP_DEFINE_MEMORYMONITOR_EXCEPTION(exc_name, base_name) \ -const mp_obj_type_t mp_type_memorymonitor_ ## exc_name = { \ - { &mp_type_type }, \ - .name = MP_QSTR_ ## exc_name, \ - .print = memorymonitor_exception_print, \ - .make_new = mp_obj_exception_make_new, \ - .attr = mp_obj_exception_attr, \ - .parent = &mp_type_ ## base_name, \ -}; + const mp_obj_type_t mp_type_memorymonitor_##exc_name = { \ + { &mp_type_type }, \ + .name = MP_QSTR_##exc_name, \ + .print = memorymonitor_exception_print, \ + .make_new = mp_obj_exception_make_new, \ + .attr = mp_obj_exception_attr, \ + .parent = &mp_type_##base_name, \ + }; extern const mp_obj_type_t mp_type_memorymonitor_AllocationError; -NORETURN void mp_raise_memorymonitor_AllocationError(const compressed_string_t* msg, ...); +NORETURN void mp_raise_memorymonitor_AllocationError(const compressed_string_t *msg, ...); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_MEMORYMONITOR___INIT___H diff --git a/shared-bindings/microcontroller/Pin.c b/shared-bindings/microcontroller/Pin.c index 2a97b54b3d..289d890172 100644 --- a/shared-bindings/microcontroller/Pin.c +++ b/shared-bindings/microcontroller/Pin.c @@ -43,8 +43,8 @@ //| ... //| -static void get_pin_name(const mcu_pin_obj_t *self, qstr* package, qstr* module, qstr* name) { - const mp_map_t* board_map = &board_module_globals.map; +static void get_pin_name(const mcu_pin_obj_t *self, qstr *package, qstr *module, qstr *name) { + const mp_map_t *board_map = &board_module_globals.map; for (uint8_t i = 0; i < board_map->alloc; i++) { if (board_map->table[i].value == self) { *package = 0; @@ -53,7 +53,7 @@ static void get_pin_name(const mcu_pin_obj_t *self, qstr* package, qstr* module, return; } } - const mp_map_t* mcu_map = &mcu_pin_globals.map; + const mp_map_t *mcu_map = &mcu_pin_globals.map; for (uint8_t i = 0; i < mcu_map->alloc; i++) { if (mcu_map->table[i].value == self) { *package = MP_QSTR_microcontroller; @@ -74,7 +74,7 @@ STATIC void mcu_pin_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki if (package) { mp_printf(print, "%q.%q.%q", package, module, name); } else { - mp_printf(print, "%q.%q", module , name); + mp_printf(print, "%q.%q", module, name); } } @@ -112,7 +112,7 @@ void validate_list_is_free_pins(qstr what, mcu_pin_obj_t **pins_out, mp_int_t ma mp_raise_ValueError_varg(translate("At most %d %q may be specified (not %d)"), max_pins, what, len); } *count_out = len; - for (mp_int_t i=0; i 1 + #if CIRCUITPY_PROCESSOR_COUNT > 1 { MP_ROM_QSTR(MP_QSTR_cpus), MP_ROM_PTR(&common_hal_multi_processor_obj) }, -#endif + #endif { MP_ROM_QSTR(MP_QSTR_delay_us), MP_ROM_PTR(&mcu_delay_us_obj) }, { MP_ROM_QSTR(MP_QSTR_disable_interrupts), MP_ROM_PTR(&mcu_disable_interrupts_obj) }, { MP_ROM_QSTR(MP_QSTR_enable_interrupts), MP_ROM_PTR(&mcu_enable_interrupts_obj) }, @@ -191,5 +191,5 @@ STATIC MP_DEFINE_CONST_DICT(mcu_module_globals, mcu_module_globals_table); const mp_obj_module_t microcontroller_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mcu_module_globals, + .globals = (mp_obj_dict_t *)&mcu_module_globals, }; diff --git a/shared-bindings/msgpack/ExtType.c b/shared-bindings/msgpack/ExtType.c index e9ddd32bce..44731c0166 100644 --- a/shared-bindings/msgpack/ExtType.c +++ b/shared-bindings/msgpack/ExtType.c @@ -122,5 +122,5 @@ const mp_obj_type_t mod_msgpack_exttype_type = { { &mp_type_type }, .name = MP_QSTR_ExtType, .make_new = mod_msgpack_exttype_make_new, - .locals_dict = (mp_obj_dict_t*)&mod_msgpack_exttype_locals_dict, + .locals_dict = (mp_obj_dict_t *)&mod_msgpack_exttype_locals_dict, }; diff --git a/shared-bindings/msgpack/__init__.c b/shared-bindings/msgpack/__init__.c index f5c47bb218..0bd1d86e20 100644 --- a/shared-bindings/msgpack/__init__.c +++ b/shared-bindings/msgpack/__init__.c @@ -31,7 +31,7 @@ #include "shared-module/msgpack/__init__.h" #include "shared-bindings/msgpack/ExtType.h" -#define MP_OBJ_IS_METH(o) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t*)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_bound_method)) +#define MP_OBJ_IS_METH(o) (MP_OBJ_IS_OBJ(o) && (((mp_obj_base_t *)MP_OBJ_TO_PTR(o))->type->name == MP_QSTR_bound_method)) //| """Pack object in msgpack format //| @@ -158,5 +158,5 @@ STATIC MP_DEFINE_CONST_DICT(msgpack_module_globals, msgpack_module_globals_table const mp_obj_module_t msgpack_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&msgpack_module_globals, + .globals = (mp_obj_dict_t *)&msgpack_module_globals, }; diff --git a/shared-bindings/multiterminal/__init__.c b/shared-bindings/multiterminal/__init__.c index 689d3d7618..f3f8d1ab6c 100644 --- a/shared-bindings/multiterminal/__init__.c +++ b/shared-bindings/multiterminal/__init__.c @@ -106,5 +106,5 @@ STATIC MP_DEFINE_CONST_DICT(multiterminal_module_globals, multiterminal_module_g const mp_obj_module_t multiterminal_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&multiterminal_module_globals, + .globals = (mp_obj_dict_t *)&multiterminal_module_globals, }; diff --git a/shared-bindings/neopixel_write/__init__.c b/shared-bindings/neopixel_write/__init__.c index a353e34aee..da4f28a137 100644 --- a/shared-bindings/neopixel_write/__init__.c +++ b/shared-bindings/neopixel_write/__init__.c @@ -65,7 +65,7 @@ STATIC mp_obj_t neopixel_write_neopixel_write_(mp_obj_t digitalinout_obj, mp_obj mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf, &bufinfo, MP_BUFFER_READ); // Call platform's neopixel write function with provided buffer and options. - common_hal_neopixel_write(digitalinout, (uint8_t*)bufinfo.buf, bufinfo.len); + common_hal_neopixel_write(digitalinout, (uint8_t *)bufinfo.buf, bufinfo.len); return mp_const_none; } STATIC MP_DEFINE_CONST_FUN_OBJ_2(neopixel_write_neopixel_write_obj, neopixel_write_neopixel_write_); @@ -79,5 +79,5 @@ STATIC MP_DEFINE_CONST_DICT(neopixel_write_module_globals, neopixel_write_module const mp_obj_module_t neopixel_write_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&neopixel_write_module_globals, + .globals = (mp_obj_dict_t *)&neopixel_write_module_globals, }; diff --git a/shared-bindings/neopixel_write/__init__.h b/shared-bindings/neopixel_write/__init__.h index 9799e3413d..89b087ddf8 100644 --- a/shared-bindings/neopixel_write/__init__.h +++ b/shared-bindings/neopixel_write/__init__.h @@ -32,6 +32,6 @@ #include "common-hal/digitalio/DigitalInOut.h" -extern void common_hal_neopixel_write(const digitalio_digitalinout_obj_t* gpio, uint8_t *pixels, uint32_t numBytes); +extern void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *gpio, uint8_t *pixels, uint32_t numBytes); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_NEOPIXEL_WRITE_H diff --git a/shared-bindings/network/__init__.c b/shared-bindings/network/__init__.c index cfcadd98f9..2c7faf182d 100644 --- a/shared-bindings/network/__init__.c +++ b/shared-bindings/network/__init__.c @@ -66,7 +66,7 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_network_globals, mp_module_network_globals const mp_obj_module_t network_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_network_globals, + .globals = (mp_obj_dict_t *)&mp_module_network_globals, }; #endif // CIRCUITPY_NETWORK diff --git a/shared-bindings/nvm/ByteArray.c b/shared-bindings/nvm/ByteArray.c index 1c8a45b203..0a2ef3389f 100644 --- a/shared-bindings/nvm/ByteArray.c +++ b/shared-bindings/nvm/ByteArray.c @@ -61,9 +61,12 @@ STATIC mp_obj_t nvm_bytearray_unary_op(mp_unary_op_t op, mp_obj_t self_in) { nvm_bytearray_obj_t *self = MP_OBJ_TO_PTR(self_in); uint16_t len = common_hal_nvm_bytearray_get_length(self); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -94,7 +97,7 @@ STATIC mp_obj_t nvm_bytearray_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj } else { nvm_bytearray_obj_t *self = MP_OBJ_TO_PTR(self_in); if (0) { -#if MICROPY_PY_BUILTINS_SLICE + #if MICROPY_PY_BUILTINS_SLICE } else if (MP_OBJ_IS_TYPE(index_in, &mp_type_slice)) { mp_bound_slice_t slice; if (!mp_seq_get_fast_slice_indexes(common_hal_nvm_bytearray_get_length(self), index_in, &slice)) { @@ -104,11 +107,11 @@ STATIC mp_obj_t nvm_bytearray_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj #if MICROPY_PY_ARRAY_SLICE_ASSIGN // Assign size_t src_len = slice.stop - slice.start; - uint8_t* src_items; + uint8_t *src_items; if (MP_OBJ_IS_TYPE(value, &mp_type_array) || - MP_OBJ_IS_TYPE(value, &mp_type_bytearray) || - MP_OBJ_IS_TYPE(value, &mp_type_memoryview) || - MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { + MP_OBJ_IS_TYPE(value, &mp_type_bytearray) || + MP_OBJ_IS_TYPE(value, &mp_type_memoryview) || + MP_OBJ_IS_TYPE(value, &mp_type_bytes)) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(value, &bufinfo, MP_BUFFER_READ); if (bufinfo.len != src_len) { @@ -137,11 +140,11 @@ STATIC mp_obj_t nvm_bytearray_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj common_hal_nvm_bytearray_get_bytes(self, slice.start, len, items); return mp_obj_new_bytearray_by_ref(len, items); } -#endif + #endif } else { // Single index rather than slice. size_t index = mp_get_index(self->base.type, common_hal_nvm_bytearray_get_length(self), - index_in, false); + index_in, false); if (value == MP_OBJ_SENTINEL) { // load uint8_t value_out; diff --git a/shared-bindings/nvm/ByteArray.h b/shared-bindings/nvm/ByteArray.h index 9375bcb857..9b74a4a3f3 100644 --- a/shared-bindings/nvm/ByteArray.h +++ b/shared-bindings/nvm/ByteArray.h @@ -34,10 +34,10 @@ extern const mp_obj_type_t nvm_bytearray_type; uint32_t common_hal_nvm_bytearray_get_length(nvm_bytearray_obj_t *self); bool common_hal_nvm_bytearray_set_bytes(nvm_bytearray_obj_t *self, - uint32_t start_index, uint8_t* values, uint32_t len); + uint32_t start_index, uint8_t *values, uint32_t len); // len and values are intentionally swapped to signify values is an output and // also leverage the compiler to validate uses are expected. void common_hal_nvm_bytearray_get_bytes(nvm_bytearray_obj_t *self, - uint32_t start_index, uint32_t len, uint8_t* values); + uint32_t start_index, uint32_t len, uint8_t *values); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_NVM_BYTEARRAY_H diff --git a/shared-bindings/nvm/__init__.c b/shared-bindings/nvm/__init__.c index e9784bd187..dffc4cda89 100644 --- a/shared-bindings/nvm/__init__.c +++ b/shared-bindings/nvm/__init__.c @@ -49,5 +49,5 @@ STATIC MP_DEFINE_CONST_DICT(nvm_module_globals, nvm_module_globals_table); const mp_obj_module_t nvm_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&nvm_module_globals, + .globals = (mp_obj_dict_t *)&nvm_module_globals, }; diff --git a/shared-bindings/os/__init__.c b/shared-bindings/os/__init__.c index 8b9b389111..798f3c361f 100644 --- a/shared-bindings/os/__init__.c +++ b/shared-bindings/os/__init__.c @@ -89,7 +89,7 @@ MP_DEFINE_CONST_FUN_OBJ_0(os_getcwd_obj, os_getcwd); //| ... //| mp_obj_t os_listdir(size_t n_args, const mp_obj_t *args) { - const char* path; + const char *path; if (n_args == 1) { path = mp_obj_str_get_str(args[0]); } else { @@ -207,7 +207,7 @@ MP_DEFINE_CONST_FUN_OBJ_0(os_sync_obj, os_sync); STATIC mp_obj_t os_urandom(mp_obj_t size_in) { mp_int_t size = mp_obj_get_int(size_in); mp_obj_str_t *result = MP_OBJ_TO_PTR(mp_obj_new_bytes_of_zeros(size)); - if (!common_hal_os_urandom((uint8_t*) result->data, size)) { + if (!common_hal_os_urandom((uint8_t *)result->data, size)) { mp_raise_NotImplementedError(translate("No hardware random available")); } return result; @@ -245,5 +245,5 @@ STATIC MP_DEFINE_CONST_DICT(os_module_globals, os_module_globals_table); const mp_obj_module_t os_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&os_module_globals, + .globals = (mp_obj_dict_t *)&os_module_globals, }; diff --git a/shared-bindings/os/__init__.h b/shared-bindings/os/__init__.h index 8394890def..f6f0a25c93 100644 --- a/shared-bindings/os/__init__.h +++ b/shared-bindings/os/__init__.h @@ -35,17 +35,17 @@ extern const mp_rom_obj_tuple_t common_hal_os_uname_info_obj; mp_obj_t common_hal_os_uname(void); -void common_hal_os_chdir(const char* path); +void common_hal_os_chdir(const char *path); mp_obj_t common_hal_os_getcwd(void); -mp_obj_t common_hal_os_listdir(const char* path); -void common_hal_os_mkdir(const char* path); -void common_hal_os_remove(const char* path); -void common_hal_os_rename(const char* old_path, const char* new_path); -void common_hal_os_rmdir(const char* path); -mp_obj_t common_hal_os_stat(const char* path); -mp_obj_t common_hal_os_statvfs(const char* path); +mp_obj_t common_hal_os_listdir(const char *path); +void common_hal_os_mkdir(const char *path); +void common_hal_os_remove(const char *path); +void common_hal_os_rename(const char *old_path, const char *new_path); +void common_hal_os_rmdir(const char *path); +mp_obj_t common_hal_os_stat(const char *path); +mp_obj_t common_hal_os_statvfs(const char *path); // Returns true if data was correctly sourced from a true random number generator. -bool common_hal_os_urandom(uint8_t* buffer, mp_uint_t length); +bool common_hal_os_urandom(uint8_t *buffer, mp_uint_t length); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_OS___INIT___H diff --git a/shared-bindings/ps2io/Ps2.c b/shared-bindings/ps2io/Ps2.c index 07fa5cebb9..dd6ca83fbe 100644 --- a/shared-bindings/ps2io/Ps2.c +++ b/shared-bindings/ps2io/Ps2.c @@ -76,8 +76,8 @@ STATIC mp_obj_t ps2io_ps2_make_new(const mp_obj_type_t *type, size_t n_args, con mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* clkpin = validate_obj_is_free_pin(args[ARG_clkpin].u_obj); - const mcu_pin_obj_t* datapin = validate_obj_is_free_pin(args[ARG_datapin].u_obj); + const mcu_pin_obj_t *clkpin = validate_obj_is_free_pin(args[ARG_clkpin].u_obj); + const mcu_pin_obj_t *datapin = validate_obj_is_free_pin(args[ARG_datapin].u_obj); ps2io_ps2_obj_t *self = m_new_obj(ps2io_ps2_obj_t); self->base.type = &ps2io_ps2_type; @@ -215,9 +215,12 @@ STATIC mp_obj_t ps2_unary_op(mp_unary_op_t op, mp_obj_t self_in) { check_for_deinit(self); uint16_t len = common_hal_ps2io_ps2_get_len(self); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -237,5 +240,5 @@ const mp_obj_type_t ps2io_ps2_type = { .name = MP_QSTR_Ps2, .make_new = ps2io_ps2_make_new, .unary_op = ps2_unary_op, - .locals_dict = (mp_obj_dict_t*)&ps2io_ps2_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ps2io_ps2_locals_dict, }; diff --git a/shared-bindings/ps2io/Ps2.h b/shared-bindings/ps2io/Ps2.h index 523869d55b..da4c6ba2fe 100644 --- a/shared-bindings/ps2io/Ps2.h +++ b/shared-bindings/ps2io/Ps2.h @@ -33,13 +33,13 @@ extern const mp_obj_type_t ps2io_ps2_type; -extern void common_hal_ps2io_ps2_construct(ps2io_ps2_obj_t* self, - const mcu_pin_obj_t* data_pin, const mcu_pin_obj_t* clk_pin); -extern void common_hal_ps2io_ps2_deinit(ps2io_ps2_obj_t* self); -extern bool common_hal_ps2io_ps2_deinited(ps2io_ps2_obj_t* self); -extern uint16_t common_hal_ps2io_ps2_get_len(ps2io_ps2_obj_t* self); -extern int16_t common_hal_ps2io_ps2_popleft(ps2io_ps2_obj_t* self); -extern int16_t common_hal_ps2io_ps2_sendcmd(ps2io_ps2_obj_t* self, uint8_t b); -extern uint16_t common_hal_ps2io_ps2_clear_errors(ps2io_ps2_obj_t* self); +extern void common_hal_ps2io_ps2_construct(ps2io_ps2_obj_t *self, + const mcu_pin_obj_t *data_pin, const mcu_pin_obj_t *clk_pin); +extern void common_hal_ps2io_ps2_deinit(ps2io_ps2_obj_t *self); +extern bool common_hal_ps2io_ps2_deinited(ps2io_ps2_obj_t *self); +extern uint16_t common_hal_ps2io_ps2_get_len(ps2io_ps2_obj_t *self); +extern int16_t common_hal_ps2io_ps2_popleft(ps2io_ps2_obj_t *self); +extern int16_t common_hal_ps2io_ps2_sendcmd(ps2io_ps2_obj_t *self, uint8_t b); +extern uint16_t common_hal_ps2io_ps2_clear_errors(ps2io_ps2_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_PS2IO_PS2_H diff --git a/shared-bindings/ps2io/__init__.c b/shared-bindings/ps2io/__init__.c index 38a70b1a27..a71ffd515f 100644 --- a/shared-bindings/ps2io/__init__.c +++ b/shared-bindings/ps2io/__init__.c @@ -57,5 +57,5 @@ STATIC MP_DEFINE_CONST_DICT(ps2io_module_globals, ps2io_module_globals_table); const mp_obj_module_t ps2io_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&ps2io_module_globals, + .globals = (mp_obj_dict_t *)&ps2io_module_globals, }; diff --git a/shared-bindings/pulseio/PulseIn.c b/shared-bindings/pulseio/PulseIn.c index 3e44a14791..18a5d3f3e5 100644 --- a/shared-bindings/pulseio/PulseIn.c +++ b/shared-bindings/pulseio/PulseIn.c @@ -85,7 +85,7 @@ STATIC mp_obj_t pulseio_pulsein_make_new(const mp_obj_type_t *type, size_t n_arg }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); + const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); pulseio_pulsein_obj_t *self = m_new_obj(pulseio_pulsein_obj_t); self->base.type = &pulseio_pulsein_type; @@ -250,9 +250,12 @@ STATIC mp_obj_t pulsein_unary_op(mp_unary_op_t op, mp_obj_t self_in) { check_for_deinit(self); uint16_t len = common_hal_pulseio_pulsein_get_len(self); switch (op) { - case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len != 0); - case MP_UNARY_OP_LEN: return MP_OBJ_NEW_SMALL_INT(len); - default: return MP_OBJ_NULL; // op not supported + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(len != 0); + case MP_UNARY_OP_LEN: + return MP_OBJ_NEW_SMALL_INT(len); + default: + return MP_OBJ_NULL; // op not supported } } @@ -310,5 +313,5 @@ const mp_obj_type_t pulseio_pulsein_type = { .make_new = pulseio_pulsein_make_new, .subscr = pulsein_subscr, .unary_op = pulsein_unary_op, - .locals_dict = (mp_obj_dict_t*)&pulseio_pulsein_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pulseio_pulsein_locals_dict, }; diff --git a/shared-bindings/pulseio/PulseIn.h b/shared-bindings/pulseio/PulseIn.h index e28a3c2df4..09d01fded7 100644 --- a/shared-bindings/pulseio/PulseIn.h +++ b/shared-bindings/pulseio/PulseIn.h @@ -32,17 +32,17 @@ extern const mp_obj_type_t pulseio_pulsein_type; -extern void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t* self, - const mcu_pin_obj_t* pin, uint16_t maxlen, bool idle_state); -extern void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t* self); -extern bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t* self); -extern void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t* self); -extern void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t* self, uint16_t trigger_duration); -extern void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t* self); -extern uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t* self); -extern uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t* self); -extern bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t* self); -extern uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t* self); -extern uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t* self, int16_t index); +extern void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, + const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state); +extern void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self); +extern bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self); +extern void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self); +extern void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t *self, uint16_t trigger_duration); +extern void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t *self); +extern uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t *self); +extern uint16_t common_hal_pulseio_pulsein_get_maxlen(pulseio_pulsein_obj_t *self); +extern bool common_hal_pulseio_pulsein_get_paused(pulseio_pulsein_obj_t *self); +extern uint16_t common_hal_pulseio_pulsein_get_len(pulseio_pulsein_obj_t *self); +extern uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t *self, int16_t index); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_PULSEIO_PULSEIN_H diff --git a/shared-bindings/pulseio/PulseOut.c b/shared-bindings/pulseio/PulseOut.c index 2b787df4f0..61614889fb 100644 --- a/shared-bindings/pulseio/PulseOut.c +++ b/shared-bindings/pulseio/PulseOut.c @@ -80,11 +80,11 @@ STATIC mp_obj_t pulseio_pulseout_make_new(const mp_obj_type_t *type, size_t n_ar static const mp_arg_t allowed_args[] = { { MP_QSTR_pin, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_frequency, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 38000} }, - { MP_QSTR_duty_cycle, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1<<15} }, + { MP_QSTR_duty_cycle, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1 << 15} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); + const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj); common_hal_pulseio_pulseout_construct(self, NULL, pin, args[ARG_frequency].u_int, args[ARG_frequency].u_int); } return MP_OBJ_FROM_PTR(self); @@ -159,5 +159,5 @@ const mp_obj_type_t pulseio_pulseout_type = { { &mp_type_type }, .name = MP_QSTR_PulseOut, .make_new = pulseio_pulseout_make_new, - .locals_dict = (mp_obj_dict_t*)&pulseio_pulseout_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pulseio_pulseout_locals_dict, }; diff --git a/shared-bindings/pulseio/PulseOut.h b/shared-bindings/pulseio/PulseOut.h index 49dc555fe3..dce58a63e0 100644 --- a/shared-bindings/pulseio/PulseOut.h +++ b/shared-bindings/pulseio/PulseOut.h @@ -33,15 +33,15 @@ extern const mp_obj_type_t pulseio_pulseout_type; -extern void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t* self, - const pwmio_pwmout_obj_t* carrier, - const mcu_pin_obj_t* pin, - uint32_t frequency, - uint16_t duty_cycle); +extern void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, + const pwmio_pwmout_obj_t *carrier, + const mcu_pin_obj_t *pin, + uint32_t frequency, + uint16_t duty_cycle); -extern void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t* self); -extern bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t* self); -extern void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t* self, - uint16_t* pulses, uint16_t len); +extern void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self); +extern bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t *self); +extern void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, + uint16_t *pulses, uint16_t len); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_PULSEIO_PULSEOUT_H diff --git a/shared-bindings/pulseio/__init__.c b/shared-bindings/pulseio/__init__.c index bfe9635f01..44a07fafc6 100644 --- a/shared-bindings/pulseio/__init__.c +++ b/shared-bindings/pulseio/__init__.c @@ -62,5 +62,5 @@ STATIC MP_DEFINE_CONST_DICT(pulseio_module_globals, pulseio_module_globals_table const mp_obj_module_t pulseio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pulseio_module_globals, + .globals = (mp_obj_dict_t *)&pulseio_module_globals, }; diff --git a/shared-bindings/pwmio/PWMOut.c b/shared-bindings/pwmio/PWMOut.c index da07555928..0f31114856 100644 --- a/shared-bindings/pwmio/PWMOut.c +++ b/shared-bindings/pwmio/PWMOut.c @@ -174,8 +174,8 @@ STATIC mp_obj_t pwmio_pwmout_obj_set_duty_cycle(mp_obj_t self_in, mp_obj_t duty_ if (duty < 0 || duty > 0xffff) { mp_raise_ValueError(translate("PWM duty_cycle must be between 0 and 65535 inclusive (16 bit resolution)")); } - common_hal_pwmio_pwmout_set_duty_cycle(self, duty); - return mp_const_none; + common_hal_pwmio_pwmout_set_duty_cycle(self, duty); + return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(pwmio_pwmout_set_duty_cycle_obj, pwmio_pwmout_obj_set_duty_cycle); @@ -211,8 +211,8 @@ STATIC mp_obj_t pwmio_pwmout_obj_set_frequency(mp_obj_t self_in, mp_obj_t freque "PWM frequency not writable when variable_frequency is False on " "construction.")); } - common_hal_pwmio_pwmout_set_frequency(self, mp_obj_get_int(frequency)); - return mp_const_none; + common_hal_pwmio_pwmout_set_frequency(self, mp_obj_get_int(frequency)); + return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(pwmio_pwmout_set_frequency_obj, pwmio_pwmout_obj_set_frequency); @@ -241,5 +241,5 @@ const mp_obj_type_t pwmio_pwmout_type = { { &mp_type_type }, .name = MP_QSTR_PWMOut, .make_new = pwmio_pwmout_make_new, - .locals_dict = (mp_obj_dict_t*)&pwmio_pwmout_locals_dict, + .locals_dict = (mp_obj_dict_t *)&pwmio_pwmout_locals_dict, }; diff --git a/shared-bindings/pwmio/PWMOut.h b/shared-bindings/pwmio/PWMOut.h index de2ebd1cf4..4155ba12d8 100644 --- a/shared-bindings/pwmio/PWMOut.h +++ b/shared-bindings/pwmio/PWMOut.h @@ -40,16 +40,16 @@ typedef enum pwmout_result_t { PWMOUT_ALL_TIMERS_IN_USE } pwmout_result_t; -extern pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t* self, - const mcu_pin_obj_t* pin, uint16_t duty, uint32_t frequency, +extern pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, + const mcu_pin_obj_t *pin, uint16_t duty, uint32_t frequency, bool variable_frequency); -extern void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t* self); -extern bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t* self); -extern void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t* self, uint16_t duty); -extern uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t* self); -extern void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t* self, uint32_t frequency); -extern uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t* self); -extern bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t* self); +extern void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self); +extern bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self); +extern void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty); +extern uint16_t common_hal_pwmio_pwmout_get_duty_cycle(pwmio_pwmout_obj_t *self); +extern void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, uint32_t frequency); +extern uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t *self); +extern bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *self); // This is used by the supervisor to claim PWMOut devices indefinitely. extern void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self); diff --git a/shared-bindings/pwmio/__init__.c b/shared-bindings/pwmio/__init__.c index a513837034..bf4ba31ddd 100644 --- a/shared-bindings/pwmio/__init__.c +++ b/shared-bindings/pwmio/__init__.c @@ -69,5 +69,5 @@ STATIC MP_DEFINE_CONST_DICT(pwmio_module_globals, pwmio_module_globals_table); const mp_obj_module_t pwmio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&pwmio_module_globals, + .globals = (mp_obj_dict_t *)&pwmio_module_globals, }; diff --git a/shared-bindings/random/__init__.c b/shared-bindings/random/__init__.c index 35756eef16..e3ac4cdc69 100644 --- a/shared-bindings/random/__init__.c +++ b/shared-bindings/random/__init__.c @@ -71,7 +71,7 @@ STATIC mp_obj_t random_getrandbits(mp_obj_t num_in) { if (n > 32 || n == 0) { mp_raise_ValueError(NULL); } - return mp_obj_new_int_from_uint(shared_modules_random_getrandbits((uint8_t) n)); + return mp_obj_new_int_from_uint(shared_modules_random_getrandbits((uint8_t)n)); } STATIC MP_DEFINE_CONST_FUN_OBJ_1(random_getrandbits_obj, random_getrandbits); @@ -182,5 +182,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_random_globals, mp_module_random_globals_t const mp_obj_module_t random_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_random_globals, + .globals = (mp_obj_dict_t *)&mp_module_random_globals, }; diff --git a/shared-bindings/rgbmatrix/RGBMatrix.c b/shared-bindings/rgbmatrix/RGBMatrix.c index 30b72dffd6..045cc82b8f 100644 --- a/shared-bindings/rgbmatrix/RGBMatrix.c +++ b/shared-bindings/rgbmatrix/RGBMatrix.c @@ -49,10 +49,10 @@ STATIC uint8_t validate_pin(mp_obj_t obj) { return common_hal_mcu_pin_number(result); } -STATIC void validate_pins(qstr what, uint8_t* pin_nos, mp_int_t max_pins, mp_obj_t seq, uint8_t *count_out) { +STATIC void validate_pins(qstr what, uint8_t *pin_nos, mp_int_t max_pins, mp_obj_t seq, uint8_t *count_out) { mcu_pin_obj_t *pins[max_pins]; validate_list_is_free_pins(what, pins, max_pins, seq, count_out); - for (mp_int_t i=0; i<*count_out; i++) { + for (mp_int_t i = 0; i < *count_out; i++) { pin_nos[i] = common_hal_mcu_pin_number(pins[i]); } } @@ -64,7 +64,7 @@ STATIC void claim_and_never_reset_pin(mp_obj_t pin) { STATIC void claim_and_never_reset_pins(mp_obj_t seq) { mp_int_t len = MP_OBJ_SMALL_INT_VALUE(mp_obj_len(seq)); - for (mp_int_t i=0; i 1.0f) { @@ -315,7 +323,7 @@ const mp_obj_property_t rgbmatrix_rgbmatrix_brightness_obj = { //| ... //| STATIC mp_obj_t rgbmatrix_rgbmatrix_refresh(mp_obj_t self_in) { - rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t*)self_in; + rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t *)self_in; check_for_deinit(self); common_hal_rgbmatrix_rgbmatrix_refresh(self); return mp_const_none; @@ -326,7 +334,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(rgbmatrix_rgbmatrix_refresh_obj, rgbmatrix_rgbmatrix_r //| """The width of the display, in pixels""" //| STATIC mp_obj_t rgbmatrix_rgbmatrix_get_width(mp_obj_t self_in) { - rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t*)self_in; + rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t *)self_in; check_for_deinit(self); return MP_OBJ_NEW_SMALL_INT(common_hal_rgbmatrix_rgbmatrix_get_width(self)); } @@ -342,7 +350,7 @@ const mp_obj_property_t rgbmatrix_rgbmatrix_width_obj = { //| """The height of the display, in pixels""" //| STATIC mp_obj_t rgbmatrix_rgbmatrix_get_height(mp_obj_t self_in) { - rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t*)self_in; + rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t *)self_in; check_for_deinit(self); return MP_OBJ_NEW_SMALL_INT(common_hal_rgbmatrix_rgbmatrix_get_height(self)); } @@ -365,7 +373,7 @@ STATIC const mp_rom_map_elem_t rgbmatrix_rgbmatrix_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(rgbmatrix_rgbmatrix_locals_dict, rgbmatrix_rgbmatrix_locals_dict_table); STATIC void rgbmatrix_rgbmatrix_get_bufinfo(mp_obj_t self_in, mp_buffer_info_t *bufinfo) { - rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t*)self_in; + rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t *)self_in; check_for_deinit(self); *bufinfo = self->bufinfo; @@ -427,7 +435,7 @@ STATIC const framebuffer_p_t rgbmatrix_rgbmatrix_proto = { }; STATIC mp_int_t rgbmatrix_rgbmatrix_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { - rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t*)self_in; + rgbmatrix_rgbmatrix_obj_t *self = (rgbmatrix_rgbmatrix_obj_t *)self_in; // a readonly framebuffer would be unusual but not impossible if ((flags & MP_BUFFER_WRITE) && !(self->bufinfo.typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) { return 1; @@ -442,5 +450,5 @@ const mp_obj_type_t rgbmatrix_RGBMatrix_type = { .buffer_p = { .get_buffer = rgbmatrix_rgbmatrix_get_buffer, }, .make_new = rgbmatrix_rgbmatrix_make_new, .protocol = &rgbmatrix_rgbmatrix_proto, - .locals_dict = (mp_obj_dict_t*)&rgbmatrix_rgbmatrix_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rgbmatrix_rgbmatrix_locals_dict, }; diff --git a/shared-bindings/rgbmatrix/RGBMatrix.h b/shared-bindings/rgbmatrix/RGBMatrix.h index 4eb3c04b27..127f920da1 100644 --- a/shared-bindings/rgbmatrix/RGBMatrix.h +++ b/shared-bindings/rgbmatrix/RGBMatrix.h @@ -31,12 +31,12 @@ extern const mp_obj_type_t rgbmatrix_RGBMatrix_type; -void common_hal_rgbmatrix_rgbmatrix_construct(rgbmatrix_rgbmatrix_obj_t* self, int width, int bit_depth, uint8_t rgb_count, uint8_t* rgb_pins, uint8_t addr_count, uint8_t* addr_pins, uint8_t clock_pin, uint8_t latch_pin, uint8_t oe_pin, bool doublebuffer, mp_obj_t framebuffer, int8_t tile, bool serpentine, void* timer); -void common_hal_rgbmatrix_rgbmatrix_deinit(rgbmatrix_rgbmatrix_obj_t*); -void rgbmatrix_rgbmatrix_collect_ptrs(rgbmatrix_rgbmatrix_obj_t*); -void common_hal_rgbmatrix_rgbmatrix_reconstruct(rgbmatrix_rgbmatrix_obj_t* self, mp_obj_t framebuffer); -void common_hal_rgbmatrix_rgbmatrix_set_paused(rgbmatrix_rgbmatrix_obj_t* self, bool paused); -bool common_hal_rgbmatrix_rgbmatrix_get_paused(rgbmatrix_rgbmatrix_obj_t* self); -void common_hal_rgbmatrix_rgbmatrix_refresh(rgbmatrix_rgbmatrix_obj_t* self); -int common_hal_rgbmatrix_rgbmatrix_get_width(rgbmatrix_rgbmatrix_obj_t* self); -int common_hal_rgbmatrix_rgbmatrix_get_height(rgbmatrix_rgbmatrix_obj_t* self); +void common_hal_rgbmatrix_rgbmatrix_construct(rgbmatrix_rgbmatrix_obj_t *self, int width, int bit_depth, uint8_t rgb_count, uint8_t *rgb_pins, uint8_t addr_count, uint8_t *addr_pins, uint8_t clock_pin, uint8_t latch_pin, uint8_t oe_pin, bool doublebuffer, mp_obj_t framebuffer, int8_t tile, bool serpentine, void *timer); +void common_hal_rgbmatrix_rgbmatrix_deinit(rgbmatrix_rgbmatrix_obj_t *); +void rgbmatrix_rgbmatrix_collect_ptrs(rgbmatrix_rgbmatrix_obj_t *); +void common_hal_rgbmatrix_rgbmatrix_reconstruct(rgbmatrix_rgbmatrix_obj_t *self, mp_obj_t framebuffer); +void common_hal_rgbmatrix_rgbmatrix_set_paused(rgbmatrix_rgbmatrix_obj_t *self, bool paused); +bool common_hal_rgbmatrix_rgbmatrix_get_paused(rgbmatrix_rgbmatrix_obj_t *self); +void common_hal_rgbmatrix_rgbmatrix_refresh(rgbmatrix_rgbmatrix_obj_t *self); +int common_hal_rgbmatrix_rgbmatrix_get_width(rgbmatrix_rgbmatrix_obj_t *self); +int common_hal_rgbmatrix_rgbmatrix_get_height(rgbmatrix_rgbmatrix_obj_t *self); diff --git a/shared-bindings/rgbmatrix/__init__.c b/shared-bindings/rgbmatrix/__init__.c index 7f0576652a..451163dbec 100644 --- a/shared-bindings/rgbmatrix/__init__.c +++ b/shared-bindings/rgbmatrix/__init__.c @@ -43,5 +43,5 @@ STATIC MP_DEFINE_CONST_DICT(rgbmatrix_module_globals, rgbmatrix_module_globals_t const mp_obj_module_t rgbmatrix_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&rgbmatrix_module_globals, + .globals = (mp_obj_dict_t *)&rgbmatrix_module_globals, }; diff --git a/shared-bindings/rotaryio/IncrementalEncoder.c b/shared-bindings/rotaryio/IncrementalEncoder.c index 8b0badbe82..b27e601c26 100644 --- a/shared-bindings/rotaryio/IncrementalEncoder.c +++ b/shared-bindings/rotaryio/IncrementalEncoder.c @@ -69,8 +69,8 @@ STATIC mp_obj_t rotaryio_incrementalencoder_make_new(const mp_obj_type_t *type, mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* pin_a = validate_obj_is_free_pin(args[ARG_pin_a].u_obj); - const mcu_pin_obj_t* pin_b = validate_obj_is_free_pin(args[ARG_pin_b].u_obj); + const mcu_pin_obj_t *pin_a = validate_obj_is_free_pin(args[ARG_pin_a].u_obj); + const mcu_pin_obj_t *pin_b = validate_obj_is_free_pin(args[ARG_pin_b].u_obj); rotaryio_incrementalencoder_obj_t *self = m_new_obj(rotaryio_incrementalencoder_obj_t); self->base.type = &rotaryio_incrementalencoder_type; @@ -157,5 +157,5 @@ const mp_obj_type_t rotaryio_incrementalencoder_type = { { &mp_type_type }, .name = MP_QSTR_IncrementalEncoder, .make_new = rotaryio_incrementalencoder_make_new, - .locals_dict = (mp_obj_dict_t*)&rotaryio_incrementalencoder_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rotaryio_incrementalencoder_locals_dict, }; diff --git a/shared-bindings/rotaryio/IncrementalEncoder.h b/shared-bindings/rotaryio/IncrementalEncoder.h index f70632aefb..51bf7bd9f6 100644 --- a/shared-bindings/rotaryio/IncrementalEncoder.h +++ b/shared-bindings/rotaryio/IncrementalEncoder.h @@ -32,12 +32,12 @@ extern const mp_obj_type_t rotaryio_incrementalencoder_type; -extern void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t* self, - const mcu_pin_obj_t* pin_a, const mcu_pin_obj_t* pin_b); -extern void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t* self); -extern bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t* self); -extern mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t* self); -extern void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t* self, +extern void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self, + const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b); +extern void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t *self); +extern bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t *self); +extern mp_int_t common_hal_rotaryio_incrementalencoder_get_position(rotaryio_incrementalencoder_obj_t *self); +extern void common_hal_rotaryio_incrementalencoder_set_position(rotaryio_incrementalencoder_obj_t *self, mp_int_t new_position); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_ROTARYIO_INCREMENTALENCODER_H diff --git a/shared-bindings/rotaryio/__init__.c b/shared-bindings/rotaryio/__init__.c index cd967baa42..cdc7742bc1 100644 --- a/shared-bindings/rotaryio/__init__.c +++ b/shared-bindings/rotaryio/__init__.c @@ -54,5 +54,5 @@ STATIC MP_DEFINE_CONST_DICT(rotaryio_module_globals, rotaryio_module_globals_tab const mp_obj_module_t rotaryio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&rotaryio_module_globals, + .globals = (mp_obj_dict_t *)&rotaryio_module_globals, }; diff --git a/shared-bindings/rtc/RTC.c b/shared-bindings/rtc/RTC.c index 5e6b00c6e7..3380a2e6a3 100644 --- a/shared-bindings/rtc/RTC.c +++ b/shared-bindings/rtc/RTC.c @@ -135,5 +135,5 @@ const mp_obj_type_t rtc_rtc_type = { { &mp_type_type }, .name = MP_QSTR_RTC, .make_new = rtc_rtc_make_new, - .locals_dict = (mp_obj_dict_t*)&rtc_rtc_locals_dict, + .locals_dict = (mp_obj_dict_t *)&rtc_rtc_locals_dict, }; diff --git a/shared-bindings/rtc/__init__.c b/shared-bindings/rtc/__init__.c index baa9c95e14..1071fa0eab 100644 --- a/shared-bindings/rtc/__init__.c +++ b/shared-bindings/rtc/__init__.c @@ -84,5 +84,5 @@ STATIC MP_DEFINE_CONST_DICT(rtc_module_globals, rtc_module_globals_table); const mp_obj_module_t rtc_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&rtc_module_globals, + .globals = (mp_obj_dict_t *)&rtc_module_globals, }; diff --git a/shared-bindings/sdcardio/SDCard.c b/shared-bindings/sdcardio/SDCard.c index 35d6c14973..612203b56d 100644 --- a/shared-bindings/sdcardio/SDCard.c +++ b/shared-bindings/sdcardio/SDCard.c @@ -84,7 +84,7 @@ STATIC mp_obj_t sdcardio_sdcard_make_new(const mp_obj_type_t *type, size_t n_arg { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = 8000000} }, { MP_QSTR_sdio, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_int = 8000000} }, }; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -108,7 +108,7 @@ STATIC mp_obj_t sdcardio_sdcard_make_new(const mp_obj_type_t *type, size_t n_arg //| :return: The number of 512-byte blocks, as a number""" //| mp_obj_t sdcardio_sdcard_count(mp_obj_t self_in) { - sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t*)self_in; + sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t *)self_in; return mp_obj_new_int_from_ull(common_hal_sdcardio_sdcard_get_blockcount(self)); } MP_DEFINE_CONST_FUN_OBJ_1(sdcardio_sdcard_count_obj, sdcardio_sdcard_count); @@ -119,7 +119,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(sdcardio_sdcard_count_obj, sdcardio_sdcard_count); //| :return: None""" //| mp_obj_t sdcardio_sdcard_deinit(mp_obj_t self_in) { - sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t*)self_in; + sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t *)self_in; common_hal_sdcardio_sdcard_deinit(self); return mp_const_none; } @@ -140,7 +140,7 @@ mp_obj_t sdcardio_sdcard_readblocks(mp_obj_t self_in, mp_obj_t start_block_in, m uint32_t start_block = mp_obj_get_int(start_block_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE); - sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t*)self_in; + sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t *)self_in; int result = common_hal_sdcardio_sdcard_readblocks(self, start_block, &bufinfo); if (result < 0) { mp_raise_OSError(-result); @@ -164,7 +164,7 @@ mp_obj_t sdcardio_sdcard_writeblocks(mp_obj_t self_in, mp_obj_t start_block_in, uint32_t start_block = mp_obj_get_int(start_block_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t*)self_in; + sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t *)self_in; int result = common_hal_sdcardio_sdcard_writeblocks(self, start_block, &bufinfo); if (result < 0) { mp_raise_OSError(-result); @@ -185,5 +185,5 @@ const mp_obj_type_t sdcardio_SDCard_type = { { &mp_type_type }, .name = MP_QSTR_SDCard, .make_new = sdcardio_sdcard_make_new, - .locals_dict = (mp_obj_dict_t*)&sdcardio_sdcard_locals_dict, + .locals_dict = (mp_obj_dict_t *)&sdcardio_sdcard_locals_dict, }; diff --git a/shared-bindings/sdcardio/__init__.c b/shared-bindings/sdcardio/__init__.c index 746aa5588e..e798ad0954 100644 --- a/shared-bindings/sdcardio/__init__.c +++ b/shared-bindings/sdcardio/__init__.c @@ -43,5 +43,5 @@ STATIC MP_DEFINE_CONST_DICT(sdcardio_module_globals, sdcardio_module_globals_tab const mp_obj_module_t sdcardio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&sdcardio_module_globals, + .globals = (mp_obj_dict_t *)&sdcardio_module_globals, }; diff --git a/shared-bindings/sdioio/SDCard.c b/shared-bindings/sdioio/SDCard.c index aba414cd63..468c89821b 100644 --- a/shared-bindings/sdioio/SDCard.c +++ b/shared-bindings/sdioio/SDCard.c @@ -88,13 +88,13 @@ STATIC mp_obj_t sdioio_sdcard_make_new(const mp_obj_type_t *type, size_t n_args, { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ }, { MP_QSTR_frequency, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_INT }, }; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t* clock = validate_obj_is_free_pin(args[ARG_clock].u_obj); - const mcu_pin_obj_t* command = validate_obj_is_free_pin(args[ARG_command].u_obj); + const mcu_pin_obj_t *clock = validate_obj_is_free_pin(args[ARG_clock].u_obj); + const mcu_pin_obj_t *command = validate_obj_is_free_pin(args[ARG_command].u_obj); mcu_pin_obj_t *data_pins[4]; uint8_t num_data; validate_list_is_free_pins(MP_QSTR_data, data_pins, MP_ARRAY_SIZE(data_pins), args[ARG_data].u_obj, &num_data); @@ -126,7 +126,7 @@ STATIC mp_obj_t sdioio_sdcard_configure(size_t n_args, const mp_obj_t *pos_args, sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); check_for_deinit(self); mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); mp_int_t frequency = args[ARG_frequency].u_int; @@ -172,7 +172,7 @@ mp_obj_t sdioio_sdcard_readblocks(mp_obj_t self_in, mp_obj_t start_block_in, mp_ uint32_t start_block = mp_obj_get_int(start_block_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE); - sdioio_sdcard_obj_t *self = (sdioio_sdcard_obj_t*)self_in; + sdioio_sdcard_obj_t *self = (sdioio_sdcard_obj_t *)self_in; int result = common_hal_sdioio_sdcard_readblocks(self, start_block, &bufinfo); if (result < 0) { mp_raise_OSError(-result); @@ -195,7 +195,7 @@ mp_obj_t sdioio_sdcard_writeblocks(mp_obj_t self_in, mp_obj_t start_block_in, mp uint32_t start_block = mp_obj_get_int(start_block_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); - sdioio_sdcard_obj_t *self = (sdioio_sdcard_obj_t*)self_in; + sdioio_sdcard_obj_t *self = (sdioio_sdcard_obj_t *)self_in; int result = common_hal_sdioio_sdcard_writeblocks(self, start_block, &bufinfo); if (result < 0) { mp_raise_OSError(-result); @@ -289,8 +289,8 @@ STATIC const mp_rom_map_elem_t sdioio_sdcard_locals_dict_table[] = { STATIC MP_DEFINE_CONST_DICT(sdioio_sdcard_locals_dict, sdioio_sdcard_locals_dict_table); const mp_obj_type_t sdioio_SDCard_type = { - { &mp_type_type }, - .name = MP_QSTR_SDCard, - .make_new = sdioio_sdcard_make_new, - .locals_dict = (mp_obj_dict_t*)&sdioio_sdcard_locals_dict, + { &mp_type_type }, + .name = MP_QSTR_SDCard, + .make_new = sdioio_sdcard_make_new, + .locals_dict = (mp_obj_dict_t *)&sdioio_sdcard_locals_dict, }; diff --git a/shared-bindings/sdioio/SDCard.h b/shared-bindings/sdioio/SDCard.h index 7f62ee7a65..cd302f4de7 100644 --- a/shared-bindings/sdioio/SDCard.h +++ b/shared-bindings/sdioio/SDCard.h @@ -37,8 +37,8 @@ extern const mp_obj_type_t sdioio_SDCard_type; // Construct an underlying SDIO object. extern void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, - const mcu_pin_obj_t * clock, const mcu_pin_obj_t * command, - uint8_t num_data, mcu_pin_obj_t ** data, uint32_t frequency); + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, + uint8_t num_data, mcu_pin_obj_t **data, uint32_t frequency); extern void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self); extern bool common_hal_sdioio_sdcard_deinited(sdioio_sdcard_obj_t *self); @@ -48,17 +48,17 @@ extern bool common_hal_sdioio_sdcard_configure(sdioio_sdcard_obj_t *self, uint32 extern void common_hal_sdioio_sdcard_unlock(sdioio_sdcard_obj_t *self); // Return actual SDIO bus frequency. -uint32_t common_hal_sdioio_sdcard_get_frequency(sdioio_sdcard_obj_t* self); +uint32_t common_hal_sdioio_sdcard_get_frequency(sdioio_sdcard_obj_t *self); // Return SDIO bus width. -uint8_t common_hal_sdioio_sdcard_get_width(sdioio_sdcard_obj_t* self); +uint8_t common_hal_sdioio_sdcard_get_width(sdioio_sdcard_obj_t *self); // Return number of device blocks -uint32_t common_hal_sdioio_sdcard_get_count(sdioio_sdcard_obj_t* self); +uint32_t common_hal_sdioio_sdcard_get_count(sdioio_sdcard_obj_t *self); // Read or write blocks -int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t* self, uint32_t start_block, mp_buffer_info_t *bufinfo); -int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t* self, uint32_t start_block, mp_buffer_info_t *bufinfo); +int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo); +int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo); // This is used by the supervisor to claim SDIO devices indefinitely. extern void common_hal_sdioio_sdcard_never_reset(sdioio_sdcard_obj_t *self); diff --git a/shared-bindings/sdioio/__init__.c b/shared-bindings/sdioio/__init__.c index b88e5c3a96..98867fc121 100644 --- a/shared-bindings/sdioio/__init__.c +++ b/shared-bindings/sdioio/__init__.c @@ -43,5 +43,5 @@ STATIC MP_DEFINE_CONST_DICT(sdioio_module_globals, sdioio_module_globals_table); const mp_obj_module_t sdioio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&sdioio_module_globals, + .globals = (mp_obj_dict_t *)&sdioio_module_globals, }; diff --git a/shared-bindings/sharpdisplay/SharpMemoryFramebuffer.c b/shared-bindings/sharpdisplay/SharpMemoryFramebuffer.c index e8f4e970a2..713807745b 100644 --- a/shared-bindings/sharpdisplay/SharpMemoryFramebuffer.c +++ b/shared-bindings/sharpdisplay/SharpMemoryFramebuffer.c @@ -43,14 +43,14 @@ STATIC mp_obj_t sharpdisplay_framebuffer_make_new(const mp_obj_type_t *type, siz { MP_QSTR_baudrate, MP_ARG_INT, {.u_int = 2000000} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - MP_STATIC_ASSERT( MP_ARRAY_SIZE(allowed_args) == NUM_ARGS ); + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); mcu_pin_obj_t *chip_select = validate_obj_is_free_pin(args[ARG_chip_select].u_obj); busio_spi_obj_t *spi = validate_obj_is_spi_bus(args[ARG_spi_bus].u_obj); - sharpdisplay_framebuffer_obj_t* self = &allocate_display_bus_or_raise()->sharpdisplay; + sharpdisplay_framebuffer_obj_t *self = &allocate_display_bus_or_raise()->sharpdisplay; self->base.type = &sharpdisplay_framebuffer_type; common_hal_sharpdisplay_framebuffer_construct(self, spi, chip_select, args[ARG_baudrate].u_int, args[ARG_width].u_int, args[ARG_height].u_int); @@ -60,7 +60,7 @@ STATIC mp_obj_t sharpdisplay_framebuffer_make_new(const mp_obj_type_t *type, siz STATIC mp_int_t sharpdisplay_framebuffer_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { - sharpdisplay_framebuffer_obj_t *self = (sharpdisplay_framebuffer_obj_t*)self_in; + sharpdisplay_framebuffer_obj_t *self = (sharpdisplay_framebuffer_obj_t *)self_in; // a readonly framebuffer would be unusual but not impossible if ((flags & MP_BUFFER_WRITE) && !(self->bufinfo.typecode & MP_OBJ_ARRAY_TYPECODE_FLAG_RW)) { return 1; @@ -70,7 +70,7 @@ STATIC mp_int_t sharpdisplay_framebuffer_get_buffer(mp_obj_t self_in, mp_buffer_ } STATIC mp_obj_t sharpdisplay_framebuffer_deinit(mp_obj_t self_in) { - sharpdisplay_framebuffer_obj_t *self = (sharpdisplay_framebuffer_obj_t*)self_in; + sharpdisplay_framebuffer_obj_t *self = (sharpdisplay_framebuffer_obj_t *)self_in; common_hal_sharpdisplay_framebuffer_deinit(self); return mp_const_none; @@ -88,5 +88,5 @@ const mp_obj_type_t sharpdisplay_framebuffer_type = { .buffer_p = { .get_buffer = sharpdisplay_framebuffer_get_buffer, }, .make_new = sharpdisplay_framebuffer_make_new, .protocol = &sharpdisplay_framebuffer_proto, - .locals_dict = (mp_obj_dict_t*)&sharpdisplay_framebuffer_locals_dict, + .locals_dict = (mp_obj_dict_t *)&sharpdisplay_framebuffer_locals_dict, }; diff --git a/shared-bindings/sharpdisplay/__init__.c b/shared-bindings/sharpdisplay/__init__.c index d1f728c61b..d3d3e14919 100644 --- a/shared-bindings/sharpdisplay/__init__.c +++ b/shared-bindings/sharpdisplay/__init__.c @@ -43,5 +43,5 @@ STATIC MP_DEFINE_CONST_DICT(sharpdisplay_module_globals, sharpdisplay_module_glo const mp_obj_module_t sharpdisplay_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&sharpdisplay_module_globals, + .globals = (mp_obj_dict_t *)&sharpdisplay_module_globals, }; diff --git a/shared-bindings/socket/__init__.c b/shared-bindings/socket/__init__.c index 799bf28afa..336b112251 100644 --- a/shared-bindings/socket/__init__.c +++ b/shared-bindings/socket/__init__.c @@ -93,7 +93,7 @@ STATIC void socket_select_nic(mod_network_socket_obj_t *self, const byte *ip) { if (self->nic == MP_OBJ_NULL) { // select NIC based on IP self->nic = network_module_find_nic(ip); - self->nic_type = (mod_network_nic_type_t*)mp_obj_get_type(self->nic); + self->nic_type = (mod_network_nic_type_t *)mp_obj_get_type(self->nic); // call the NIC to open the socket int _errno; @@ -289,7 +289,7 @@ STATIC mp_obj_t socket_recv_into(size_t n_args, const mp_obj_t *args) { } } - mp_int_t ret = _socket_recv_into(self, (byte*)bufinfo.buf, len); + mp_int_t ret = _socket_recv_into(self, (byte *)bufinfo.buf, len); return mp_obj_new_int_from_uint(ret); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socket_recv_into_obj, 2, 3, socket_recv_into); @@ -312,7 +312,7 @@ STATIC mp_obj_t socket_recv(mp_obj_t self_in, mp_obj_t len_in) { mp_int_t len = mp_obj_get_int(len_in); vstr_t vstr; vstr_init_len(&vstr, len); - mp_int_t ret = _socket_recv_into(self, (byte*)vstr.buf, len); + mp_int_t ret = _socket_recv_into(self, (byte *)vstr.buf, len); if (ret == 0) { return mp_const_empty_bytes; } @@ -379,7 +379,7 @@ STATIC mp_obj_t socket_recvfrom(mp_obj_t self_in, mp_obj_t len_in) { byte ip[4]; mp_uint_t port; int _errno; - mp_int_t ret = self->nic_type->recvfrom(self, (byte*)vstr.buf, vstr.len, ip, &port, &_errno); + mp_int_t ret = self->nic_type->recvfrom(self, (byte *)vstr.buf, vstr.len, ip, &port, &_errno); if (ret == -1) { mp_raise_OSError(_errno); } @@ -519,7 +519,7 @@ STATIC const mp_obj_type_t socket_type = { .name = MP_QSTR_socket, .make_new = socket_make_new, .protocol = &socket_stream_p, - .locals_dict = (mp_obj_dict_t*)&socket_locals_dict, + .locals_dict = (mp_obj_dict_t *)&socket_locals_dict, }; //| def getaddrinfo(host: str, port: int) -> Tuple[int, int, int, str, str]: @@ -554,7 +554,7 @@ STATIC mp_obj_t socket_getaddrinfo(mp_obj_t host_in, mp_obj_t port_in) { // find a NIC that can do a name lookup for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) { mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i]; - mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic); + mod_network_nic_type_t *nic_type = (mod_network_nic_type_t *)mp_obj_get_type(nic); if (nic_type->gethostbyname != NULL) { int ret = nic_type->gethostbyname(nic, host, hlen, out_ip); if (ret != 0) { @@ -576,7 +576,7 @@ STATIC mp_obj_t socket_getaddrinfo(mp_obj_t host_in, mp_obj_t port_in) { tuple->items[2] = MP_OBJ_NEW_SMALL_INT(0); tuple->items[3] = MP_OBJ_NEW_QSTR(MP_QSTR_); tuple->items[4] = netutils_format_inet_addr(out_ip, port, NETUTILS_BIG); - return mp_obj_new_list(1, (mp_obj_t*)&tuple); + return mp_obj_new_list(1, (mp_obj_t *)&tuple); } STATIC MP_DEFINE_CONST_FUN_OBJ_2(socket_getaddrinfo_obj, socket_getaddrinfo); @@ -609,5 +609,5 @@ STATIC MP_DEFINE_CONST_DICT(socket_globals, socket_globals_table); const mp_obj_module_t socket_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&socket_globals, + .globals = (mp_obj_dict_t *)&socket_globals, }; diff --git a/shared-bindings/socketpool/Socket.c b/shared-bindings/socketpool/Socket.c index da827798c4..642656bbfa 100644 --- a/shared-bindings/socketpool/Socket.c +++ b/shared-bindings/socketpool/Socket.c @@ -74,7 +74,7 @@ STATIC mp_obj_t socketpool_socket_accept(mp_obj_t self_in) { uint8_t ip[4]; uint32_t port; - socketpool_socket_obj_t * sock = common_hal_socketpool_socket_accept(self, ip, &port); + socketpool_socket_obj_t *sock = common_hal_socketpool_socket_accept(self, ip, &port); mp_obj_t tuple_contents[2]; tuple_contents[0] = MP_OBJ_FROM_PTR(sock); @@ -96,7 +96,7 @@ STATIC mp_obj_t socketpool_socket_bind(mp_obj_t self_in, mp_obj_t addr_in) { mp_obj_get_array_fixed_n(addr_in, 2, &addr_items); size_t hostlen; - const char* host = mp_obj_str_get_data(addr_items[0], &hostlen); + const char *host = mp_obj_str_get_data(addr_items[0], &hostlen); mp_int_t port = mp_obj_get_int(addr_items[1]); if (port < 0) { mp_raise_ValueError(translate("port must be >= 0")); @@ -134,7 +134,7 @@ STATIC mp_obj_t socketpool_socket_connect(mp_obj_t self_in, mp_obj_t addr_in) { mp_obj_get_array_fixed_n(addr_in, 2, &addr_items); size_t hostlen; - const char* host = mp_obj_str_get_data(addr_items[0], &hostlen); + const char *host = mp_obj_str_get_data(addr_items[0], &hostlen); mp_int_t port = mp_obj_get_int(addr_items[1]); if (port < 0) { mp_raise_ValueError(translate("port must be >= 0")); @@ -183,7 +183,7 @@ STATIC mp_obj_t socketpool_socket_recvfrom_into(mp_obj_t self_in, mp_obj_t data_ byte ip[4]; mp_uint_t port; mp_int_t ret = common_hal_socketpool_socket_recvfrom_into(self, - (byte*)bufinfo.buf, bufinfo.len, ip, &port); + (byte *)bufinfo.buf, bufinfo.len, ip, &port); mp_obj_t tuple_contents[2]; tuple_contents[0] = mp_obj_new_int_from_uint(ret); tuple_contents[1] = netutils_format_inet_addr(ip, port, NETUTILS_BIG); @@ -232,7 +232,7 @@ STATIC mp_obj_t socketpool_socket_recv_into(size_t n_args, const mp_obj_t *args) return MP_OBJ_NEW_SMALL_INT(0); } - mp_int_t ret = common_hal_socketpool_socket_recv_into(self, (byte*)bufinfo.buf, len); + mp_int_t ret = common_hal_socketpool_socket_recv_into(self, (byte *)bufinfo.buf, len); return mp_obj_new_int_from_uint(ret); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socketpool_socket_recv_into_obj, 2, 3, socketpool_socket_recv_into); @@ -282,7 +282,7 @@ STATIC mp_obj_t socketpool_socket_sendto(mp_obj_t self_in, mp_obj_t data_in, mp_ mp_obj_get_array_fixed_n(addr_in, 2, &addr_items); size_t hostlen; - const char* host = mp_obj_str_get_data(addr_items[0], &hostlen); + const char *host = mp_obj_str_get_data(addr_items[0], &hostlen); mp_int_t port = mp_obj_get_int(addr_items[1]); if (port < 0) { mp_raise_ValueError(translate("port must be >= 0")); @@ -410,6 +410,6 @@ STATIC MP_DEFINE_CONST_DICT(socketpool_socket_locals_dict, socketpool_socket_loc const mp_obj_type_t socketpool_socket_type = { { &mp_type_type }, .name = MP_QSTR_Socket, - .locals_dict = (mp_obj_dict_t*)&socketpool_socket_locals_dict, + .locals_dict = (mp_obj_dict_t *)&socketpool_socket_locals_dict, .unary_op = socketpool_socket_unary_op, }; diff --git a/shared-bindings/socketpool/Socket.h b/shared-bindings/socketpool/Socket.h index 27173c8b3f..3e757c73ac 100644 --- a/shared-bindings/socketpool/Socket.h +++ b/shared-bindings/socketpool/Socket.h @@ -31,20 +31,20 @@ extern const mp_obj_type_t socketpool_socket_type; -socketpool_socket_obj_t * common_hal_socketpool_socket_accept(socketpool_socket_obj_t* self, uint8_t* ip, uint32_t *port); -bool common_hal_socketpool_socket_bind(socketpool_socket_obj_t* self, const char* host, size_t hostlen, uint32_t port); -void common_hal_socketpool_socket_close(socketpool_socket_obj_t* self); -bool common_hal_socketpool_socket_connect(socketpool_socket_obj_t* self, const char* host, size_t hostlen, uint32_t port); -bool common_hal_socketpool_socket_get_closed(socketpool_socket_obj_t* self); -bool common_hal_socketpool_socket_get_connected(socketpool_socket_obj_t* self); -mp_uint_t common_hal_socketpool_socket_get_timeout(socketpool_socket_obj_t* self); -bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t* self, int backlog); -mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t* self, - uint8_t* buf, uint32_t len, uint8_t* ip, uint32_t *port); -mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t* self, const uint8_t* buf, uint32_t len); -mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t* self, const uint8_t* buf, uint32_t len); -mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t* self, - const char* host, size_t hostlen, uint32_t port, const uint8_t* buf, uint32_t len); -void common_hal_socketpool_socket_settimeout(socketpool_socket_obj_t* self, uint32_t timeout_ms); +socketpool_socket_obj_t *common_hal_socketpool_socket_accept(socketpool_socket_obj_t *self, uint8_t *ip, uint32_t *port); +bool common_hal_socketpool_socket_bind(socketpool_socket_obj_t *self, const char *host, size_t hostlen, uint32_t port); +void common_hal_socketpool_socket_close(socketpool_socket_obj_t *self); +bool common_hal_socketpool_socket_connect(socketpool_socket_obj_t *self, const char *host, size_t hostlen, uint32_t port); +bool common_hal_socketpool_socket_get_closed(socketpool_socket_obj_t *self); +bool common_hal_socketpool_socket_get_connected(socketpool_socket_obj_t *self); +mp_uint_t common_hal_socketpool_socket_get_timeout(socketpool_socket_obj_t *self); +bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t *self, int backlog); +mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t *self, + uint8_t *buf, uint32_t len, uint8_t *ip, uint32_t *port); +mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t *self, const uint8_t *buf, uint32_t len); +mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t *self, const uint8_t *buf, uint32_t len); +mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t *self, + const char *host, size_t hostlen, uint32_t port, const uint8_t *buf, uint32_t len); +void common_hal_socketpool_socket_settimeout(socketpool_socket_obj_t *self, uint32_t timeout_ms); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_SOCKETPOOL_SOCKET_H diff --git a/shared-bindings/socketpool/SocketPool.c b/shared-bindings/socketpool/SocketPool.c index 6ff6d5f98d..038a0d5337 100644 --- a/shared-bindings/socketpool/SocketPool.c +++ b/shared-bindings/socketpool/SocketPool.c @@ -135,7 +135,7 @@ STATIC mp_obj_t socketpool_socketpool_getaddrinfo(size_t n_args, const mp_obj_t sockaddr->items[0] = ip_str; sockaddr->items[1] = MP_OBJ_NEW_SMALL_INT(port); tuple->items[4] = MP_OBJ_FROM_PTR(sockaddr); - return mp_obj_new_list(1, (mp_obj_t*)&tuple); + return mp_obj_new_list(1, (mp_obj_t *)&tuple); } STATIC MP_DEFINE_CONST_FUN_OBJ_KW(socketpool_socketpool_getaddrinfo_obj, 3, socketpool_socketpool_getaddrinfo); @@ -158,5 +158,5 @@ const mp_obj_type_t socketpool_socketpool_type = { { &mp_type_type }, .name = MP_QSTR_SocketPool, .make_new = socketpool_socketpool_make_new, - .locals_dict = (mp_obj_dict_t*)&socketpool_socketpool_locals_dict, + .locals_dict = (mp_obj_dict_t *)&socketpool_socketpool_locals_dict, }; diff --git a/shared-bindings/socketpool/SocketPool.h b/shared-bindings/socketpool/SocketPool.h index b007aad8f4..10a943d38b 100644 --- a/shared-bindings/socketpool/SocketPool.h +++ b/shared-bindings/socketpool/SocketPool.h @@ -44,12 +44,12 @@ typedef enum { SOCKETPOOL_AF_INET6 } socketpool_socketpool_addressfamily_t; -void common_hal_socketpool_socketpool_construct(socketpool_socketpool_obj_t* self, mp_obj_t radio); +void common_hal_socketpool_socketpool_construct(socketpool_socketpool_obj_t *self, mp_obj_t radio); -socketpool_socket_obj_t* common_hal_socketpool_socket(socketpool_socketpool_obj_t* self, +socketpool_socket_obj_t *common_hal_socketpool_socket(socketpool_socketpool_obj_t *self, socketpool_socketpool_addressfamily_t family, socketpool_socketpool_sock_t type); -mp_obj_t common_hal_socketpool_socketpool_gethostbyname(socketpool_socketpool_obj_t* self, - const char* host); +mp_obj_t common_hal_socketpool_socketpool_gethostbyname(socketpool_socketpool_obj_t *self, + const char *host); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_SOCKETPOOL_SOCKETPOOL_H diff --git a/shared-bindings/socketpool/__init__.c b/shared-bindings/socketpool/__init__.c index d3f8ba3028..e6f36261aa 100644 --- a/shared-bindings/socketpool/__init__.c +++ b/shared-bindings/socketpool/__init__.c @@ -49,5 +49,5 @@ STATIC MP_DEFINE_CONST_DICT(socketpool_globals, socketpool_globals_table); const mp_obj_module_t socketpool_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&socketpool_globals, + .globals = (mp_obj_dict_t *)&socketpool_globals, }; diff --git a/shared-bindings/ssl/SSLContext.c b/shared-bindings/ssl/SSLContext.c index 44e9e6bbf8..4a3dafb981 100644 --- a/shared-bindings/ssl/SSLContext.c +++ b/shared-bindings/ssl/SSLContext.c @@ -75,7 +75,7 @@ STATIC mp_obj_t ssl_sslcontext_wrap_socket(size_t n_args, const mp_obj_t *pos_ar mp_raise_ValueError(translate("Server side context cannot have hostname")); } - socketpool_socket_obj_t* sock = args[ARG_sock].u_obj; + socketpool_socket_obj_t *sock = args[ARG_sock].u_obj; return common_hal_ssl_sslcontext_wrap_socket(self, sock, server_side, server_hostname); } @@ -91,5 +91,5 @@ const mp_obj_type_t ssl_sslcontext_type = { { &mp_type_type }, .name = MP_QSTR_SSLContext, .make_new = ssl_sslcontext_make_new, - .locals_dict = (mp_obj_dict_t*)&ssl_sslcontext_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ssl_sslcontext_locals_dict, }; diff --git a/shared-bindings/ssl/SSLContext.h b/shared-bindings/ssl/SSLContext.h index ad4d7e6a8c..1e1986a48d 100644 --- a/shared-bindings/ssl/SSLContext.h +++ b/shared-bindings/ssl/SSLContext.h @@ -34,9 +34,9 @@ extern const mp_obj_type_t ssl_sslcontext_type; -void common_hal_ssl_sslcontext_construct(ssl_sslcontext_obj_t* self); +void common_hal_ssl_sslcontext_construct(ssl_sslcontext_obj_t *self); -ssl_sslsocket_obj_t* common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t* self, - socketpool_socket_obj_t* sock, bool server_side, const char* server_hostname); +ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t *self, + socketpool_socket_obj_t *sock, bool server_side, const char *server_hostname); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_SSL_SSLCONTEXT_H diff --git a/shared-bindings/ssl/SSLSocket.c b/shared-bindings/ssl/SSLSocket.c index 0daa930ef7..1c2de28e95 100644 --- a/shared-bindings/ssl/SSLSocket.c +++ b/shared-bindings/ssl/SSLSocket.c @@ -73,7 +73,7 @@ STATIC mp_obj_t ssl_sslsocket_accept(mp_obj_t self_in) { uint8_t ip[4]; uint32_t port; - ssl_sslsocket_obj_t * sslsock = common_hal_ssl_sslsocket_accept(self, ip, &port); + ssl_sslsocket_obj_t *sslsock = common_hal_ssl_sslsocket_accept(self, ip, &port); mp_obj_t tuple_contents[2]; tuple_contents[0] = MP_OBJ_FROM_PTR(sslsock); @@ -95,7 +95,7 @@ STATIC mp_obj_t ssl_sslsocket_bind(mp_obj_t self_in, mp_obj_t addr_in) { mp_obj_get_array_fixed_n(addr_in, 2, &addr_items); size_t hostlen; - const char* host = mp_obj_str_get_data(addr_items[0], &hostlen); + const char *host = mp_obj_str_get_data(addr_items[0], &hostlen); mp_int_t port = mp_obj_get_int(addr_items[1]); if (port < 0) { mp_raise_ValueError(translate("port must be >= 0")); @@ -133,7 +133,7 @@ STATIC mp_obj_t ssl_sslsocket_connect(mp_obj_t self_in, mp_obj_t addr_in) { mp_obj_get_array_fixed_n(addr_in, 2, &addr_items); size_t hostlen; - const char* host = mp_obj_str_get_data(addr_items[0], &hostlen); + const char *host = mp_obj_str_get_data(addr_items[0], &hostlen); mp_int_t port = mp_obj_get_int(addr_items[1]); if (port < 0) { mp_raise_ValueError(translate("port must be >= 0")); @@ -205,7 +205,7 @@ STATIC mp_obj_t ssl_sslsocket_recv_into(size_t n_args, const mp_obj_t *args) { return MP_OBJ_NEW_SMALL_INT(0); } - mp_int_t ret = common_hal_ssl_sslsocket_recv_into(self, (byte*)bufinfo.buf, len); + mp_int_t ret = common_hal_ssl_sslsocket_recv_into(self, (byte *)bufinfo.buf, len); return mp_obj_new_int_from_uint(ret); } STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(ssl_sslsocket_recv_into_obj, 2, 3, ssl_sslsocket_recv_into); @@ -321,6 +321,6 @@ STATIC MP_DEFINE_CONST_DICT(ssl_sslsocket_locals_dict, ssl_sslsocket_locals_dict const mp_obj_type_t ssl_sslsocket_type = { { &mp_type_type }, .name = MP_QSTR_SSLSocket, - .locals_dict = (mp_obj_dict_t*)&ssl_sslsocket_locals_dict, + .locals_dict = (mp_obj_dict_t *)&ssl_sslsocket_locals_dict, .unary_op = ssl_sslsocket_unary_op, }; diff --git a/shared-bindings/ssl/SSLSocket.h b/shared-bindings/ssl/SSLSocket.h index d117e5dca2..fc6cc8ec14 100644 --- a/shared-bindings/ssl/SSLSocket.h +++ b/shared-bindings/ssl/SSLSocket.h @@ -31,15 +31,15 @@ extern const mp_obj_type_t ssl_sslsocket_type; -ssl_sslsocket_obj_t * common_hal_ssl_sslsocket_accept(ssl_sslsocket_obj_t* self, uint8_t* ip, uint32_t *port); -bool common_hal_ssl_sslsocket_bind(ssl_sslsocket_obj_t* self, const char* host, size_t hostlen, uint32_t port); -void common_hal_ssl_sslsocket_close(ssl_sslsocket_obj_t* self); -bool common_hal_ssl_sslsocket_connect(ssl_sslsocket_obj_t* self, const char* host, size_t hostlen, uint32_t port); -bool common_hal_ssl_sslsocket_get_closed(ssl_sslsocket_obj_t* self); -bool common_hal_ssl_sslsocket_get_connected(ssl_sslsocket_obj_t* self); -bool common_hal_ssl_sslsocket_listen(ssl_sslsocket_obj_t* self, int backlog); -mp_uint_t common_hal_ssl_sslsocket_recv_into(ssl_sslsocket_obj_t* self, const uint8_t* buf, uint32_t len); -mp_uint_t common_hal_ssl_sslsocket_send(ssl_sslsocket_obj_t* self, const uint8_t* buf, uint32_t len); -void common_hal_ssl_sslsocket_settimeout(ssl_sslsocket_obj_t* self, uint32_t timeout_ms); +ssl_sslsocket_obj_t *common_hal_ssl_sslsocket_accept(ssl_sslsocket_obj_t *self, uint8_t *ip, uint32_t *port); +bool common_hal_ssl_sslsocket_bind(ssl_sslsocket_obj_t *self, const char *host, size_t hostlen, uint32_t port); +void common_hal_ssl_sslsocket_close(ssl_sslsocket_obj_t *self); +bool common_hal_ssl_sslsocket_connect(ssl_sslsocket_obj_t *self, const char *host, size_t hostlen, uint32_t port); +bool common_hal_ssl_sslsocket_get_closed(ssl_sslsocket_obj_t *self); +bool common_hal_ssl_sslsocket_get_connected(ssl_sslsocket_obj_t *self); +bool common_hal_ssl_sslsocket_listen(ssl_sslsocket_obj_t *self, int backlog); +mp_uint_t common_hal_ssl_sslsocket_recv_into(ssl_sslsocket_obj_t *self, const uint8_t *buf, uint32_t len); +mp_uint_t common_hal_ssl_sslsocket_send(ssl_sslsocket_obj_t *self, const uint8_t *buf, uint32_t len); +void common_hal_ssl_sslsocket_settimeout(ssl_sslsocket_obj_t *self, uint32_t timeout_ms); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_SSL_SSLSOCKET_H diff --git a/shared-bindings/ssl/__init__.c b/shared-bindings/ssl/__init__.c index 57f4e6f4af..151acfe80c 100644 --- a/shared-bindings/ssl/__init__.c +++ b/shared-bindings/ssl/__init__.c @@ -62,5 +62,5 @@ STATIC MP_DEFINE_CONST_DICT(ssl_globals, ssl_globals_table); const mp_obj_module_t ssl_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&ssl_globals, + .globals = (mp_obj_dict_t *)&ssl_globals, }; diff --git a/shared-bindings/ssl/__init__.h b/shared-bindings/ssl/__init__.h index 5ddada64e6..64f69c3ed9 100644 --- a/shared-bindings/ssl/__init__.h +++ b/shared-bindings/ssl/__init__.h @@ -29,6 +29,6 @@ #include "common-hal/ssl/SSLContext.h" -void common_hal_ssl_create_default_context(ssl_sslcontext_obj_t* self); +void common_hal_ssl_create_default_context(ssl_sslcontext_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_SSL___INIT___H diff --git a/shared-bindings/storage/__init__.c b/shared-bindings/storage/__init__.c index cafaf59869..7b436a4df1 100644 --- a/shared-bindings/storage/__init__.c +++ b/shared-bindings/storage/__init__.c @@ -223,5 +223,5 @@ STATIC MP_DEFINE_CONST_DICT(storage_module_globals, storage_module_globals_table const mp_obj_module_t storage_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&storage_module_globals, + .globals = (mp_obj_dict_t *)&storage_module_globals, }; diff --git a/shared-bindings/storage/__init__.h b/shared-bindings/storage/__init__.h index 7851b9e292..eeb0d3a73b 100644 --- a/shared-bindings/storage/__init__.h +++ b/shared-bindings/storage/__init__.h @@ -30,11 +30,11 @@ #include #include -void common_hal_storage_mount(mp_obj_t vfs_obj, const char* path, bool readonly); -void common_hal_storage_umount_path(const char* path); +void common_hal_storage_mount(mp_obj_t vfs_obj, const char *path, bool readonly); +void common_hal_storage_umount_path(const char *path); void common_hal_storage_umount_object(mp_obj_t vfs_obj); -void common_hal_storage_remount(const char* path, bool readonly, bool disable_concurrent_write_protection); -mp_obj_t common_hal_storage_getmount(const char* path); +void common_hal_storage_remount(const char *path, bool readonly, bool disable_concurrent_write_protection); +mp_obj_t common_hal_storage_getmount(const char *path); void common_hal_storage_erase_filesystem(void); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_STORAGE___INIT___H diff --git a/shared-bindings/struct/__init__.c b/shared-bindings/struct/__init__.c index b886a662e8..56371d3b9a 100644 --- a/shared-bindings/struct/__init__.c +++ b/shared-bindings/struct/__init__.c @@ -72,7 +72,7 @@ STATIC mp_obj_t struct_pack(size_t n_args, const mp_obj_t *args) { mp_int_t size = MP_OBJ_SMALL_INT_VALUE(struct_calcsize(args[0])); vstr_t vstr; vstr_init_len(&vstr, size); - byte *p = (byte*)vstr.buf; + byte *p = (byte *)vstr.buf; memset(p, 0, size); byte *end_p = &p[size]; shared_modules_struct_pack_into(args[0], p, end_p, n_args - 1, &args[1]); @@ -120,7 +120,7 @@ STATIC mp_obj_t struct_unpack(size_t n_args, const mp_obj_t *args) { byte *end_p = &p[bufinfo.len]; // true means check the size must be exactly right. - return MP_OBJ_FROM_PTR(shared_modules_struct_unpack_from(args[0] , p, end_p, true)); + return MP_OBJ_FROM_PTR(shared_modules_struct_unpack_from(args[0], p, end_p, true)); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(struct_unpack_obj, 2, 3, struct_unpack); @@ -177,5 +177,5 @@ STATIC MP_DEFINE_CONST_DICT(mp_module_struct_globals, mp_module_struct_globals_t const mp_obj_module_t struct_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_struct_globals, + .globals = (mp_obj_dict_t *)&mp_module_struct_globals, }; diff --git a/shared-bindings/struct/__init__.h b/shared-bindings/struct/__init__.h index a7e72b11c7..4c7c65da38 100644 --- a/shared-bindings/struct/__init__.h +++ b/shared-bindings/struct/__init__.h @@ -27,8 +27,8 @@ #ifndef MICROPY_INCLUDED_SHARED_BINDINGS_STRUCT___INIT___H #define MICROPY_INCLUDED_SHARED_BINDINGS_STRUCT___INIT___H -void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte* end_p, size_t n_args, const mp_obj_t *args); +void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte *end_p, size_t n_args, const mp_obj_t *args); mp_uint_t shared_modules_struct_calcsize(mp_obj_t fmt_in); -mp_obj_tuple_t * shared_modules_struct_unpack_from(mp_obj_t fmt_in, byte *p, byte *end_p, bool exact_size); +mp_obj_tuple_t *shared_modules_struct_unpack_from(mp_obj_t fmt_in, byte *p, byte *end_p, bool exact_size); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_RANDOM___INIT___H diff --git a/shared-bindings/supervisor/Runtime.c b/shared-bindings/supervisor/Runtime.c old mode 100755 new mode 100644 index 283c8a1d6c..4c004e092b --- a/shared-bindings/supervisor/Runtime.c +++ b/shared-bindings/supervisor/Runtime.c @@ -35,7 +35,7 @@ STATIC supervisor_run_reason_t _run_reason; -//TODO: add USB, REPL to description once they're operational +// TODO: add USB, REPL to description once they're operational //| class Runtime: //| """Current status of runtime objects. //| @@ -55,7 +55,7 @@ STATIC supervisor_run_reason_t _run_reason; //| serial_connected: bool //| """Returns the USB serial communication status (read-only).""" //| -STATIC mp_obj_t supervisor_runtime_get_serial_connected(mp_obj_t self){ +STATIC mp_obj_t supervisor_runtime_get_serial_connected(mp_obj_t self) { return mp_obj_new_bool(common_hal_supervisor_runtime_get_serial_connected()); } MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_serial_connected_obj, supervisor_runtime_get_serial_connected); @@ -72,7 +72,7 @@ const mp_obj_property_t supervisor_runtime_serial_connected_obj = { //| on the USB serial input. Allows for polling to see whether //| to call the built-in input() or wait. (read-only)""" //| -STATIC mp_obj_t supervisor_runtime_get_serial_bytes_available(mp_obj_t self){ +STATIC mp_obj_t supervisor_runtime_get_serial_bytes_available(mp_obj_t self) { return mp_obj_new_bool(common_hal_supervisor_runtime_get_serial_bytes_available()); } MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_serial_bytes_available_obj, supervisor_runtime_get_serial_bytes_available); diff --git a/shared-bindings/supervisor/Runtime.h b/shared-bindings/supervisor/Runtime.h old mode 100755 new mode 100644 index 6874ac744a..3a94a8fd5d --- a/shared-bindings/supervisor/Runtime.h +++ b/shared-bindings/supervisor/Runtime.h @@ -40,8 +40,8 @@ bool common_hal_supervisor_runtime_get_serial_connected(void); bool common_hal_supervisor_runtime_get_serial_bytes_available(void); -//TODO: placeholders for future functions -//bool common_hal_get_supervisor_runtime_repl_active(void); -//bool common_hal_get_supervisor_runtime_usb_enumerated(void); +// TODO: placeholders for future functions +// bool common_hal_get_supervisor_runtime_repl_active(void); +// bool common_hal_get_supervisor_runtime_usb_enumerated(void); #endif // MICROPY_INCLUDED_SHARED_BINDINGS_SUPERVISOR_RUNTIME_H diff --git a/shared-bindings/supervisor/__init__.c b/shared-bindings/supervisor/__init__.c index ad86030478..28ac68d629 100644 --- a/shared-bindings/supervisor/__init__.c +++ b/shared-bindings/supervisor/__init__.c @@ -73,14 +73,14 @@ MP_DEFINE_CONST_FUN_OBJ_0(supervisor_disable_autoreload_obj, supervisor_disable_ //| `set_rgb_status_brightness` is called.""" //| ... //| -STATIC mp_obj_t supervisor_set_rgb_status_brightness(mp_obj_t lvl){ - // This must be int. If cast to uint8_t first, will never raise a ValueError. - int brightness_int = mp_obj_get_int(lvl); - if(brightness_int < 0 || brightness_int > 255){ - mp_raise_ValueError(translate("Brightness must be between 0 and 255")); - } - set_rgb_status_brightness((uint8_t)brightness_int); - return mp_const_none; +STATIC mp_obj_t supervisor_set_rgb_status_brightness(mp_obj_t lvl) { + // This must be int. If cast to uint8_t first, will never raise a ValueError. + int brightness_int = mp_obj_get_int(lvl); + if (brightness_int < 0 || brightness_int > 255) { + mp_raise_ValueError(translate("Brightness must be between 0 and 255")); + } + set_rgb_status_brightness((uint8_t)brightness_int); + return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(supervisor_set_rgb_status_brightness_obj, supervisor_set_rgb_status_brightness); @@ -128,5 +128,5 @@ STATIC MP_DEFINE_CONST_DICT(supervisor_module_globals, supervisor_module_globals const mp_obj_module_t supervisor_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&supervisor_module_globals, + .globals = (mp_obj_dict_t *)&supervisor_module_globals, }; diff --git a/shared-bindings/supervisor/__init__.h b/shared-bindings/supervisor/__init__.h old mode 100755 new mode 100644 index b79bdacca3..a2ad3dd6d4 --- a/shared-bindings/supervisor/__init__.h +++ b/shared-bindings/supervisor/__init__.h @@ -27,7 +27,7 @@ #ifndef MICROPY_INCLUDED_SHARED_BINDINGS_SUPERVISOR___INIT___H #define MICROPY_INCLUDED_SHARED_BINDINGS_SUPERVISOR___INIT___H -//#include "py/mpconfig.h" +// #include "py/mpconfig.h" #include "py/obj.h" #include "common-hal/supervisor/Runtime.h" diff --git a/shared-bindings/terminalio/Terminal.c b/shared-bindings/terminalio/Terminal.c index 3d53e3cce7..b1d3cce653 100644 --- a/shared-bindings/terminalio/Terminal.c +++ b/shared-bindings/terminalio/Terminal.c @@ -123,5 +123,5 @@ const mp_obj_type_t terminalio_terminal_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &terminalio_terminal_stream_p, - .locals_dict = (mp_obj_dict_t*)&terminalio_terminal_locals_dict, + .locals_dict = (mp_obj_dict_t *)&terminalio_terminal_locals_dict, }; diff --git a/shared-bindings/terminalio/Terminal.h b/shared-bindings/terminalio/Terminal.h index 7ae0bf1b03..f884edd6d5 100644 --- a/shared-bindings/terminalio/Terminal.h +++ b/shared-bindings/terminalio/Terminal.h @@ -34,11 +34,11 @@ extern const mp_obj_type_t terminalio_terminal_type; extern void common_hal_terminalio_terminal_construct(terminalio_terminal_obj_t *self, - displayio_tilegrid_t* tilegrid, const fontio_builtinfont_t* font); + displayio_tilegrid_t *tilegrid, const fontio_builtinfont_t *font); // Write characters. len is in characters NOT bytes! extern size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, - const uint8_t *data, size_t len, int *errcode); + const uint8_t *data, size_t len, int *errcode); extern bool common_hal_terminalio_terminal_ready_to_tx(terminalio_terminal_obj_t *self); diff --git a/shared-bindings/terminalio/__init__.c b/shared-bindings/terminalio/__init__.c index 9cd1da5b67..084b76f21e 100644 --- a/shared-bindings/terminalio/__init__.c +++ b/shared-bindings/terminalio/__init__.c @@ -43,7 +43,7 @@ //| FONT: fontio.BuiltinFont //| """The built in font""" //| -STATIC const mp_rom_map_elem_t terminalio_module_globals_table[] = { +STATIC const mp_rom_map_elem_t terminalio_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_terminalio) }, { MP_ROM_QSTR(MP_QSTR_Terminal), MP_OBJ_FROM_PTR(&terminalio_terminal_type) }, { MP_ROM_QSTR(MP_QSTR_FONT), MP_ROM_PTR(&supervisor_terminal_font) }, @@ -54,5 +54,5 @@ STATIC MP_DEFINE_CONST_DICT(terminalio_module_globals, terminalio_module_globals const mp_obj_module_t terminalio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&terminalio_module_globals, + .globals = (mp_obj_dict_t *)&terminalio_module_globals, }; diff --git a/shared-bindings/time/__init__.c b/shared-bindings/time/__init__.c index 2624384afb..0fb12c9b85 100644 --- a/shared-bindings/time/__init__.c +++ b/shared-bindings/time/__init__.c @@ -83,11 +83,11 @@ mp_obj_t struct_time_make_new(const mp_obj_type_t *type, size_t n_args, const mp if (n_args != 1 || (kw_args != NULL && kw_args->used > 0)) { return namedtuple_make_new(type, n_args, args, kw_args); } - if (mp_obj_get_type(args[0])->getiter != mp_obj_tuple_getiter || ((mp_obj_tuple_t*) MP_OBJ_TO_PTR(args[0]))->len != 9) { + if (mp_obj_get_type(args[0])->getiter != mp_obj_tuple_getiter || ((mp_obj_tuple_t *)MP_OBJ_TO_PTR(args[0]))->len != 9) { mp_raise_TypeError(translate("time.struct_time() takes a 9-sequence")); } - mp_obj_tuple_t* tuple = MP_OBJ_TO_PTR(args[0]); + mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(args[0]); return namedtuple_make_new(type, 9, tuple->items, NULL); } @@ -140,7 +140,7 @@ const mp_obj_namedtuple_type_t struct_time_type_obj = { mp_obj_t struct_time_from_tm(timeutils_struct_time_t *tm) { timeutils_struct_time_t tmp; mp_uint_t secs = timeutils_seconds_since_epoch(tm->tm_year, tm->tm_mon, tm->tm_mday, - tm->tm_hour, tm->tm_min, tm->tm_sec); + tm->tm_hour, tm->tm_min, tm->tm_sec); timeutils_seconds_since_epoch_to_struct_time(secs, &tmp); tm->tm_wday = tmp.tm_wday; tm->tm_yday = tmp.tm_yday; @@ -157,7 +157,7 @@ mp_obj_t struct_time_from_tm(timeutils_struct_time_t *tm) { mp_obj_new_int(-1), // tm_isdst is not supported }; - return namedtuple_make_new((const mp_obj_type_t*)&struct_time_type_obj, 9, elems, NULL); + return namedtuple_make_new((const mp_obj_type_t *)&struct_time_type_obj, 9, elems, NULL); }; void struct_time_to_tm(mp_obj_t t, timeutils_struct_time_t *tm) { @@ -208,7 +208,7 @@ STATIC mp_obj_t time_time(void) { timeutils_struct_time_t tm; struct_time_to_tm(rtc_get_time_source_time(), &tm); mp_uint_t secs = timeutils_seconds_since_epoch(tm.tm_year, tm.tm_mon, tm.tm_mday, - tm.tm_hour, tm.tm_min, tm.tm_sec); + tm.tm_hour, tm.tm_min, tm.tm_sec); return mp_obj_new_int_from_uint(secs); } MP_DEFINE_CONST_FUN_OBJ_0(time_time_obj, time_time); @@ -222,7 +222,7 @@ MP_DEFINE_CONST_FUN_OBJ_0(time_time_obj, time_time); //| STATIC mp_obj_t time_monotonic_ns(void) { uint64_t time64 = common_hal_time_monotonic_ns(); - return mp_obj_new_int_from_ll((long long) time64); + return mp_obj_new_int_from_ll((long long)time64); } MP_DEFINE_CONST_FUN_OBJ_0(time_monotonic_ns_obj, time_monotonic_ns); @@ -287,7 +287,7 @@ STATIC mp_obj_t time_mktime(mp_obj_t t) { } mp_uint_t secs = timeutils_mktime(mp_obj_get_int(elem[0]), mp_obj_get_int(elem[1]), mp_obj_get_int(elem[2]), - mp_obj_get_int(elem[3]), mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5])); + mp_obj_get_int(elem[3]), mp_obj_get_int(elem[4]), mp_obj_get_int(elem[5])); return mp_obj_new_int_from_uint(secs); } MP_DEFINE_CONST_FUN_OBJ_1(time_mktime_obj, time_mktime); @@ -322,5 +322,5 @@ STATIC MP_DEFINE_CONST_DICT(time_module_globals, time_module_globals_table); const mp_obj_module_t time_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&time_module_globals, + .globals = (mp_obj_dict_t *)&time_module_globals, }; diff --git a/shared-bindings/touchio/TouchIn.c b/shared-bindings/touchio/TouchIn.c index 904589a48e..8fb36eab45 100644 --- a/shared-bindings/touchio/TouchIn.c +++ b/shared-bindings/touchio/TouchIn.c @@ -59,7 +59,7 @@ //| ... //| STATIC mp_obj_t touchio_touchin_make_new(const mp_obj_type_t *type, - mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { + mp_uint_t n_args, const mp_obj_t *args, mp_map_t *kw_args) { // check number of arguments mp_arg_check_num(n_args, kw_args, 1, 1, false); @@ -70,7 +70,7 @@ STATIC mp_obj_t touchio_touchin_make_new(const mp_obj_type_t *type, self->base.type = &touchio_touchin_type; common_hal_touchio_touchin_construct(self, pin); - return (mp_obj_t) self; + return (mp_obj_t)self; } //| def deinit(self) -> None: @@ -144,7 +144,7 @@ const mp_obj_property_t touchio_touchin_raw_value_obj = { .proxy = {(mp_obj_t)&touchio_touchin_get_raw_value_obj, (mp_obj_t)&mp_const_none_obj, (mp_obj_t)&mp_const_none_obj}, - }; +}; //| threshold: Optional[int] diff --git a/shared-bindings/touchio/TouchIn.h b/shared-bindings/touchio/TouchIn.h index 42f9da46d5..1da2cf190a 100644 --- a/shared-bindings/touchio/TouchIn.h +++ b/shared-bindings/touchio/TouchIn.h @@ -37,9 +37,9 @@ extern const mp_obj_type_t touchio_touchin_type; -void common_hal_touchio_touchin_construct(touchio_touchin_obj_t* self, const mcu_pin_obj_t *pin); -void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t* self); -bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t* self); +void common_hal_touchio_touchin_construct(touchio_touchin_obj_t *self, const mcu_pin_obj_t *pin); +void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t *self); +bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t *self); bool common_hal_touchio_touchin_get_value(touchio_touchin_obj_t *self); uint16_t common_hal_touchio_touchin_get_raw_value(touchio_touchin_obj_t *self); uint16_t common_hal_touchio_touchin_get_threshold(touchio_touchin_obj_t *self); diff --git a/shared-bindings/touchio/__init__.c b/shared-bindings/touchio/__init__.c index 92e067cf68..3c3413438e 100644 --- a/shared-bindings/touchio/__init__.c +++ b/shared-bindings/touchio/__init__.c @@ -66,5 +66,5 @@ STATIC MP_DEFINE_CONST_DICT(touchio_module_globals, touchio_module_globals_table const mp_obj_module_t touchio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&touchio_module_globals, + .globals = (mp_obj_dict_t *)&touchio_module_globals, }; diff --git a/shared-bindings/uheap/__init__.c b/shared-bindings/uheap/__init__.c index daf55a6138..8c9e2e81dc 100644 --- a/shared-bindings/uheap/__init__.c +++ b/shared-bindings/uheap/__init__.c @@ -55,5 +55,5 @@ STATIC MP_DEFINE_CONST_DICT(uheap_module_globals, uheap_module_globals_table); const mp_obj_module_t uheap_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&uheap_module_globals, + .globals = (mp_obj_dict_t *)&uheap_module_globals, }; diff --git a/shared-bindings/usb_cdc/Serial.c b/shared-bindings/usb_cdc/Serial.c index 82355f8978..ab05494519 100644 --- a/shared-bindings/usb_cdc/Serial.c +++ b/shared-bindings/usb_cdc/Serial.c @@ -314,5 +314,5 @@ const mp_obj_type_t usb_cdc_serial_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &usb_cdc_serial_stream_p, - .locals_dict = (mp_obj_dict_t*)&usb_cdc_serial_locals_dict, + .locals_dict = (mp_obj_dict_t *)&usb_cdc_serial_locals_dict, }; diff --git a/shared-bindings/usb_cdc/__init__.c b/shared-bindings/usb_cdc/__init__.c index eb9c25e001..9e9ccb898d 100644 --- a/shared-bindings/usb_cdc/__init__.c +++ b/shared-bindings/usb_cdc/__init__.c @@ -55,5 +55,5 @@ static MP_DEFINE_CONST_DICT(usb_cdc_module_globals, usb_cdc_module_globals_table const mp_obj_module_t usb_cdc_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&usb_cdc_module_globals, + .globals = (mp_obj_dict_t *)&usb_cdc_module_globals, }; diff --git a/shared-bindings/usb_hid/Device.c b/shared-bindings/usb_hid/Device.c index c7c05a9749..cd4f3dd54b 100644 --- a/shared-bindings/usb_hid/Device.c +++ b/shared-bindings/usb_hid/Device.c @@ -53,7 +53,7 @@ STATIC mp_obj_t usb_hid_device_send_report(mp_obj_t self_in, mp_obj_t buffer) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_READ); - common_hal_usb_hid_device_send_report(self, ((uint8_t*) bufinfo.buf), bufinfo.len); + common_hal_usb_hid_device_send_report(self, ((uint8_t *)bufinfo.buf), bufinfo.len); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(usb_hid_device_send_report_obj, usb_hid_device_send_report); @@ -104,7 +104,7 @@ STATIC mp_obj_t usb_hid_device_obj_get_usage(mp_obj_t self_in) { return MP_OBJ_NEW_SMALL_INT(common_hal_usb_hid_device_get_usage(self)); } MP_DEFINE_CONST_FUN_OBJ_1(usb_hid_device_get_usage_obj, - usb_hid_device_obj_get_usage); + usb_hid_device_obj_get_usage); const mp_obj_property_t usb_hid_device_usage_obj = { .base.type = &mp_type_property, diff --git a/shared-bindings/usb_hid/Device.h b/shared-bindings/usb_hid/Device.h index 017995ccc3..d9918d4060 100644 --- a/shared-bindings/usb_hid/Device.h +++ b/shared-bindings/usb_hid/Device.h @@ -31,7 +31,7 @@ extern const mp_obj_type_t usb_hid_device_type; -void common_hal_usb_hid_device_send_report(usb_hid_device_obj_t *self, uint8_t* report, uint8_t len); +void common_hal_usb_hid_device_send_report(usb_hid_device_obj_t *self, uint8_t *report, uint8_t len); uint8_t common_hal_usb_hid_device_get_usage_page(usb_hid_device_obj_t *self); uint8_t common_hal_usb_hid_device_get_usage(usb_hid_device_obj_t *self); diff --git a/shared-bindings/usb_hid/__init__.c b/shared-bindings/usb_hid/__init__.c index 36111e9194..1a2f28d431 100644 --- a/shared-bindings/usb_hid/__init__.c +++ b/shared-bindings/usb_hid/__init__.c @@ -49,5 +49,5 @@ STATIC MP_DEFINE_CONST_DICT(usb_hid_module_globals, usb_hid_module_globals_table const mp_obj_module_t usb_hid_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&usb_hid_module_globals, + .globals = (mp_obj_dict_t *)&usb_hid_module_globals, }; diff --git a/shared-bindings/usb_midi/PortIn.c b/shared-bindings/usb_midi/PortIn.c index c621c8c502..735d9da18a 100644 --- a/shared-bindings/usb_midi/PortIn.c +++ b/shared-bindings/usb_midi/PortIn.c @@ -117,5 +117,5 @@ const mp_obj_type_t usb_midi_portin_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &usb_midi_portin_stream_p, - .locals_dict = (mp_obj_dict_t*)&usb_midi_portin_locals_dict, + .locals_dict = (mp_obj_dict_t *)&usb_midi_portin_locals_dict, }; diff --git a/shared-bindings/usb_midi/PortOut.c b/shared-bindings/usb_midi/PortOut.c index ce7062ed3c..42fb61016e 100644 --- a/shared-bindings/usb_midi/PortOut.c +++ b/shared-bindings/usb_midi/PortOut.c @@ -98,5 +98,5 @@ const mp_obj_type_t usb_midi_portout_type = { .getiter = mp_identity_getiter, .iternext = mp_stream_unbuffered_iter, .protocol = &usb_midi_portout_stream_p, - .locals_dict = (mp_obj_dict_t*)&usb_midi_portout_locals_dict, + .locals_dict = (mp_obj_dict_t *)&usb_midi_portout_locals_dict, }; diff --git a/shared-bindings/usb_midi/PortOut.h b/shared-bindings/usb_midi/PortOut.h index 1eac2fa985..7d8a014dad 100644 --- a/shared-bindings/usb_midi/PortOut.h +++ b/shared-bindings/usb_midi/PortOut.h @@ -33,7 +33,7 @@ extern const mp_obj_type_t usb_midi_portout_type; // Write characters. len is in characters NOT bytes! extern size_t common_hal_usb_midi_portout_write(usb_midi_portout_obj_t *self, - const uint8_t *data, size_t len, int *errcode); + const uint8_t *data, size_t len, int *errcode); extern bool common_hal_usb_midi_portout_ready_to_tx(usb_midi_portout_obj_t *self); diff --git a/shared-bindings/usb_midi/__init__.c b/shared-bindings/usb_midi/__init__.c index d88a0db48d..4bbe46fda5 100644 --- a/shared-bindings/usb_midi/__init__.c +++ b/shared-bindings/usb_midi/__init__.c @@ -55,5 +55,5 @@ MP_DEFINE_MUTABLE_DICT(usb_midi_module_globals, usb_midi_module_globals_table); const mp_obj_module_t usb_midi_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&usb_midi_module_globals, + .globals = (mp_obj_dict_t *)&usb_midi_module_globals, }; diff --git a/shared-bindings/ustack/__init__.c b/shared-bindings/ustack/__init__.c index de48c838a2..e2a31e9c47 100644 --- a/shared-bindings/ustack/__init__.c +++ b/shared-bindings/ustack/__init__.c @@ -83,5 +83,5 @@ STATIC MP_DEFINE_CONST_DICT(ustack_module_globals, ustack_module_globals_table); const mp_obj_module_t ustack_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&ustack_module_globals, + .globals = (mp_obj_dict_t *)&ustack_module_globals, }; diff --git a/shared-bindings/vectorio/Circle.c b/shared-bindings/vectorio/Circle.c index 8f0d58d873..f7cf254fa4 100644 --- a/shared-bindings/vectorio/Circle.c +++ b/shared-bindings/vectorio/Circle.c @@ -70,5 +70,5 @@ const mp_obj_type_t vectorio_circle_type = { { &mp_type_type }, .name = MP_QSTR_Circle, .make_new = vectorio_circle_make_new, - .locals_dict = (mp_obj_dict_t*)&vectorio_circle_locals_dict, + .locals_dict = (mp_obj_dict_t *)&vectorio_circle_locals_dict, }; diff --git a/shared-bindings/vectorio/Polygon.c b/shared-bindings/vectorio/Polygon.c index 6a72f91246..737476c5ef 100644 --- a/shared-bindings/vectorio/Polygon.c +++ b/shared-bindings/vectorio/Polygon.c @@ -75,5 +75,5 @@ const mp_obj_type_t vectorio_polygon_type = { { &mp_type_type }, .name = MP_QSTR_Polygon, .make_new = vectorio_polygon_make_new, - .locals_dict = (mp_obj_dict_t*)&vectorio_polygon_locals_dict, + .locals_dict = (mp_obj_dict_t *)&vectorio_polygon_locals_dict, }; diff --git a/shared-bindings/vectorio/Rectangle.c b/shared-bindings/vectorio/Rectangle.c index 9a637f317c..a50a8a14b3 100644 --- a/shared-bindings/vectorio/Rectangle.c +++ b/shared-bindings/vectorio/Rectangle.c @@ -48,5 +48,5 @@ const mp_obj_type_t vectorio_rectangle_type = { { &mp_type_type }, .name = MP_QSTR_Rectangle, .make_new = vectorio_rectangle_make_new, - .locals_dict = (mp_obj_dict_t*)&vectorio_rectangle_locals_dict, + .locals_dict = (mp_obj_dict_t *)&vectorio_rectangle_locals_dict, }; diff --git a/shared-bindings/vectorio/VectorShape.c b/shared-bindings/vectorio/VectorShape.c index bc8c8d29c7..7c7f467b09 100644 --- a/shared-bindings/vectorio/VectorShape.c +++ b/shared-bindings/vectorio/VectorShape.c @@ -72,7 +72,7 @@ STATIC mp_obj_t vectorio_vector_shape_make_new(const mp_obj_type_t *type, size_t self->base.type = &vectorio_vector_shape_type; common_hal_vectorio_vector_shape_construct(self, ishape, pixel_shader, x, y - ); + ); // Wire up event callbacks vectorio_event_t on_dirty = { @@ -186,5 +186,5 @@ const mp_obj_type_t vectorio_vector_shape_type = { { &mp_type_type }, .name = MP_QSTR_VectorShape, .make_new = vectorio_vector_shape_make_new, - .locals_dict = (mp_obj_dict_t*)&vectorio_vector_shape_locals_dict, + .locals_dict = (mp_obj_dict_t *)&vectorio_vector_shape_locals_dict, }; diff --git a/shared-bindings/vectorio/VectorShape.h b/shared-bindings/vectorio/VectorShape.h index d098504e93..fa11f73ffd 100644 --- a/shared-bindings/vectorio/VectorShape.h +++ b/shared-bindings/vectorio/VectorShape.h @@ -7,8 +7,8 @@ extern const mp_obj_type_t vectorio_vector_shape_type; void common_hal_vectorio_vector_shape_construct(vectorio_vector_shape_t *self, - vectorio_ishape_t ishape, - mp_obj_t pixel_shader, uint16_t x, uint16_t y); + vectorio_ishape_t ishape, + mp_obj_t pixel_shader, uint16_t x, uint16_t y); void common_hal_vectorio_vector_shape_set_dirty(void *self); diff --git a/shared-bindings/vectorio/__init__.c b/shared-bindings/vectorio/__init__.c index c747834263..12fb4d72b1 100644 --- a/shared-bindings/vectorio/__init__.c +++ b/shared-bindings/vectorio/__init__.c @@ -23,5 +23,5 @@ STATIC MP_DEFINE_CONST_DICT(vectorio_module_globals, vectorio_module_globals_tab const mp_obj_module_t vectorio_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&vectorio_module_globals, + .globals = (mp_obj_dict_t *)&vectorio_module_globals, }; diff --git a/shared-bindings/watchdog/WatchDogMode.c b/shared-bindings/watchdog/WatchDogMode.c index 71512bdf8d..513884cdfc 100644 --- a/shared-bindings/watchdog/WatchDogMode.c +++ b/shared-bindings/watchdog/WatchDogMode.c @@ -83,12 +83,11 @@ STATIC void watchdog_watchdogmode_print(const mp_print_t *print, mp_obj_t self_i qstr runmode = MP_QSTR_None; if (MP_OBJ_TO_PTR(self_in) == MP_ROM_PTR(&watchdog_watchdogmode_raise_obj)) { runmode = MP_QSTR_RAISE; - } - else if (MP_OBJ_TO_PTR(self_in) == MP_ROM_PTR(&watchdog_watchdogmode_reset_obj)) { + } else if (MP_OBJ_TO_PTR(self_in) == MP_ROM_PTR(&watchdog_watchdogmode_reset_obj)) { runmode = MP_QSTR_RESET; } mp_printf(print, "%q.%q.%q", MP_QSTR_watchdog, MP_QSTR_WatchDogMode, - runmode); + runmode); } const mp_obj_type_t watchdog_watchdogmode_type = { diff --git a/shared-bindings/watchdog/WatchDogTimer.c b/shared-bindings/watchdog/WatchDogTimer.c index 575021a219..a27d26c20c 100644 --- a/shared-bindings/watchdog/WatchDogTimer.c +++ b/shared-bindings/watchdog/WatchDogTimer.c @@ -177,5 +177,5 @@ const mp_obj_type_t watchdog_watchdogtimer_type = { { &mp_type_type }, .name = MP_QSTR_WatchDogTimer, // .make_new = watchdog_watchdogtimer_make_new, - .locals_dict = (mp_obj_dict_t*)&watchdog_watchdogtimer_locals_dict, + .locals_dict = (mp_obj_dict_t *)&watchdog_watchdogtimer_locals_dict, }; diff --git a/shared-bindings/watchdog/__init__.c b/shared-bindings/watchdog/__init__.c index 76e6317294..0911aca282 100644 --- a/shared-bindings/watchdog/__init__.c +++ b/shared-bindings/watchdog/__init__.c @@ -64,7 +64,7 @@ mp_obj_exception_t mp_watchdog_timeout_exception = { .traceback_alloc = 0, .traceback_len = 0, .traceback_data = NULL, - .args = (mp_obj_tuple_t*)&mp_const_empty_tuple_obj, + .args = (mp_obj_tuple_t *)&mp_const_empty_tuple_obj, }; STATIC const mp_rom_map_elem_t watchdog_module_globals_table[] = { @@ -77,5 +77,5 @@ STATIC MP_DEFINE_CONST_DICT(watchdog_module_globals, watchdog_module_globals_tab const mp_obj_module_t watchdog_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&watchdog_module_globals, + .globals = (mp_obj_dict_t *)&watchdog_module_globals, }; diff --git a/shared-bindings/wifi/Radio.c b/shared-bindings/wifi/Radio.c index 8181fc4c96..5c7fe14924 100644 --- a/shared-bindings/wifi/Radio.c +++ b/shared-bindings/wifi/Radio.c @@ -132,7 +132,7 @@ STATIC mp_obj_t wifi_radio_set_hostname(mp_obj_t self_in, mp_obj_t hostname_in) mp_raise_ValueError(translate("Hostname must be between 1 and 253 characters")); } - regex_t regex; //validate hostname according to RFC 1123 + regex_t regex; // validate hostname according to RFC 1123 regcomp(®ex,"^(([a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])\\.)*([a-z0-9]|[a-z0-9][a-z0-9\\-]{0,61}[a-z0-9])$", REG_EXTENDED | REG_ICASE | REG_NOSUB); if (regexec(®ex, hostname.buf, 0, NULL, 0)) { mp_raise_ValueError(translate("invalid hostname")); @@ -179,7 +179,7 @@ STATIC mp_obj_t wifi_radio_connect(size_t n_args, const mp_obj_t *pos_args, mp_m static const mp_arg_t allowed_args[] = { { MP_QSTR_ssid, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_password, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, { MP_QSTR_bssid, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, }; diff --git a/shared-bindings/wifi/Radio.h b/shared-bindings/wifi/Radio.h index 64c1052f7b..333c82bab5 100644 --- a/shared-bindings/wifi/Radio.h +++ b/shared-bindings/wifi/Radio.h @@ -82,7 +82,7 @@ extern mp_obj_t common_hal_wifi_radio_get_mac_address(wifi_radio_obj_t *self); extern mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self); extern void common_hal_wifi_radio_stop_scanning_networks(wifi_radio_obj_t *self); -extern wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t* ssid, size_t ssid_len, uint8_t* password, size_t password_len, uint8_t channel, mp_float_t timeout, uint8_t* bssid, size_t bssid_len); +extern wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t *ssid, size_t ssid_len, uint8_t *password, size_t password_len, uint8_t channel, mp_float_t timeout, uint8_t *bssid, size_t bssid_len); extern mp_obj_t common_hal_wifi_radio_get_ap_info(wifi_radio_obj_t *self); extern mp_obj_t common_hal_wifi_radio_get_ipv4_dns(wifi_radio_obj_t *self); diff --git a/shared-bindings/wifi/__init__.c b/shared-bindings/wifi/__init__.c index 352ceb3318..38bd1bf078 100644 --- a/shared-bindings/wifi/__init__.c +++ b/shared-bindings/wifi/__init__.c @@ -66,5 +66,5 @@ STATIC MP_DEFINE_CONST_DICT(wifi_module_globals, wifi_module_globals_table); const mp_obj_module_t wifi_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&wifi_module_globals, + .globals = (mp_obj_dict_t *)&wifi_module_globals, }; diff --git a/shared-bindings/wiznet/__init__.c b/shared-bindings/wiznet/__init__.c index 8df06b5467..68402fd105 100644 --- a/shared-bindings/wiznet/__init__.c +++ b/shared-bindings/wiznet/__init__.c @@ -47,13 +47,13 @@ extern const mod_network_nic_type_t mod_network_nic_type_wiznet5k; STATIC const mp_rom_map_elem_t mp_module_wiznet_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_wiznet) }, -#ifdef MICROPY_PY_WIZNET5K + #ifdef MICROPY_PY_WIZNET5K { MP_ROM_QSTR(MP_QSTR_WIZNET5K), MP_ROM_PTR(&mod_network_nic_type_wiznet5k) }, -#endif // MICROPY_PY_WIZNET5K + #endif // MICROPY_PY_WIZNET5K }; STATIC MP_DEFINE_CONST_DICT(mp_module_wiznet_globals, mp_module_wiznet_globals_table); const mp_obj_module_t wiznet_module = { .base = { &mp_type_module }, - .globals = (mp_obj_dict_t*)&mp_module_wiznet_globals, + .globals = (mp_obj_dict_t *)&mp_module_wiznet_globals, }; diff --git a/shared-bindings/wiznet/wiznet5k.c b/shared-bindings/wiznet/wiznet5k.c index 5e9a3a9fbc..9ee1c6d58c 100644 --- a/shared-bindings/wiznet/wiznet5k.c +++ b/shared-bindings/wiznet/wiznet5k.c @@ -80,7 +80,9 @@ STATIC mp_obj_t wiznet5k_make_new(const mp_obj_type_t *type, size_t n_args, cons const mcu_pin_obj_t *rst = validate_obj_is_free_pin_or_none(args[ARG_rst].u_obj); mp_obj_t ret = wiznet5k_create(args[ARG_spi].u_obj, cs, rst); - if (args[ARG_dhcp].u_bool) wiznet5k_start_dhcp(); + if (args[ARG_dhcp].u_bool) { + wiznet5k_start_dhcp(); + } return ret; } @@ -118,10 +120,14 @@ STATIC mp_obj_t wiznet5k_dhcp_set_value(mp_obj_t self_in, mp_obj_t value) { (void)self_in; if (mp_obj_is_true(value)) { int ret = wiznet5k_start_dhcp(); - if (ret) mp_raise_OSError(ret); + if (ret) { + mp_raise_OSError(ret); + } } else { int ret = wiznet5k_stop_dhcp(); - if (ret) mp_raise_OSError(ret); + if (ret) { + mp_raise_OSError(ret); + } } return mp_const_none; } @@ -183,7 +189,7 @@ const mod_network_nic_type_t mod_network_nic_type_wiznet5k = { { &mp_type_type }, .name = MP_QSTR_WIZNET5K, .make_new = wiznet5k_make_new, - .locals_dict = (mp_obj_dict_t*)&wiznet5k_locals_dict, + .locals_dict = (mp_obj_dict_t *)&wiznet5k_locals_dict, }, .gethostbyname = wiznet5k_gethostbyname, .socket = wiznet5k_socket_socket, diff --git a/shared-module/_bleio/Characteristic.h b/shared-module/_bleio/Characteristic.h index 7776b1fa57..298592b9eb 100644 --- a/shared-module/_bleio/Characteristic.h +++ b/shared-module/_bleio/Characteristic.h @@ -39,18 +39,18 @@ typedef enum { CHAR_PROP_WRITE = 1u << 4, CHAR_PROP_WRITE_NO_RESPONSE = 1u << 5, CHAR_PROP_ALL = (CHAR_PROP_BROADCAST | CHAR_PROP_INDICATE | CHAR_PROP_NOTIFY | - CHAR_PROP_READ | CHAR_PROP_WRITE | CHAR_PROP_WRITE_NO_RESPONSE) + CHAR_PROP_READ | CHAR_PROP_WRITE | CHAR_PROP_WRITE_NO_RESPONSE) } bleio_characteristic_properties_enum_t; typedef uint8_t bleio_characteristic_properties_t; // Bluetooth spec property values -#define BT_GATT_CHRC_BROADCAST 0x01 -#define BT_GATT_CHRC_READ 0x02 -#define BT_GATT_CHRC_WRITE_WITHOUT_RESP 0x04 -#define BT_GATT_CHRC_WRITE 0x08 -#define BT_GATT_CHRC_NOTIFY 0x10 -#define BT_GATT_CHRC_INDICATE 0x20 -#define BT_GATT_CHRC_AUTH 0x40 -#define BT_GATT_CHRC_EXT_PROP 0x80 +#define BT_GATT_CHRC_BROADCAST 0x01 +#define BT_GATT_CHRC_READ 0x02 +#define BT_GATT_CHRC_WRITE_WITHOUT_RESP 0x04 +#define BT_GATT_CHRC_WRITE 0x08 +#define BT_GATT_CHRC_NOTIFY 0x10 +#define BT_GATT_CHRC_INDICATE 0x20 +#define BT_GATT_CHRC_AUTH 0x40 +#define BT_GATT_CHRC_EXT_PROP 0x80 #endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_CHARACTERISTIC_H diff --git a/shared-module/_bleio/ScanEntry.c b/shared-module/_bleio/ScanEntry.c index af9e4b3471..28ff215a35 100644 --- a/shared-module/_bleio/ScanEntry.c +++ b/shared-module/_bleio/ScanEntry.c @@ -52,7 +52,7 @@ bool common_hal_bleio_scanentry_get_scan_response(bleio_scanentry_obj_t *self) { return self->scan_response; } -bool bleio_scanentry_data_matches(const uint8_t* data, size_t len, const uint8_t* prefixes, size_t prefixes_length, bool any) { +bool bleio_scanentry_data_matches(const uint8_t *data, size_t len, const uint8_t *prefixes, size_t prefixes_length, bool any) { if (prefixes_length == 0) { return true; } @@ -61,7 +61,7 @@ bool bleio_scanentry_data_matches(const uint8_t* data, size_t len, const uint8_t return false; } size_t i = 0; - while(i < prefixes_length) { + while (i < prefixes_length) { uint8_t prefix_length = prefixes[i]; i += 1; size_t j = 0; @@ -91,6 +91,6 @@ bool bleio_scanentry_data_matches(const uint8_t* data, size_t len, const uint8_t return !any; } -bool common_hal_bleio_scanentry_matches(bleio_scanentry_obj_t *self, const uint8_t* prefixes, size_t prefixes_len, bool all) { +bool common_hal_bleio_scanentry_matches(bleio_scanentry_obj_t *self, const uint8_t *prefixes, size_t prefixes_len, bool all) { return bleio_scanentry_data_matches(self->data->data, self->data->len, prefixes, prefixes_len, !all); } diff --git a/shared-module/_bleio/ScanEntry.h b/shared-module/_bleio/ScanEntry.h index 94361a397d..9e142fd6e0 100644 --- a/shared-module/_bleio/ScanEntry.h +++ b/shared-module/_bleio/ScanEntry.h @@ -42,6 +42,6 @@ typedef struct { uint64_t time_received; } bleio_scanentry_obj_t; -bool bleio_scanentry_data_matches(const uint8_t* data, size_t len, const uint8_t* prefixes, size_t prefix_length, bool any); +bool bleio_scanentry_data_matches(const uint8_t *data, size_t len, const uint8_t *prefixes, size_t prefix_length, bool any); #endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANENTRY_H diff --git a/shared-module/_bleio/ScanResults.c b/shared-module/_bleio/ScanResults.c index cb48d636dc..25ce387d07 100644 --- a/shared-module/_bleio/ScanResults.c +++ b/shared-module/_bleio/ScanResults.c @@ -34,8 +34,8 @@ #include "shared-bindings/_bleio/ScanEntry.h" #include "shared-bindings/_bleio/ScanResults.h" -bleio_scanresults_obj_t* shared_module_bleio_new_scanresults(size_t buffer_size, uint8_t* prefixes, size_t prefixes_len, mp_int_t minimum_rssi) { - bleio_scanresults_obj_t* self = m_new_obj(bleio_scanresults_obj_t); +bleio_scanresults_obj_t *shared_module_bleio_new_scanresults(size_t buffer_size, uint8_t *prefixes, size_t prefixes_len, mp_int_t minimum_rssi) { + bleio_scanresults_obj_t *self = m_new_obj(bleio_scanresults_obj_t); self->base.type = &bleio_scanresults_type; ringbuf_alloc(&self->buf, buffer_size, false); self->prefixes = prefixes; @@ -57,16 +57,16 @@ mp_obj_t common_hal_bleio_scanresults_next(bleio_scanresults_obj_t *self) { bool connectable = (type & (1 << 0)) != 0; bool scan_response = (type & (1 << 1)) != 0; uint64_t ticks_ms; - ringbuf_get_n(&self->buf, (uint8_t*) &ticks_ms, sizeof(ticks_ms)); + ringbuf_get_n(&self->buf, (uint8_t *)&ticks_ms, sizeof(ticks_ms)); uint8_t rssi = ringbuf_get(&self->buf); uint8_t peer_addr[NUM_BLEIO_ADDRESS_BYTES]; ringbuf_get_n(&self->buf, peer_addr, sizeof(peer_addr)); uint8_t addr_type = ringbuf_get(&self->buf); uint16_t len; - ringbuf_get_n(&self->buf, (uint8_t*) &len, sizeof(len)); + ringbuf_get_n(&self->buf, (uint8_t *)&len, sizeof(len)); mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_bytes_of_zeros(len)); - ringbuf_get_n(&self->buf, (uint8_t*) o->data, len); + ringbuf_get_n(&self->buf, (uint8_t *)o->data, len); bleio_scanentry_obj_t *entry = m_new_obj(bleio_scanentry_obj_t); entry->base.type = &bleio_scanentry_type; @@ -86,15 +86,15 @@ mp_obj_t common_hal_bleio_scanresults_next(bleio_scanresults_obj_t *self) { } -void shared_module_bleio_scanresults_append(bleio_scanresults_obj_t* self, - uint64_t ticks_ms, - bool connectable, - bool scan_response, - int8_t rssi, - uint8_t *peer_addr, - uint8_t addr_type, - uint8_t *data, - uint16_t len) { +void shared_module_bleio_scanresults_append(bleio_scanresults_obj_t *self, + uint64_t ticks_ms, + bool connectable, + bool scan_response, + int8_t rssi, + uint8_t *peer_addr, + uint8_t addr_type, + uint8_t *data, + uint16_t len) { int32_t packet_size = sizeof(uint8_t) + sizeof(ticks_ms) + sizeof(rssi) + NUM_BLEIO_ADDRESS_BYTES + sizeof(addr_type) + sizeof(len) + len; int32_t empty_space = self->buf.size - ringbuf_num_filled(&self->buf); @@ -121,19 +121,19 @@ void shared_module_bleio_scanresults_append(bleio_scanresults_obj_t* self, // Add the packet to the buffer. ringbuf_put(&self->buf, type); - ringbuf_put_n(&self->buf, (uint8_t*) &ticks_ms, sizeof(ticks_ms)); + ringbuf_put_n(&self->buf, (uint8_t *)&ticks_ms, sizeof(ticks_ms)); ringbuf_put(&self->buf, rssi); ringbuf_put_n(&self->buf, peer_addr, NUM_BLEIO_ADDRESS_BYTES); ringbuf_put(&self->buf, addr_type); - ringbuf_put_n(&self->buf, (uint8_t*) &len, sizeof(len)); + ringbuf_put_n(&self->buf, (uint8_t *)&len, sizeof(len)); ringbuf_put_n(&self->buf, data, len); } -bool shared_module_bleio_scanresults_get_done(bleio_scanresults_obj_t* self) { +bool shared_module_bleio_scanresults_get_done(bleio_scanresults_obj_t *self) { return self->done; } -void shared_module_bleio_scanresults_set_done(bleio_scanresults_obj_t* self, bool done) { +void shared_module_bleio_scanresults_set_done(bleio_scanresults_obj_t *self, bool done) { self->done = done; self->common_hal_data = NULL; } diff --git a/shared-module/_bleio/ScanResults.h b/shared-module/_bleio/ScanResults.h index 8912357a97..fa181aabee 100644 --- a/shared-module/_bleio/ScanResults.h +++ b/shared-module/_bleio/ScanResults.h @@ -36,29 +36,29 @@ typedef struct { mp_obj_base_t base; // Pointers that needs to live until the scan is done. - void* common_hal_data; + void *common_hal_data; ringbuf_t buf; // Prefixes is a length encoded array of prefixes. - uint8_t* prefixes; + uint8_t *prefixes; size_t prefix_length; mp_int_t minimum_rssi; bool active; bool done; } bleio_scanresults_obj_t; -bleio_scanresults_obj_t* shared_module_bleio_new_scanresults(size_t buffer_size, uint8_t* prefixes, size_t prefixes_len, mp_int_t minimum_rssi); +bleio_scanresults_obj_t *shared_module_bleio_new_scanresults(size_t buffer_size, uint8_t *prefixes, size_t prefixes_len, mp_int_t minimum_rssi); -bool shared_module_bleio_scanresults_get_done(bleio_scanresults_obj_t* self); -void shared_module_bleio_scanresults_set_done(bleio_scanresults_obj_t* self, bool done); +bool shared_module_bleio_scanresults_get_done(bleio_scanresults_obj_t *self); +void shared_module_bleio_scanresults_set_done(bleio_scanresults_obj_t *self, bool done); -void shared_module_bleio_scanresults_append(bleio_scanresults_obj_t* self, - uint64_t ticks_ms, - bool connectable, - bool scan_result, - int8_t rssi, - uint8_t *peer_addr, - uint8_t addr_type, - uint8_t* data, - uint16_t len); +void shared_module_bleio_scanresults_append(bleio_scanresults_obj_t *self, + uint64_t ticks_ms, + bool connectable, + bool scan_result, + int8_t rssi, + uint8_t *peer_addr, + uint8_t addr_type, + uint8_t *data, + uint16_t len); #endif // MICROPY_INCLUDED_SHARED_MODULE_BLEIO_SCANRESULTS_H diff --git a/shared-module/_eve/__init__.c b/shared-module/_eve/__init__.c index 579729d42c..0df77b65cb 100644 --- a/shared-module/_eve/__init__.c +++ b/shared-module/_eve/__init__.c @@ -42,25 +42,28 @@ void common_hal__eve_flush(common_hal__eve_t *eve) { } static void *append(common_hal__eve_t *eve, size_t m) { - if ((eve->n + m) > sizeof(eve->buf)) + if ((eve->n + m) > sizeof(eve->buf)) { common_hal__eve_flush(eve); + } uint8_t *r = eve->buf + eve->n; eve->n += m; - return (void*)r; + return (void *)r; } void common_hal__eve_add(common_hal__eve_t *eve, size_t len, void *buf) { if (len <= sizeof(eve->buf)) { - uint8_t *p = (uint8_t*)append(eve, len); - // memcpy(p, buffer_info.buf, buffer_info.len); - uint8_t *s = buf; for (size_t i = 0; i < len; i++) *p++ = *s++; + uint8_t *p = (uint8_t *)append(eve, len); + // memcpy(p, buffer_info.buf, buffer_info.len); + uint8_t *s = buf; + for (size_t i = 0; i < len; i++) { *p++ = *s++; + } } else { - common_hal__eve_flush(eve); - write(eve, len, buf); + common_hal__eve_flush(eve); + write(eve, len, buf); } } -#define C4(eve, u) (*(uint32_t*)append((eve), sizeof(uint32_t)) = (u)) +#define C4(eve, u) (*(uint32_t *)append((eve), sizeof(uint32_t)) = (u)) void common_hal__eve_Vertex2f(common_hal__eve_t *eve, mp_float_t x, mp_float_t y) { int16_t ix = (int)(eve->vscale * x); @@ -68,8 +71,7 @@ void common_hal__eve_Vertex2f(common_hal__eve_t *eve, mp_float_t x, mp_float_t y C4(eve, (1 << 30) | ((ix & 32767) << 15) | (iy & 32767)); } -void common_hal__eve_VertexFormat(common_hal__eve_t *eve, uint32_t frac) -{ +void common_hal__eve_VertexFormat(common_hal__eve_t *eve, uint32_t frac) { C4(eve, ((39 << 24) | ((frac & 7)))); eve->vscale = 1 << frac; } diff --git a/shared-module/_pixelbuf/PixelBuf.c b/shared-module/_pixelbuf/PixelBuf.c index 4cbf6dc21f..df160b1ffa 100644 --- a/shared-module/_pixelbuf/PixelBuf.c +++ b/shared-module/_pixelbuf/PixelBuf.c @@ -34,15 +34,15 @@ #include // Helper to ensure we have the native super class instead of a subclass. -static pixelbuf_pixelbuf_obj_t* native_pixelbuf(mp_obj_t pixelbuf_obj) { +static pixelbuf_pixelbuf_obj_t *native_pixelbuf(mp_obj_t pixelbuf_obj) { mp_obj_t native_pixelbuf = mp_instance_cast_to_native_base(pixelbuf_obj, &pixelbuf_pixelbuf_type); mp_obj_assert_native_inited(native_pixelbuf); return MP_OBJ_TO_PTR(native_pixelbuf); } void common_hal__pixelbuf_pixelbuf_construct(pixelbuf_pixelbuf_obj_t *self, size_t n, - pixelbuf_byteorder_details_t* byteorder, mp_float_t brightness, bool auto_write, - uint8_t* header, size_t header_len, uint8_t* trailer, size_t trailer_len) { + pixelbuf_byteorder_details_t *byteorder, mp_float_t brightness, bool auto_write, + uint8_t *header, size_t header_len, uint8_t *trailer, size_t trailer_len) { self->pixel_count = n; self->byteorder = *byteorder; // Copied because we modify for dotstar @@ -56,7 +56,7 @@ void common_hal__pixelbuf_pixelbuf_construct(pixelbuf_pixelbuf_obj_t *self, size // Abuse the bytes object a bit by mutating it's data by dropping the const. If the user's // Python code holds onto it, they'll find out that it changes. At least this way it isn't // mutable by the code itself. - uint8_t* transmit_buffer = (uint8_t*) o->data; + uint8_t *transmit_buffer = (uint8_t *)o->data; memcpy(transmit_buffer, header, header_len); memcpy(transmit_buffer + header_len + pixel_len, trailer, trailer_len); self->post_brightness_buffer = transmit_buffer + header_len; @@ -78,37 +78,37 @@ void common_hal__pixelbuf_pixelbuf_construct(pixelbuf_pixelbuf_obj_t *self, size } size_t common_hal__pixelbuf_pixelbuf_get_len(mp_obj_t self_in) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); return self->pixel_count; } uint8_t common_hal__pixelbuf_pixelbuf_get_bpp(mp_obj_t self_in) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); return self->byteorder.bpp; } mp_obj_t common_hal__pixelbuf_pixelbuf_get_byteorder_string(mp_obj_t self_in) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); return self->byteorder.order_string; } bool common_hal__pixelbuf_pixelbuf_get_auto_write(mp_obj_t self_in) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); return self->auto_write; } void common_hal__pixelbuf_pixelbuf_set_auto_write(mp_obj_t self_in, bool auto_write) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); self->auto_write = auto_write; } mp_float_t common_hal__pixelbuf_pixelbuf_get_brightness(mp_obj_t self_in) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); return self->brightness; } void common_hal__pixelbuf_pixelbuf_set_brightness(mp_obj_t self_in, mp_float_t brightness) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); // Skip out if the brightness is already set. The default of self->brightness is 1.0. So, this // also prevents the pre_brightness_buffer allocation when brightness is set to 1.0 again. self->brightness = brightness; @@ -149,10 +149,10 @@ uint8_t _pixelbuf_get_as_uint8(mp_obj_t obj) { return (uint8_t)mp_obj_get_float(obj); } mp_raise_TypeError_varg( - translate("can't convert %q to %q"), mp_obj_get_type_qstr(obj), MP_QSTR_int); + translate("can't convert %q to %q"), mp_obj_get_type_qstr(obj), MP_QSTR_int); } -void _pixelbuf_parse_color(pixelbuf_pixelbuf_obj_t* self, mp_obj_t color, uint8_t* r, uint8_t* g, uint8_t* b, uint8_t* w) { +void _pixelbuf_parse_color(pixelbuf_pixelbuf_obj_t *self, mp_obj_t color, uint8_t *r, uint8_t *g, uint8_t *b, uint8_t *w) { pixelbuf_byteorder_details_t *byteorder = &self->byteorder; // w is shared between white in NeoPixels and brightness in dotstars (so that DotStars can have // per-pixel brightness). Set the defaults here in case it isn't set below. @@ -197,7 +197,7 @@ void _pixelbuf_parse_color(pixelbuf_pixelbuf_obj_t* self, mp_obj_t color, uint8_ } } -void _pixelbuf_set_pixel_color(pixelbuf_pixelbuf_obj_t* self, size_t index, uint8_t r, uint8_t g, uint8_t b, uint8_t w) { +void _pixelbuf_set_pixel_color(pixelbuf_pixelbuf_obj_t *self, size_t index, uint8_t r, uint8_t g, uint8_t b, uint8_t w) { // DotStars don't have white, instead they have 5 bit brightness so pack it into w. Shift right // by three to leave the top five bits. if (self->bytes_per_pixel == 4 && self->byteorder.is_dotstar) { @@ -235,7 +235,7 @@ void _pixelbuf_set_pixel_color(pixelbuf_pixelbuf_obj_t* self, size_t index, uint } } -void _pixelbuf_set_pixel(pixelbuf_pixelbuf_obj_t* self, size_t index, mp_obj_t value) { +void _pixelbuf_set_pixel(pixelbuf_pixelbuf_obj_t *self, size_t index, mp_obj_t value) { uint8_t r; uint8_t g; uint8_t b; @@ -244,26 +244,27 @@ void _pixelbuf_set_pixel(pixelbuf_pixelbuf_obj_t* self, size_t index, mp_obj_t v _pixelbuf_set_pixel_color(self, index, r, g, b, w); } -void common_hal__pixelbuf_pixelbuf_set_pixels(mp_obj_t self_in, size_t start, mp_int_t step, size_t slice_len, mp_obj_t* values, - mp_obj_tuple_t *flatten_to) -{ - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); +void common_hal__pixelbuf_pixelbuf_set_pixels(mp_obj_t self_in, size_t start, mp_int_t step, size_t slice_len, mp_obj_t *values, + mp_obj_tuple_t *flatten_to) { + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); mp_obj_iter_buf_t iter_buf; mp_obj_t iterable = mp_getiter(values, &iter_buf); mp_obj_t item; size_t i = 0; bool flattened = flatten_to != mp_const_none; - if (flattened) flatten_to->len = self->bytes_per_pixel; + if (flattened) { + flatten_to->len = self->bytes_per_pixel; + } while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { if (flattened) { flatten_to->items[i % self->bytes_per_pixel] = item; if (++i % self->bytes_per_pixel == 0) { _pixelbuf_set_pixel(self, start, flatten_to); - start+=step; + start += step; } } else { _pixelbuf_set_pixel(self, start, item); - start+=step; + start += step; } } if (self->auto_write) { @@ -274,7 +275,7 @@ void common_hal__pixelbuf_pixelbuf_set_pixels(mp_obj_t self_in, size_t start, mp void common_hal__pixelbuf_pixelbuf_set_pixel(mp_obj_t self_in, size_t index, mp_obj_t value) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); _pixelbuf_set_pixel(self, index, value); if (self->auto_write) { common_hal__pixelbuf_pixelbuf_show(self_in); @@ -282,9 +283,9 @@ void common_hal__pixelbuf_pixelbuf_set_pixel(mp_obj_t self_in, size_t index, mp_ } mp_obj_t common_hal__pixelbuf_pixelbuf_get_pixel(mp_obj_t self_in, size_t index) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); mp_obj_t elems[self->byteorder.bpp]; - uint8_t* pixel_buffer = self->post_brightness_buffer; + uint8_t *pixel_buffer = self->post_brightness_buffer; if (self->pre_brightness_buffer != NULL) { pixel_buffer = self->pre_brightness_buffer; } @@ -307,7 +308,7 @@ mp_obj_t common_hal__pixelbuf_pixelbuf_get_pixel(mp_obj_t self_in, size_t index) } void common_hal__pixelbuf_pixelbuf_show(mp_obj_t self_in) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); mp_obj_t dest[2 + 1]; mp_load_method(self_in, MP_QSTR__transmit, dest); @@ -317,7 +318,7 @@ void common_hal__pixelbuf_pixelbuf_show(mp_obj_t self_in) { } void common_hal__pixelbuf_pixelbuf_fill(mp_obj_t self_in, mp_obj_t fill_color) { - pixelbuf_pixelbuf_obj_t* self = native_pixelbuf(self_in); + pixelbuf_pixelbuf_obj_t *self = native_pixelbuf(self_in); uint8_t r; uint8_t g; diff --git a/shared-module/_stage/Layer.c b/shared-module/_stage/Layer.c index d958f0d197..df2b27fa13 100644 --- a/shared-module/_stage/Layer.c +++ b/shared-module/_stage/Layer.c @@ -37,7 +37,7 @@ uint16_t get_layer_pixel(layer_obj_t *layer, uint16_t x, uint16_t y) { // Bounds check. if ((x < 0) || (x >= layer->width << 4) || - (y < 0) || (y >= layer->height << 4)) { + (y < 0) || (y >= layer->height << 4)) { return TRANSPARENT; } diff --git a/shared-module/_stage/Text.c b/shared-module/_stage/Text.c index df5bf80080..91223f5258 100644 --- a/shared-module/_stage/Text.c +++ b/shared-module/_stage/Text.c @@ -37,7 +37,7 @@ uint16_t get_text_pixel(text_obj_t *text, uint16_t x, uint16_t y) { // Bounds check. if ((x < 0) || (x >= text->width << 3) || - (y < 0) || (y >= text->height << 3)) { + (y < 0) || (y >= text->height << 3)) { return TRANSPARENT; } diff --git a/shared-module/_stage/__init__.c b/shared-module/_stage/__init__.c index 6dfc188801..06a12aa0a7 100644 --- a/shared-module/_stage/__init__.c +++ b/shared-module/_stage/__init__.c @@ -32,10 +32,10 @@ void render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, - mp_obj_t *layers, size_t layers_size, - uint16_t *buffer, size_t buffer_size, - displayio_display_obj_t *display, - uint8_t scale, uint16_t background) { + mp_obj_t *layers, size_t layers_size, + uint16_t *buffer, size_t buffer_size, + displayio_display_obj_t *display, + uint8_t scale, uint16_t background) { displayio_area_t area; @@ -51,8 +51,8 @@ void render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, RUN_BACKGROUND_TASKS; } display->core.send(display->core.bus, DISPLAY_COMMAND, - CHIP_SELECT_TOGGLE_EVERY_BYTE, - &display->write_ram_command, 1); + CHIP_SELECT_TOGGLE_EVERY_BYTE, + &display->write_ram_command, 1); size_t index = 0; for (uint16_t y = y0; y < y1; ++y) { for (uint8_t yscale = 0; yscale < scale; ++yscale) { @@ -78,8 +78,8 @@ void render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, // The buffer is full, send it. if (index >= buffer_size) { display->core.send(display->core.bus, DISPLAY_DATA, - CHIP_SELECT_UNTOUCHED, - ((uint8_t*)buffer), buffer_size * 2); + CHIP_SELECT_UNTOUCHED, + ((uint8_t *)buffer), buffer_size * 2); index = 0; } } @@ -89,8 +89,8 @@ void render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, // Send the remaining data. if (index) { display->core.send(display->core.bus, DISPLAY_DATA, - CHIP_SELECT_UNTOUCHED, - ((uint8_t*)buffer), index * 2); + CHIP_SELECT_UNTOUCHED, + ((uint8_t *)buffer), index * 2); } displayio_display_core_end_transaction(&display->core); diff --git a/shared-module/_stage/__init__.h b/shared-module/_stage/__init__.h index 7a1826200e..5cbaa235b6 100644 --- a/shared-module/_stage/__init__.h +++ b/shared-module/_stage/__init__.h @@ -35,9 +35,9 @@ #define TRANSPARENT (0x1ff8) void render_stage(uint16_t x0, uint16_t y0, uint16_t x1, uint16_t y1, - mp_obj_t *layers, size_t layers_size, - uint16_t *buffer, size_t buffer_size, - displayio_display_obj_t *display, - uint8_t scale, uint16_t background); + mp_obj_t *layers, size_t layers_size, + uint16_t *buffer, size_t buffer_size, + displayio_display_obj_t *display, + uint8_t scale, uint16_t background); #endif // MICROPY_INCLUDED_SHARED_MODULE__STAGE diff --git a/shared-module/adafruit_bus_device/I2CDevice.c b/shared-module/adafruit_bus_device/I2CDevice.c index 6d80cf599d..51c5073a74 100644 --- a/shared-module/adafruit_bus_device/I2CDevice.c +++ b/shared-module/adafruit_bus_device/I2CDevice.c @@ -78,10 +78,9 @@ void common_hal_adafruit_bus_device_i2cdevice_probe_for_device(adafruit_bus_devi } else { common_hal_adafruit_bus_device_i2cdevice_unlock(self); - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t*)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_OSError))) { + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_OSError))) { mp_raise_ValueError_varg(translate("No I2C device at address: %x"), self->device_address); - } - else { + } else { /* In case we receive an unrelated exception pass it up */ nlr_raise(MP_OBJ_FROM_PTR(nlr.ret_val)); } diff --git a/shared-module/adafruit_bus_device/SPIDevice.c b/shared-module/adafruit_bus_device/SPIDevice.c index 65649026a6..c65807aeb4 100644 --- a/shared-module/adafruit_bus_device/SPIDevice.c +++ b/shared-module/adafruit_bus_device/SPIDevice.c @@ -68,14 +68,15 @@ void common_hal_adafruit_bus_device_spidevice_exit(adafruit_bus_device_spidevice mp_obj_t buffer = mp_obj_new_bytearray_of_zeros(1); mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_READ); - ((uint8_t*)bufinfo.buf)[0] = 0xFF; + ((uint8_t *)bufinfo.buf)[0] = 0xFF; uint8_t clocks = self->extra_clocks / 8; - if ((self->extra_clocks % 8) != 0) + if ((self->extra_clocks % 8) != 0) { clocks += 1; + } while (clocks > 0) { - if (!common_hal_busio_spi_write(self->spi, ((uint8_t*)bufinfo.buf), 1)) { + if (!common_hal_busio_spi_write(self->spi, ((uint8_t *)bufinfo.buf), 1)) { mp_raise_OSError(MP_EIO); } clocks--; diff --git a/shared-module/aesio/__init__.c b/shared-module/aesio/__init__.c index 2cacaeb66e..bd748f9800 100644 --- a/shared-module/aesio/__init__.c +++ b/shared-module/aesio/__init__.c @@ -6,53 +6,53 @@ #include "shared-module/aesio/__init__.h" void common_hal_aesio_aes_construct(aesio_aes_obj_t *self, const uint8_t *key, - uint32_t key_length, const uint8_t *iv, - int mode, int counter) { - self->mode = mode; - self->counter = counter; - common_hal_aesio_aes_rekey(self, key, key_length, iv); + uint32_t key_length, const uint8_t *iv, + int mode, int counter) { + self->mode = mode; + self->counter = counter; + common_hal_aesio_aes_rekey(self, key, key_length, iv); } void common_hal_aesio_aes_rekey(aesio_aes_obj_t *self, const uint8_t *key, - uint32_t key_length, const uint8_t *iv) { - memset(&self->ctx, 0, sizeof(self->ctx)); - if (iv != NULL) { - AES_init_ctx_iv(&self->ctx, key, key_length, iv); - } else { - AES_init_ctx(&self->ctx, key, key_length); - } + uint32_t key_length, const uint8_t *iv) { + memset(&self->ctx, 0, sizeof(self->ctx)); + if (iv != NULL) { + AES_init_ctx_iv(&self->ctx, key, key_length, iv); + } else { + AES_init_ctx(&self->ctx, key, key_length); + } } void common_hal_aesio_aes_set_mode(aesio_aes_obj_t *self, int mode) { - self->mode = mode; + self->mode = mode; } void common_hal_aesio_aes_encrypt(aesio_aes_obj_t *self, uint8_t *buffer, - size_t length) { - switch (self->mode) { - case AES_MODE_ECB: - AES_ECB_encrypt(&self->ctx, buffer); - break; - case AES_MODE_CBC: - AES_CBC_encrypt_buffer(&self->ctx, buffer, length); - break; - case AES_MODE_CTR: - AES_CTR_xcrypt_buffer(&self->ctx, buffer, length); - break; - } + size_t length) { + switch (self->mode) { + case AES_MODE_ECB: + AES_ECB_encrypt(&self->ctx, buffer); + break; + case AES_MODE_CBC: + AES_CBC_encrypt_buffer(&self->ctx, buffer, length); + break; + case AES_MODE_CTR: + AES_CTR_xcrypt_buffer(&self->ctx, buffer, length); + break; + } } void common_hal_aesio_aes_decrypt(aesio_aes_obj_t *self, uint8_t *buffer, - size_t length) { - switch (self->mode) { - case AES_MODE_ECB: - AES_ECB_decrypt(&self->ctx, buffer); - break; - case AES_MODE_CBC: - AES_CBC_decrypt_buffer(&self->ctx, buffer, length); - break; - case AES_MODE_CTR: - AES_CTR_xcrypt_buffer(&self->ctx, buffer, length); - break; - } + size_t length) { + switch (self->mode) { + case AES_MODE_ECB: + AES_ECB_decrypt(&self->ctx, buffer); + break; + case AES_MODE_CBC: + AES_CBC_decrypt_buffer(&self->ctx, buffer, length); + break; + case AES_MODE_CTR: + AES_CTR_xcrypt_buffer(&self->ctx, buffer, length); + break; + } } diff --git a/shared-module/aesio/aes.c b/shared-module/aesio/aes.c index b62b5afc48..f417e76de6 100644 --- a/shared-module/aesio/aes.c +++ b/shared-module/aesio/aes.c @@ -80,46 +80,49 @@ typedef uint8_t state_t[4][4]; // RAM - This can be useful in (embedded) bootloader applications, where ROM is // often limited. static const uint8_t sbox[256] = { - //0 1 2 3 4 5 6 7 8 9 A B C D E F - 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, - 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, - 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, - 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, - 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, - 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; + // 0 1 2 3 4 5 6 7 8 9 A B C D E F + 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, + 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, + 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, + 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, + 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, + 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, + 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, + 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, + 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, + 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, + 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, + 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, + 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, + 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, + 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, + 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 +}; static const uint8_t rsbox[256] = { - 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, - 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, - 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, - 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, - 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, - 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, - 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, - 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, - 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, - 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, - 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, - 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, - 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, - 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, - 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, - 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; + 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, + 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, + 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, + 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, + 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, + 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, + 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, + 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, + 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, + 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, + 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, + 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, + 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, + 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, + 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, + 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d +}; // The round constant word array, Rcon[i], contains the values given by x to the // power (i-1) being powers of x (x is denoted as {02}) in the field GF(2^8) static const uint8_t Rcon[11] = { - 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 }; + 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 +}; /* * Jordan Goulder points out in PR #12 @@ -139,18 +142,21 @@ static const uint8_t Rcon[11] = { /* Private functions: */ /*****************************************************************************/ static const uint8_t *GetRoundKey(const struct AES_ctx *ctx) { - switch (ctx->KeyLength) { -#if defined(AES128) && (AES128 == 1) - case 16: return ctx->RoundKey128; -#endif -#if defined(AES192) && (AES192 == 1) - case 24: return ctx->RoundKey192; -#endif -#if defined(AES256) && (AES256 == 1) - case 32: return ctx->RoundKey256; -#endif - } - return NULL; + switch (ctx->KeyLength) { + #if defined(AES128) && (AES128 == 1) + case 16: + return ctx->RoundKey128; + #endif + #if defined(AES192) && (AES192 == 1) + case 24: + return ctx->RoundKey192; + #endif + #if defined(AES256) && (AES256 == 1) + case 32: + return ctx->RoundKey256; + #endif + } + return NULL; } @@ -171,190 +177,200 @@ static uint8_t getSBoxInvert(uint8_t num) // This function produces Nb(Nr+1) round keys. The round keys are used in each // round to decrypt the states. -static void KeyExpansion(struct AES_ctx* ctx, const uint8_t* Key) -{ - uint8_t* RoundKey = (uint8_t *)GetRoundKey(ctx); +static void KeyExpansion(struct AES_ctx *ctx, const uint8_t *Key) { + uint8_t *RoundKey = (uint8_t *)GetRoundKey(ctx); - unsigned i, j, k; - uint8_t tempa[4]; // Used for the column/row operations + unsigned i, j, k; + uint8_t tempa[4]; // Used for the column/row operations - // The first round key is the key itself. - for (i = 0; i < ctx->Nk; ++i) - { - RoundKey[(i * 4) + 0] = Key[(i * 4) + 0]; - RoundKey[(i * 4) + 1] = Key[(i * 4) + 1]; - RoundKey[(i * 4) + 2] = Key[(i * 4) + 2]; - RoundKey[(i * 4) + 3] = Key[(i * 4) + 3]; - } - - // All other round keys are found from the previous round keys. - for (i = ctx->Nk; i < Nb * (ctx->Nr + 1); ++i) - { + // The first round key is the key itself. + for (i = 0; i < ctx->Nk; ++i) { - k = (i - 1) * 4; - tempa[0]=RoundKey[k + 0]; - tempa[1]=RoundKey[k + 1]; - tempa[2]=RoundKey[k + 2]; - tempa[3]=RoundKey[k + 3]; - + RoundKey[(i * 4) + 0] = Key[(i * 4) + 0]; + RoundKey[(i * 4) + 1] = Key[(i * 4) + 1]; + RoundKey[(i * 4) + 2] = Key[(i * 4) + 2]; + RoundKey[(i * 4) + 3] = Key[(i * 4) + 3]; } - if (i % ctx->Nk == 0) + // All other round keys are found from the previous round keys. + for (i = ctx->Nk; i < Nb * (ctx->Nr + 1); ++i) { - // This function shifts the 4 bytes in a word to the left once. - // [a0,a1,a2,a3] becomes [a1,a2,a3,a0] - - // Function RotWord() - { - const uint8_t u8tmp = tempa[0]; - tempa[0] = tempa[1]; - tempa[1] = tempa[2]; - tempa[2] = tempa[3]; - tempa[3] = u8tmp; - } - - // SubWord() is a function that takes a four-byte input word and applies - // the S-box to each of the four bytes to produce an output word. - - // Function Subword() - { - tempa[0] = getSBoxValue(tempa[0]); - tempa[1] = getSBoxValue(tempa[1]); - tempa[2] = getSBoxValue(tempa[2]); - tempa[3] = getSBoxValue(tempa[3]); - } - - tempa[0] = tempa[0] ^ Rcon[i/ctx->Nk]; - } -#if defined(AES256) && (AES256 == 1) - if (ctx->KeyLength == 32) { - if (i % ctx->Nk == 4) - { - // Function Subword() { - tempa[0] = getSBoxValue(tempa[0]); - tempa[1] = getSBoxValue(tempa[1]); - tempa[2] = getSBoxValue(tempa[2]); - tempa[3] = getSBoxValue(tempa[3]); + k = (i - 1) * 4; + tempa[0] = RoundKey[k + 0]; + tempa[1] = RoundKey[k + 1]; + tempa[2] = RoundKey[k + 2]; + tempa[3] = RoundKey[k + 3]; + } - } + + if (i % ctx->Nk == 0) { + // This function shifts the 4 bytes in a word to the left once. + // [a0,a1,a2,a3] becomes [a1,a2,a3,a0] + + // Function RotWord() + { + const uint8_t u8tmp = tempa[0]; + tempa[0] = tempa[1]; + tempa[1] = tempa[2]; + tempa[2] = tempa[3]; + tempa[3] = u8tmp; + } + + // SubWord() is a function that takes a four-byte input word and applies + // the S-box to each of the four bytes to produce an output word. + + // Function Subword() + { + tempa[0] = getSBoxValue(tempa[0]); + tempa[1] = getSBoxValue(tempa[1]); + tempa[2] = getSBoxValue(tempa[2]); + tempa[3] = getSBoxValue(tempa[3]); + } + + tempa[0] = tempa[0] ^ Rcon[i / ctx->Nk]; + } + #if defined(AES256) && (AES256 == 1) + if (ctx->KeyLength == 32) { + if (i % ctx->Nk == 4) { + // Function Subword() + { + tempa[0] = getSBoxValue(tempa[0]); + tempa[1] = getSBoxValue(tempa[1]); + tempa[2] = getSBoxValue(tempa[2]); + tempa[3] = getSBoxValue(tempa[3]); + } + } + } + #endif + j = i * 4; + k = (i - ctx->Nk) * 4; + RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0]; + RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1]; + RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2]; + RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3]; } -#endif - j = i * 4; k=(i - ctx->Nk) * 4; - RoundKey[j + 0] = RoundKey[k + 0] ^ tempa[0]; - RoundKey[j + 1] = RoundKey[k + 1] ^ tempa[1]; - RoundKey[j + 2] = RoundKey[k + 2] ^ tempa[2]; - RoundKey[j + 3] = RoundKey[k + 3] ^ tempa[3]; - } } -void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key, uint32_t keylen) -{ - ctx->KeyLength = keylen; - switch (ctx->KeyLength) { -#if defined(AES128) && (AES128 == 1) - case 16: ctx->Nr = Nr128; ctx->Nk = Nk128; break; -#endif -#if defined(AES192) && (AES192 == 1) - case 24: ctx->Nr = Nr192; ctx->Nk = Nk192; break; -#endif -#if defined(AES256) && (AES256 == 1) - case 32: ctx->Nr = Nr256; ctx->Nk = Nk256; break; -#endif - default: ctx->Nr = 0; ctx->Nk = 0; break; - } - KeyExpansion(ctx, key); +void AES_init_ctx(struct AES_ctx *ctx, const uint8_t *key, uint32_t keylen) { + ctx->KeyLength = keylen; + switch (ctx->KeyLength) { + #if defined(AES128) && (AES128 == 1) + case 16: + ctx->Nr = Nr128; + ctx->Nk = Nk128; + break; + #endif + #if defined(AES192) && (AES192 == 1) + case 24: + ctx->Nr = Nr192; + ctx->Nk = Nk192; + break; + #endif + #if defined(AES256) && (AES256 == 1) + case 32: + ctx->Nr = Nr256; + ctx->Nk = Nk256; + break; + #endif + default: + ctx->Nr = 0; + ctx->Nk = 0; + break; + } + KeyExpansion(ctx, key); } #if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1)) -void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, uint32_t keylen, const uint8_t* iv) -{ - AES_init_ctx(ctx, key, keylen); - memcpy (ctx->Iv, iv, AES_BLOCKLEN); +void AES_init_ctx_iv(struct AES_ctx *ctx, const uint8_t *key, uint32_t keylen, const uint8_t *iv) { + AES_init_ctx(ctx, key, keylen); + memcpy(ctx->Iv, iv, AES_BLOCKLEN); } -void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv) -{ - memcpy (ctx->Iv, iv, AES_BLOCKLEN); +void AES_ctx_set_iv(struct AES_ctx *ctx, const uint8_t *iv) { + memcpy(ctx->Iv, iv, AES_BLOCKLEN); } #endif // This function adds the round key to state. The round key is added to the // state by an XOR function. -static void AddRoundKey(uint8_t round, state_t* state, const uint8_t* RoundKey) -{ - uint8_t i,j; - for (i = 0; i < 4; ++i) - { - for (j = 0; j < 4; ++j) +static void AddRoundKey(uint8_t round, state_t *state, const uint8_t *RoundKey) { + uint8_t i,j; + for (i = 0; i < 4; ++i) { - (*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j]; + for (j = 0; j < 4; ++j) + { + (*state)[i][j] ^= RoundKey[(round * Nb * 4) + (i * Nb) + j]; + } } - } } // The SubBytes Function Substitutes the values in the state matrix with values // in an S-box. -static void SubBytes(state_t* state) -{ - uint8_t i, j; - for (i = 0; i < 4; ++i) - { - for (j = 0; j < 4; ++j) +static void SubBytes(state_t *state) { + uint8_t i, j; + for (i = 0; i < 4; ++i) { - (*state)[j][i] = getSBoxValue((*state)[j][i]); + for (j = 0; j < 4; ++j) + { + (*state)[j][i] = getSBoxValue((*state)[j][i]); + } } - } } // The ShiftRows() function shifts the rows in the state to the left. Each row // is shifted with different offset. Offset = Row number. So the first row is // not shifted. -static void ShiftRows(state_t* state) -{ - uint8_t temp; +static void ShiftRows(state_t *state) { + uint8_t temp; - // Rotate first row 1 columns to left - temp = (*state)[0][1]; - (*state)[0][1] = (*state)[1][1]; - (*state)[1][1] = (*state)[2][1]; - (*state)[2][1] = (*state)[3][1]; - (*state)[3][1] = temp; + // Rotate first row 1 columns to left + temp = (*state)[0][1]; + (*state)[0][1] = (*state)[1][1]; + (*state)[1][1] = (*state)[2][1]; + (*state)[2][1] = (*state)[3][1]; + (*state)[3][1] = temp; - // Rotate second row 2 columns to left - temp = (*state)[0][2]; - (*state)[0][2] = (*state)[2][2]; - (*state)[2][2] = temp; + // Rotate second row 2 columns to left + temp = (*state)[0][2]; + (*state)[0][2] = (*state)[2][2]; + (*state)[2][2] = temp; - temp = (*state)[1][2]; - (*state)[1][2] = (*state)[3][2]; - (*state)[3][2] = temp; + temp = (*state)[1][2]; + (*state)[1][2] = (*state)[3][2]; + (*state)[3][2] = temp; - // Rotate third row 3 columns to left - temp = (*state)[0][3]; - (*state)[0][3] = (*state)[3][3]; - (*state)[3][3] = (*state)[2][3]; - (*state)[2][3] = (*state)[1][3]; - (*state)[1][3] = temp; + // Rotate third row 3 columns to left + temp = (*state)[0][3]; + (*state)[0][3] = (*state)[3][3]; + (*state)[3][3] = (*state)[2][3]; + (*state)[2][3] = (*state)[1][3]; + (*state)[1][3] = temp; } -static uint8_t xtime(uint8_t x) -{ - return ((x<<1) ^ (((x>>7) & 1) * 0x1b)); +static uint8_t xtime(uint8_t x) { + return (x << 1) ^ (((x >> 7) & 1) * 0x1b); } // MixColumns function mixes the columns of the state matrix -static void MixColumns(state_t* state) -{ - uint8_t i; - uint8_t Tmp, Tm, t; - for (i = 0; i < 4; ++i) - { - t = (*state)[i][0]; - Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3] ; - Tm = (*state)[i][0] ^ (*state)[i][1] ; Tm = xtime(Tm); (*state)[i][0] ^= Tm ^ Tmp ; - Tm = (*state)[i][1] ^ (*state)[i][2] ; Tm = xtime(Tm); (*state)[i][1] ^= Tm ^ Tmp ; - Tm = (*state)[i][2] ^ (*state)[i][3] ; Tm = xtime(Tm); (*state)[i][2] ^= Tm ^ Tmp ; - Tm = (*state)[i][3] ^ t ; Tm = xtime(Tm); (*state)[i][3] ^= Tm ^ Tmp ; - } +static void MixColumns(state_t *state) { + uint8_t i; + uint8_t Tmp, Tm, t; + for (i = 0; i < 4; ++i) + { + t = (*state)[i][0]; + Tmp = (*state)[i][0] ^ (*state)[i][1] ^ (*state)[i][2] ^ (*state)[i][3]; + Tm = (*state)[i][0] ^ (*state)[i][1]; + Tm = xtime(Tm); + (*state)[i][0] ^= Tm ^ Tmp; + Tm = (*state)[i][1] ^ (*state)[i][2]; + Tm = xtime(Tm); + (*state)[i][1] ^= Tm ^ Tmp; + Tm = (*state)[i][2] ^ (*state)[i][3]; + Tm = xtime(Tm); + (*state)[i][2] ^= Tm ^ Tmp; + Tm = (*state)[i][3] ^ t; + Tm = xtime(Tm); + (*state)[i][3] ^= Tm ^ Tmp; + } } // Multiply is used to multiply numbers in the field GF(2^8) @@ -362,21 +378,20 @@ static void MixColumns(state_t* state) // The compiler seems to be able to vectorize the operation better this way. // See https://github.com/kokke/tiny-AES-c/pull/34 #if MULTIPLY_AS_A_FUNCTION -static uint8_t Multiply(uint8_t x, uint8_t y) -{ - return (((y & 1) * x) ^ - ((y>>1 & 1) * xtime(x)) ^ - ((y>>2 & 1) * xtime(xtime(x))) ^ - ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ - ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))); /* this last call to xtime() can be omitted */ - } +static uint8_t Multiply(uint8_t x, uint8_t y) { + return ((y & 1) * x) ^ + ((y >> 1 & 1) * xtime(x)) ^ + ((y >> 2 & 1) * xtime(xtime(x))) ^ + ((y >> 3 & 1) * xtime(xtime(xtime(x)))) ^ + ((y >> 4 & 1) * xtime(xtime(xtime(xtime(x))))); /* this last call to xtime() can be omitted */ +} #else #define Multiply(x, y) \ - ( ((y & 1) * x) ^ \ - ((y>>1 & 1) * xtime(x)) ^ \ - ((y>>2 & 1) * xtime(xtime(x))) ^ \ - ((y>>3 & 1) * xtime(xtime(xtime(x)))) ^ \ - ((y>>4 & 1) * xtime(xtime(xtime(xtime(x)))))) \ + (((y & 1) * x) ^ \ + ((y >> 1 & 1) * xtime(x)) ^ \ + ((y >> 2 & 1) * xtime(xtime(x))) ^ \ + ((y >> 3 & 1) * xtime(xtime(xtime(x)))) ^ \ + ((y >> 4 & 1) * xtime(xtime(xtime(xtime(x)))))) \ #endif @@ -384,114 +399,109 @@ static uint8_t Multiply(uint8_t x, uint8_t y) // MixColumns function mixes the columns of the state matrix. The method used to // multiply may be difficult to understand for the inexperienced. Please use the // references to gain more information. -static void InvMixColumns(state_t* state) -{ - int i; - uint8_t a, b, c, d; - for (i = 0; i < 4; ++i) - { - a = (*state)[i][0]; - b = (*state)[i][1]; - c = (*state)[i][2]; - d = (*state)[i][3]; +static void InvMixColumns(state_t *state) { + int i; + uint8_t a, b, c, d; + for (i = 0; i < 4; ++i) + { + a = (*state)[i][0]; + b = (*state)[i][1]; + c = (*state)[i][2]; + d = (*state)[i][3]; - (*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09); - (*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d); - (*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b); - (*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e); - } + (*state)[i][0] = Multiply(a, 0x0e) ^ Multiply(b, 0x0b) ^ Multiply(c, 0x0d) ^ Multiply(d, 0x09); + (*state)[i][1] = Multiply(a, 0x09) ^ Multiply(b, 0x0e) ^ Multiply(c, 0x0b) ^ Multiply(d, 0x0d); + (*state)[i][2] = Multiply(a, 0x0d) ^ Multiply(b, 0x09) ^ Multiply(c, 0x0e) ^ Multiply(d, 0x0b); + (*state)[i][3] = Multiply(a, 0x0b) ^ Multiply(b, 0x0d) ^ Multiply(c, 0x09) ^ Multiply(d, 0x0e); + } } // The SubBytes Function Substitutes the values in the state matrix with values // in an S-box. -static void InvSubBytes(state_t* state) -{ - uint8_t i, j; - for (i = 0; i < 4; ++i) - { - for (j = 0; j < 4; ++j) +static void InvSubBytes(state_t *state) { + uint8_t i, j; + for (i = 0; i < 4; ++i) { - (*state)[j][i] = getSBoxInvert((*state)[j][i]); + for (j = 0; j < 4; ++j) + { + (*state)[j][i] = getSBoxInvert((*state)[j][i]); + } } - } } -static void InvShiftRows(state_t* state) -{ - uint8_t temp; +static void InvShiftRows(state_t *state) { + uint8_t temp; - // Rotate first row 1 columns to right - temp = (*state)[3][1]; - (*state)[3][1] = (*state)[2][1]; - (*state)[2][1] = (*state)[1][1]; - (*state)[1][1] = (*state)[0][1]; - (*state)[0][1] = temp; + // Rotate first row 1 columns to right + temp = (*state)[3][1]; + (*state)[3][1] = (*state)[2][1]; + (*state)[2][1] = (*state)[1][1]; + (*state)[1][1] = (*state)[0][1]; + (*state)[0][1] = temp; - // Rotate second row 2 columns to right - temp = (*state)[0][2]; - (*state)[0][2] = (*state)[2][2]; - (*state)[2][2] = temp; + // Rotate second row 2 columns to right + temp = (*state)[0][2]; + (*state)[0][2] = (*state)[2][2]; + (*state)[2][2] = temp; - temp = (*state)[1][2]; - (*state)[1][2] = (*state)[3][2]; - (*state)[3][2] = temp; + temp = (*state)[1][2]; + (*state)[1][2] = (*state)[3][2]; + (*state)[3][2] = temp; - // Rotate third row 3 columns to right - temp = (*state)[0][3]; - (*state)[0][3] = (*state)[1][3]; - (*state)[1][3] = (*state)[2][3]; - (*state)[2][3] = (*state)[3][3]; - (*state)[3][3] = temp; + // Rotate third row 3 columns to right + temp = (*state)[0][3]; + (*state)[0][3] = (*state)[1][3]; + (*state)[1][3] = (*state)[2][3]; + (*state)[2][3] = (*state)[3][3]; + (*state)[3][3] = temp; } #endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1) // Cipher is the main function that encrypts the PlainText. -static void Cipher(state_t* state, const struct AES_ctx* ctx) -{ - const uint8_t* RoundKey = GetRoundKey(ctx); - uint8_t round = 0; +static void Cipher(state_t *state, const struct AES_ctx *ctx) { + const uint8_t *RoundKey = GetRoundKey(ctx); + uint8_t round = 0; - // Add the First round key to the state before starting the rounds. - AddRoundKey(0, state, RoundKey); + // Add the First round key to the state before starting the rounds. + AddRoundKey(0, state, RoundKey); - // There will be Nr rounds. The first Nr-1 rounds are identical. These Nr - // rounds are executed in the loop below. Last one without MixColumns() - for (round = 1; ; ++round) - { - SubBytes(state); - ShiftRows(state); - if (round == ctx->Nr) { - break; + // There will be Nr rounds. The first Nr-1 rounds are identical. These Nr + // rounds are executed in the loop below. Last one without MixColumns() + for (round = 1; ; ++round) + { + SubBytes(state); + ShiftRows(state); + if (round == ctx->Nr) { + break; + } + MixColumns(state); + AddRoundKey(round, state, RoundKey); } - MixColumns(state); - AddRoundKey(round, state, RoundKey); - } - // Add round key to last round - AddRoundKey(ctx->Nr, state, RoundKey); + // Add round key to last round + AddRoundKey(ctx->Nr, state, RoundKey); } #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1) -static void InvCipher(state_t* state, const struct AES_ctx* ctx) -{ - const uint8_t* RoundKey = GetRoundKey(ctx); - uint8_t round = 0; +static void InvCipher(state_t *state, const struct AES_ctx *ctx) { + const uint8_t *RoundKey = GetRoundKey(ctx); + uint8_t round = 0; - // Add the First round key to the state before starting the rounds. - AddRoundKey(ctx->Nr, state, RoundKey); + // Add the First round key to the state before starting the rounds. + AddRoundKey(ctx->Nr, state, RoundKey); - // There will be Nr rounds. The first Nr-1 rounds are identical. These Nr - // rounds are executed in the loop below. Last one without InvMixColumn() - for (round = (ctx->Nr - 1); ; --round) - { - InvShiftRows(state); - InvSubBytes(state); - AddRoundKey(round, state, RoundKey); - if (round == 0) { - break; + // There will be Nr rounds. The first Nr-1 rounds are identical. These Nr + // rounds are executed in the loop below. Last one without InvMixColumn() + for (round = (ctx->Nr - 1); ; --round) + { + InvShiftRows(state); + InvSubBytes(state); + AddRoundKey(round, state, RoundKey); + if (round == 0) { + break; + } + InvMixColumns(state); } - InvMixColumns(state); - } } #endif // #if (defined(CBC) && CBC == 1) || (defined(ECB) && ECB == 1) @@ -502,18 +512,16 @@ static void InvCipher(state_t* state, const struct AES_ctx* ctx) #if defined(ECB) && (ECB == 1) -void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf) -{ - // The next function call encrypts the PlainText with the Key using AES - // algorithm. - Cipher((state_t*)buf, ctx); +void AES_ECB_encrypt(const struct AES_ctx *ctx, uint8_t *buf) { + // The next function call encrypts the PlainText with the Key using AES + // algorithm. + Cipher((state_t *)buf, ctx); } -void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf) -{ - // The next function call decrypts the PlainText with the Key using AES - // algorithm. - InvCipher((state_t*)buf, ctx); +void AES_ECB_decrypt(const struct AES_ctx *ctx, uint8_t *buf) { + // The next function call decrypts the PlainText with the Key using AES + // algorithm. + InvCipher((state_t *)buf, ctx); } @@ -526,42 +534,39 @@ void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf) #if defined(CBC) && (CBC == 1) -static void XorWithIv(uint8_t* buf, const uint8_t* Iv) -{ - uint8_t i; - for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size - { - buf[i] ^= Iv[i]; - } +static void XorWithIv(uint8_t *buf, const uint8_t *Iv) { + uint8_t i; + for (i = 0; i < AES_BLOCKLEN; ++i) // The block in AES is always 128bit no matter the key size + { + buf[i] ^= Iv[i]; + } } -void AES_CBC_encrypt_buffer(struct AES_ctx *ctx, uint8_t* buf, uint32_t length) -{ - uintptr_t i; - uint8_t *Iv = ctx->Iv; - for (i = 0; i < length; i += AES_BLOCKLEN) - { - XorWithIv(buf, Iv); - Cipher((state_t*)buf, ctx); - Iv = buf; - buf += AES_BLOCKLEN; - } - /* store Iv in ctx for next call */ - memcpy(ctx->Iv, Iv, AES_BLOCKLEN); +void AES_CBC_encrypt_buffer(struct AES_ctx *ctx, uint8_t *buf, uint32_t length) { + uintptr_t i; + uint8_t *Iv = ctx->Iv; + for (i = 0; i < length; i += AES_BLOCKLEN) + { + XorWithIv(buf, Iv); + Cipher((state_t *)buf, ctx); + Iv = buf; + buf += AES_BLOCKLEN; + } + /* store Iv in ctx for next call */ + memcpy(ctx->Iv, Iv, AES_BLOCKLEN); } -void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length) -{ - uintptr_t i; - uint8_t storeNextIv[AES_BLOCKLEN]; - for (i = 0; i < length; i += AES_BLOCKLEN) - { - memcpy(storeNextIv, buf, AES_BLOCKLEN); - InvCipher((state_t*)buf, ctx); - XorWithIv(buf, ctx->Iv); - memcpy(ctx->Iv, storeNextIv, AES_BLOCKLEN); - buf += AES_BLOCKLEN; - } +void AES_CBC_decrypt_buffer(struct AES_ctx *ctx, uint8_t *buf, uint32_t length) { + uintptr_t i; + uint8_t storeNextIv[AES_BLOCKLEN]; + for (i = 0; i < length; i += AES_BLOCKLEN) + { + memcpy(storeNextIv, buf, AES_BLOCKLEN); + InvCipher((state_t *)buf, ctx); + XorWithIv(buf, ctx->Iv); + memcpy(ctx->Iv, storeNextIv, AES_BLOCKLEN); + buf += AES_BLOCKLEN; + } } @@ -573,36 +578,33 @@ void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length) /* Symmetrical operation: same function for encrypting as for decrypting. Note any IV/nonce should never be reused with the same key */ -void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length) -{ - uint8_t buffer[AES_BLOCKLEN]; +void AES_CTR_xcrypt_buffer(struct AES_ctx *ctx, uint8_t *buf, uint32_t length) { + uint8_t buffer[AES_BLOCKLEN]; - unsigned i; - int bi; - for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi) - { - if (bi == AES_BLOCKLEN) /* we need to regen xor compliment in buffer */ + unsigned i; + int bi; + for (i = 0, bi = AES_BLOCKLEN; i < length; ++i, ++bi) { - memcpy(buffer, ctx->Iv, AES_BLOCKLEN); - Cipher((state_t*)buffer, ctx); + if (bi == AES_BLOCKLEN) { /* we need to regen xor compliment in buffer */ + memcpy(buffer, ctx->Iv, AES_BLOCKLEN); + Cipher((state_t *)buffer, ctx); - /* Increment Iv and handle overflow */ - for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi) - { - /* inc will overflow */ - if (ctx->Iv[bi] == 255) - { - ctx->Iv[bi] = 0; - continue; + /* Increment Iv and handle overflow */ + for (bi = (AES_BLOCKLEN - 1); bi >= 0; --bi) + { + /* inc will overflow */ + if (ctx->Iv[bi] == 255) { + ctx->Iv[bi] = 0; + continue; + } + ctx->Iv[bi] += 1; + break; + } + bi = 0; } - ctx->Iv[bi] += 1; - break; - } - bi = 0; - } - buf[i] = (buf[i] ^ buffer[bi]); - } + buf[i] = (buf[i] ^ buffer[bi]); + } } #endif // #if defined(CTR) && (CTR == 1) diff --git a/shared-module/aesio/aes.h b/shared-module/aesio/aes.h index a87fa5be75..92539f1dab 100644 --- a/shared-module/aesio/aes.h +++ b/shared-module/aesio/aes.h @@ -44,37 +44,37 @@ struct AES_ctx { - union { -#if defined(AES256) && (AES256 == 1) - uint8_t RoundKey256[AES_keyExpSize256]; -#endif -#if defined(AES192) && (AES192 == 1) - uint8_t RoundKey192[AES_keyExpSize192]; -#endif -#if defined(AES128) && (AES128 == 1) - uint8_t RoundKey128[AES_keyExpSize128]; -#endif - }; -#if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1)) - uint8_t Iv[AES_BLOCKLEN]; -#endif - uint32_t KeyLength; - uint8_t Nr; - uint8_t Nk; + union { + #if defined(AES256) && (AES256 == 1) + uint8_t RoundKey256[AES_keyExpSize256]; + #endif + #if defined(AES192) && (AES192 == 1) + uint8_t RoundKey192[AES_keyExpSize192]; + #endif + #if defined(AES128) && (AES128 == 1) + uint8_t RoundKey128[AES_keyExpSize128]; + #endif + }; + #if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1)) + uint8_t Iv[AES_BLOCKLEN]; + #endif + uint32_t KeyLength; + uint8_t Nr; + uint8_t Nk; }; -void AES_init_ctx(struct AES_ctx* ctx, const uint8_t* key, uint32_t keylen); +void AES_init_ctx(struct AES_ctx *ctx, const uint8_t *key, uint32_t keylen); #if (defined(CBC) && (CBC == 1)) || (defined(CTR) && (CTR == 1)) -void AES_init_ctx_iv(struct AES_ctx* ctx, const uint8_t* key, uint32_t keylen, const uint8_t* iv); -void AES_ctx_set_iv(struct AES_ctx* ctx, const uint8_t* iv); +void AES_init_ctx_iv(struct AES_ctx *ctx, const uint8_t *key, uint32_t keylen, const uint8_t *iv); +void AES_ctx_set_iv(struct AES_ctx *ctx, const uint8_t *iv); #endif #if defined(ECB) && (ECB == 1) // buffer size is exactly AES_BLOCKLEN bytes; // you need only AES_init_ctx as IV is not used in ECB // NB: ECB is considered insecure for most uses -void AES_ECB_encrypt(const struct AES_ctx* ctx, uint8_t* buf); -void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf); +void AES_ECB_encrypt(const struct AES_ctx *ctx, uint8_t *buf); +void AES_ECB_decrypt(const struct AES_ctx *ctx, uint8_t *buf); #endif // #if defined(ECB) && (ECB == !) @@ -84,8 +84,8 @@ void AES_ECB_decrypt(const struct AES_ctx* ctx, uint8_t* buf); // Suggest https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme // NOTES: you need to set IV in ctx via AES_init_ctx_iv() or AES_ctx_set_iv() // no IV should ever be reused with the same key -void AES_CBC_encrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length); -void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length); +void AES_CBC_encrypt_buffer(struct AES_ctx *ctx, uint8_t *buf, uint32_t length); +void AES_CBC_decrypt_buffer(struct AES_ctx *ctx, uint8_t *buf, uint32_t length); #endif // #if defined(CBC) && (CBC == 1) @@ -97,7 +97,7 @@ void AES_CBC_decrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length); // Suggesting https://en.wikipedia.org/wiki/Padding_(cryptography)#PKCS7 for padding scheme // NOTES: you need to set IV in ctx with AES_init_ctx_iv() or AES_ctx_set_iv() // no IV should ever be reused with the same key -void AES_CTR_xcrypt_buffer(struct AES_ctx* ctx, uint8_t* buf, uint32_t length); +void AES_CTR_xcrypt_buffer(struct AES_ctx *ctx, uint8_t *buf, uint32_t length); #endif // #if defined(CTR) && (CTR == 1) diff --git a/shared-module/audiocore/RawSample.c b/shared-module/audiocore/RawSample.c index 316a1c69f6..1f1db0a509 100644 --- a/shared-module/audiocore/RawSample.c +++ b/shared-module/audiocore/RawSample.c @@ -30,13 +30,13 @@ #include "shared-module/audiocore/RawSample.h" -void common_hal_audioio_rawsample_construct(audioio_rawsample_obj_t* self, - uint8_t* buffer, - uint32_t len, - uint8_t bytes_per_sample, - bool samples_signed, - uint8_t channel_count, - uint32_t sample_rate) { +void common_hal_audioio_rawsample_construct(audioio_rawsample_obj_t *self, + uint8_t *buffer, + uint32_t len, + uint8_t bytes_per_sample, + bool samples_signed, + uint8_t channel_count, + uint32_t sample_rate) { self->buffer = buffer; self->bits_per_sample = bytes_per_sample * 8; self->samples_signed = samples_signed; @@ -45,37 +45,37 @@ void common_hal_audioio_rawsample_construct(audioio_rawsample_obj_t* self, self->sample_rate = sample_rate; } -void common_hal_audioio_rawsample_deinit(audioio_rawsample_obj_t* self) { +void common_hal_audioio_rawsample_deinit(audioio_rawsample_obj_t *self) { self->buffer = NULL; } -bool common_hal_audioio_rawsample_deinited(audioio_rawsample_obj_t* self) { +bool common_hal_audioio_rawsample_deinited(audioio_rawsample_obj_t *self) { return self->buffer == NULL; } -uint32_t common_hal_audioio_rawsample_get_sample_rate(audioio_rawsample_obj_t* self) { +uint32_t common_hal_audioio_rawsample_get_sample_rate(audioio_rawsample_obj_t *self) { return self->sample_rate; } -void common_hal_audioio_rawsample_set_sample_rate(audioio_rawsample_obj_t* self, - uint32_t sample_rate) { +void common_hal_audioio_rawsample_set_sample_rate(audioio_rawsample_obj_t *self, + uint32_t sample_rate) { self->sample_rate = sample_rate; } -uint8_t common_hal_audioio_rawsample_get_bits_per_sample(audioio_rawsample_obj_t* self) { +uint8_t common_hal_audioio_rawsample_get_bits_per_sample(audioio_rawsample_obj_t *self) { return self->bits_per_sample; } -uint8_t common_hal_audioio_rawsample_get_channel_count(audioio_rawsample_obj_t* self) { +uint8_t common_hal_audioio_rawsample_get_channel_count(audioio_rawsample_obj_t *self) { return self->channel_count; } -void audioio_rawsample_reset_buffer(audioio_rawsample_obj_t* self, - bool single_channel, - uint8_t channel) { +void audioio_rawsample_reset_buffer(audioio_rawsample_obj_t *self, + bool single_channel, + uint8_t channel) { } -audioio_get_buffer_result_t audioio_rawsample_get_buffer(audioio_rawsample_obj_t* self, - bool single_channel, - uint8_t channel, - uint8_t** buffer, - uint32_t* buffer_length) { +audioio_get_buffer_result_t audioio_rawsample_get_buffer(audioio_rawsample_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length) { *buffer_length = self->len; if (single_channel) { *buffer = self->buffer + (channel % self->channel_count) * (self->bits_per_sample / 8); @@ -85,9 +85,9 @@ audioio_get_buffer_result_t audioio_rawsample_get_buffer(audioio_rawsample_obj_t return GET_BUFFER_DONE; } -void audioio_rawsample_get_buffer_structure(audioio_rawsample_obj_t* self, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing) { +void audioio_rawsample_get_buffer_structure(audioio_rawsample_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing) { *single_buffer = true; *samples_signed = self->samples_signed; *max_buffer_length = self->len; diff --git a/shared-module/audiocore/RawSample.h b/shared-module/audiocore/RawSample.h index 2ea8c89f43..8208b4c280 100644 --- a/shared-module/audiocore/RawSample.h +++ b/shared-module/audiocore/RawSample.h @@ -33,7 +33,7 @@ typedef struct { mp_obj_base_t base; - uint8_t* buffer; + uint8_t *buffer; uint32_t len; uint8_t bits_per_sample; bool samples_signed; @@ -43,16 +43,16 @@ typedef struct { // These are not available from Python because it may be called in an interrupt. -void audioio_rawsample_reset_buffer(audioio_rawsample_obj_t* self, - bool single_channel, - uint8_t channel); -audioio_get_buffer_result_t audioio_rawsample_get_buffer(audioio_rawsample_obj_t* self, - bool single_channel, - uint8_t channel, - uint8_t** buffer, - uint32_t* buffer_length); // length in bytes -void audioio_rawsample_get_buffer_structure(audioio_rawsample_obj_t* self, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing); +void audioio_rawsample_reset_buffer(audioio_rawsample_obj_t *self, + bool single_channel, + uint8_t channel); +audioio_get_buffer_result_t audioio_rawsample_get_buffer(audioio_rawsample_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes +void audioio_rawsample_get_buffer_structure(audioio_rawsample_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing); #endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_RAWSAMPLE_H diff --git a/shared-module/audiocore/WaveFile.c b/shared-module/audiocore/WaveFile.c index 0248d42e22..4864004d52 100644 --- a/shared-module/audiocore/WaveFile.c +++ b/shared-module/audiocore/WaveFile.c @@ -45,10 +45,10 @@ struct wave_format_chunk { uint16_t extra_params; // Assumed to be zero below. }; -void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t* self, - pyb_file_obj_t* file, - uint8_t *buffer, - size_t buffer_size) { +void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t *self, + pyb_file_obj_t *file, + uint8_t *buffer, + size_t buffer_size) { // Load the wave self->file = file; uint8_t chunk_header[16]; @@ -96,7 +96,7 @@ void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t* self, mp_raise_OSError(MP_EIO); } if (bytes_read != 4 || - memcmp((uint8_t *) data_tag, "data", 4) != 0) { + memcmp((uint8_t *)data_tag, "data", 4) != 0) { mp_raise_ValueError(translate("Data chunk must follow fmt chunk")); } @@ -122,55 +122,55 @@ void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t* self, if (self->buffer == NULL) { common_hal_audioio_wavefile_deinit(self); mp_raise_msg(&mp_type_MemoryError, - translate("Couldn't allocate first buffer")); + translate("Couldn't allocate first buffer")); } self->second_buffer = m_malloc(self->len, false); if (self->second_buffer == NULL) { common_hal_audioio_wavefile_deinit(self); mp_raise_msg(&mp_type_MemoryError, - translate("Couldn't allocate second buffer")); + translate("Couldn't allocate second buffer")); } } } -void common_hal_audioio_wavefile_deinit(audioio_wavefile_obj_t* self) { +void common_hal_audioio_wavefile_deinit(audioio_wavefile_obj_t *self) { self->buffer = NULL; self->second_buffer = NULL; } -bool common_hal_audioio_wavefile_deinited(audioio_wavefile_obj_t* self) { +bool common_hal_audioio_wavefile_deinited(audioio_wavefile_obj_t *self) { return self->buffer == NULL; } -uint32_t common_hal_audioio_wavefile_get_sample_rate(audioio_wavefile_obj_t* self) { +uint32_t common_hal_audioio_wavefile_get_sample_rate(audioio_wavefile_obj_t *self) { return self->sample_rate; } -void common_hal_audioio_wavefile_set_sample_rate(audioio_wavefile_obj_t* self, - uint32_t sample_rate) { +void common_hal_audioio_wavefile_set_sample_rate(audioio_wavefile_obj_t *self, + uint32_t sample_rate) { self->sample_rate = sample_rate; } -uint8_t common_hal_audioio_wavefile_get_bits_per_sample(audioio_wavefile_obj_t* self) { +uint8_t common_hal_audioio_wavefile_get_bits_per_sample(audioio_wavefile_obj_t *self) { return self->bits_per_sample; } -uint8_t common_hal_audioio_wavefile_get_channel_count(audioio_wavefile_obj_t* self) { +uint8_t common_hal_audioio_wavefile_get_channel_count(audioio_wavefile_obj_t *self) { return self->channel_count; } -bool audioio_wavefile_samples_signed(audioio_wavefile_obj_t* self) { +bool audioio_wavefile_samples_signed(audioio_wavefile_obj_t *self) { return self->bits_per_sample > 8; } -uint32_t audioio_wavefile_max_buffer_length(audioio_wavefile_obj_t* self) { +uint32_t audioio_wavefile_max_buffer_length(audioio_wavefile_obj_t *self) { return 512; } -void audioio_wavefile_reset_buffer(audioio_wavefile_obj_t* self, - bool single_channel, - uint8_t channel) { +void audioio_wavefile_reset_buffer(audioio_wavefile_obj_t *self, + bool single_channel, + uint8_t channel) { if (single_channel && channel == 1) { return; } @@ -183,11 +183,11 @@ void audioio_wavefile_reset_buffer(audioio_wavefile_obj_t* self, self->right_read_count = 0; } -audioio_get_buffer_result_t audioio_wavefile_get_buffer(audioio_wavefile_obj_t* self, - bool single_channel, - uint8_t channel, - uint8_t** buffer, - uint32_t* buffer_length) { +audioio_get_buffer_result_t audioio_wavefile_get_buffer(audioio_wavefile_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length) { if (!single_channel) { channel = 0; } @@ -226,13 +226,13 @@ audioio_get_buffer_result_t audioio_wavefile_get_buffer(audioio_wavefile_obj_t* length_read += pad; if (self->bits_per_sample == 8) { for (uint32_t i = 0; i < pad; i++) { - ((uint8_t*) (*buffer))[length_read / sizeof(uint8_t) - i - 1] = 0x80; + ((uint8_t *)(*buffer))[length_read / sizeof(uint8_t) - i - 1] = 0x80; } } else if (self->bits_per_sample == 16) { // We know the buffer is aligned because we allocated it onto the heap ourselves. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" - ((int16_t*) (*buffer))[length_read / sizeof(int16_t) - 1] = 0; + ((int16_t *)(*buffer))[length_read / sizeof(int16_t) - 1] = 0; #pragma GCC diagnostic pop } } @@ -265,9 +265,9 @@ audioio_get_buffer_result_t audioio_wavefile_get_buffer(audioio_wavefile_obj_t* return self->bytes_remaining == 0 ? GET_BUFFER_DONE : GET_BUFFER_MORE_DATA; } -void audioio_wavefile_get_buffer_structure(audioio_wavefile_obj_t* self, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing) { +void audioio_wavefile_get_buffer_structure(audioio_wavefile_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing) { *single_buffer = false; *samples_signed = self->bits_per_sample > 8; *max_buffer_length = 512; diff --git a/shared-module/audiocore/WaveFile.h b/shared-module/audiocore/WaveFile.h index 3eecbf15ce..80b2fd3a56 100644 --- a/shared-module/audiocore/WaveFile.h +++ b/shared-module/audiocore/WaveFile.h @@ -34,9 +34,9 @@ typedef struct { mp_obj_base_t base; - uint8_t* buffer; + uint8_t *buffer; uint32_t buffer_length; - uint8_t* second_buffer; + uint8_t *second_buffer; uint32_t second_buffer_length; uint32_t file_length; // In bytes uint16_t data_start; // Where the data values start @@ -48,7 +48,7 @@ typedef struct { uint32_t sample_rate; uint32_t len; - pyb_file_obj_t* file; + pyb_file_obj_t *file; uint32_t read_count; uint32_t left_read_count; @@ -56,16 +56,16 @@ typedef struct { } audioio_wavefile_obj_t; // These are not available from Python because it may be called in an interrupt. -void audioio_wavefile_reset_buffer(audioio_wavefile_obj_t* self, - bool single_channel, - uint8_t channel); -audioio_get_buffer_result_t audioio_wavefile_get_buffer(audioio_wavefile_obj_t* self, - bool single_channel, - uint8_t channel, - uint8_t** buffer, - uint32_t* buffer_length); // length in bytes -void audioio_wavefile_get_buffer_structure(audioio_wavefile_obj_t* self, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing); +void audioio_wavefile_reset_buffer(audioio_wavefile_obj_t *self, + bool single_channel, + uint8_t channel); +audioio_get_buffer_result_t audioio_wavefile_get_buffer(audioio_wavefile_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes +void audioio_wavefile_get_buffer_structure(audioio_wavefile_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing); #endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_WAVEFILE_H diff --git a/shared-module/audiocore/__init__.c b/shared-module/audiocore/__init__.c index 7bdfe460ce..605eac70b9 100644 --- a/shared-module/audiocore/__init__.c +++ b/shared-module/audiocore/__init__.c @@ -56,23 +56,23 @@ void audiosample_reset_buffer(mp_obj_t sample_obj, bool single_channel, uint8_t } audioio_get_buffer_result_t audiosample_get_buffer(mp_obj_t sample_obj, - bool single_channel, - uint8_t channel, - uint8_t** buffer, uint32_t* buffer_length) { + bool single_channel, + uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj); return proto->get_buffer(MP_OBJ_TO_PTR(sample_obj), single_channel, channel, buffer, buffer_length); } void audiosample_get_buffer_structure(mp_obj_t sample_obj, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing) { + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing) { const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj); proto->get_buffer_structure(MP_OBJ_TO_PTR(sample_obj), single_channel, single_buffer, samples_signed, max_buffer_length, spacing); } void audiosample_convert_u8m_s16s(int16_t *buffer_out, const uint8_t *buffer_in, size_t nframes) { - for(;nframes--;) { + for (; nframes--;) { int16_t sample = (*buffer_in++ - 0x80) << 8; *buffer_out++ = sample; *buffer_out++ = sample; @@ -81,15 +81,15 @@ void audiosample_convert_u8m_s16s(int16_t *buffer_out, const uint8_t *buffer_in, void audiosample_convert_u8s_s16s(int16_t *buffer_out, const uint8_t *buffer_in, size_t nframes) { - size_t nsamples = 2*nframes; - for(;nsamples--;) { + size_t nsamples = 2 * nframes; + for (; nsamples--;) { int16_t sample = (*buffer_in++ - 0x80) << 8; *buffer_out++ = sample; } } void audiosample_convert_s8m_s16s(int16_t *buffer_out, const int8_t *buffer_in, size_t nframes) { - for(;nframes--;) { + for (; nframes--;) { int16_t sample = (*buffer_in++) << 8; *buffer_out++ = sample; *buffer_out++ = sample; @@ -98,8 +98,8 @@ void audiosample_convert_s8m_s16s(int16_t *buffer_out, const int8_t *buffer_in, void audiosample_convert_s8s_s16s(int16_t *buffer_out, const int8_t *buffer_in, size_t nframes) { - size_t nsamples = 2*nframes; - for(;nsamples--;) { + size_t nsamples = 2 * nframes; + for (; nsamples--;) { int16_t sample = (*buffer_in++) << 8; *buffer_out++ = sample; } @@ -107,7 +107,7 @@ void audiosample_convert_s8s_s16s(int16_t *buffer_out, const int8_t *buffer_in, void audiosample_convert_u16m_s16s(int16_t *buffer_out, const uint16_t *buffer_in, size_t nframes) { - for(;nframes--;) { + for (; nframes--;) { int16_t sample = *buffer_in++ - 0x8000; *buffer_out++ = sample; *buffer_out++ = sample; @@ -116,15 +116,15 @@ void audiosample_convert_u16m_s16s(int16_t *buffer_out, const uint16_t *buffer_i void audiosample_convert_u16s_s16s(int16_t *buffer_out, const uint16_t *buffer_in, size_t nframes) { - size_t nsamples = 2*nframes; - for(;nsamples--;) { + size_t nsamples = 2 * nframes; + for (; nsamples--;) { int16_t sample = *buffer_in++ - 0x8000; *buffer_out++ = sample; } } void audiosample_convert_s16m_s16s(int16_t *buffer_out, const int16_t *buffer_in, size_t nframes) { - for(;nframes--;) { + for (; nframes--;) { int16_t sample = *buffer_in++; *buffer_out++ = sample; *buffer_out++ = sample; diff --git a/shared-module/audiocore/__init__.h b/shared-module/audiocore/__init__.h index ec2cf1cfab..69955a25f7 100644 --- a/shared-module/audiocore/__init__.h +++ b/shared-module/audiocore/__init__.h @@ -43,14 +43,14 @@ typedef uint32_t (*audiosample_sample_rate_fun)(mp_obj_t); typedef uint8_t (*audiosample_bits_per_sample_fun)(mp_obj_t); typedef uint8_t (*audiosample_channel_count_fun)(mp_obj_t); typedef void (*audiosample_reset_buffer_fun)(mp_obj_t, - bool single_channel, uint8_t audio_channel); + bool single_channel, uint8_t audio_channel); typedef audioio_get_buffer_result_t (*audiosample_get_buffer_fun)(mp_obj_t, - bool single_channel, uint8_t channel, uint8_t** buffer, - uint32_t* buffer_length); + bool single_channel, uint8_t channel, uint8_t **buffer, + uint32_t *buffer_length); typedef void (*audiosample_get_buffer_structure_fun)(mp_obj_t, - bool single_channel, bool* single_buffer, - bool* samples_signed, uint32_t *max_buffer_length, - uint8_t* spacing); + bool single_channel, bool *single_buffer, + bool *samples_signed, uint32_t *max_buffer_length, + uint8_t *spacing); typedef struct _audiosample_p_t { MP_PROTOCOL_HEAD // MP_QSTR_protocol_audiosample @@ -67,12 +67,12 @@ uint8_t audiosample_bits_per_sample(mp_obj_t sample_obj); uint8_t audiosample_channel_count(mp_obj_t sample_obj); void audiosample_reset_buffer(mp_obj_t sample_obj, bool single_channel, uint8_t audio_channel); audioio_get_buffer_result_t audiosample_get_buffer(mp_obj_t sample_obj, - bool single_channel, - uint8_t channel, - uint8_t** buffer, uint32_t* buffer_length); + bool single_channel, + uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length); void audiosample_get_buffer_structure(mp_obj_t sample_obj, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing); + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing); void audiosample_convert_u8m_s16s(int16_t *buffer_out, const uint8_t *buffer_in, size_t nframes); void audiosample_convert_u8s_s16s(int16_t *buffer_out, const uint8_t *buffer_in, size_t nframes); diff --git a/shared-module/audiomixer/Mixer.c b/shared-module/audiomixer/Mixer.c index 6c1ba1973e..fdcd2dbfbf 100644 --- a/shared-module/audiomixer/Mixer.c +++ b/shared-module/audiomixer/Mixer.c @@ -35,13 +35,13 @@ #include "shared-module/audiocore/__init__.h" #include "shared-module/audiocore/RawSample.h" -void common_hal_audiomixer_mixer_construct(audiomixer_mixer_obj_t* self, - uint8_t voice_count, - uint32_t buffer_size, - uint8_t bits_per_sample, - bool samples_signed, - uint8_t channel_count, - uint32_t sample_rate) { +void common_hal_audiomixer_mixer_construct(audiomixer_mixer_obj_t *self, + uint8_t voice_count, + uint32_t buffer_size, + uint8_t bits_per_sample, + bool samples_signed, + uint8_t channel_count, + uint32_t sample_rate) { self->len = buffer_size / 2 / sizeof(uint32_t) * sizeof(uint32_t); self->first_buffer = m_malloc(self->len, false); @@ -63,28 +63,28 @@ void common_hal_audiomixer_mixer_construct(audiomixer_mixer_obj_t* self, self->voice_count = voice_count; } -void common_hal_audiomixer_mixer_deinit(audiomixer_mixer_obj_t* self) { +void common_hal_audiomixer_mixer_deinit(audiomixer_mixer_obj_t *self) { self->first_buffer = NULL; self->second_buffer = NULL; } -bool common_hal_audiomixer_mixer_deinited(audiomixer_mixer_obj_t* self) { +bool common_hal_audiomixer_mixer_deinited(audiomixer_mixer_obj_t *self) { return self->first_buffer == NULL; } -uint32_t common_hal_audiomixer_mixer_get_sample_rate(audiomixer_mixer_obj_t* self) { +uint32_t common_hal_audiomixer_mixer_get_sample_rate(audiomixer_mixer_obj_t *self) { return self->sample_rate; } -uint8_t common_hal_audiomixer_mixer_get_channel_count(audiomixer_mixer_obj_t* self) { +uint8_t common_hal_audiomixer_mixer_get_channel_count(audiomixer_mixer_obj_t *self) { return self->channel_count; } -uint8_t common_hal_audiomixer_mixer_get_bits_per_sample(audiomixer_mixer_obj_t* self) { +uint8_t common_hal_audiomixer_mixer_get_bits_per_sample(audiomixer_mixer_obj_t *self) { return self->bits_per_sample; } -bool common_hal_audiomixer_mixer_get_playing(audiomixer_mixer_obj_t* self) { +bool common_hal_audiomixer_mixer_get_playing(audiomixer_mixer_obj_t *self) { for (uint8_t v = 0; v < self->voice_count; v++) { if (common_hal_audiomixer_mixervoice_get_playing(MP_OBJ_TO_PTR(self->voice[v]))) { return true; @@ -93,9 +93,9 @@ bool common_hal_audiomixer_mixer_get_playing(audiomixer_mixer_obj_t* self) { return false; } -void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t* self, - bool single_channel, - uint8_t channel) { +void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t *self, + bool single_channel, + uint8_t channel) { for (uint8_t i = 0; i < self->voice_count; i++) { common_hal_audiomixer_mixervoice_stop(self->voice[i]); } @@ -112,11 +112,11 @@ static inline uint32_t mult16signed(uint32_t val, int32_t mul) { int32_t hi, lo; enum { bits = 16 }; // saturate to 16 bits enum { shift = 15 }; // shift is done automatically - asm volatile("smulwb %0, %1, %2" : "=r" (lo) : "r" (mul), "r" (val)); - asm volatile("smulwt %0, %1, %2" : "=r" (hi) : "r" (mul), "r" (val)); - asm volatile("ssat %0, %1, %2, asr %3" : "=r" (lo) : "I" (bits), "r" (lo), "I" (shift)); - asm volatile("ssat %0, %1, %2, asr %3" : "=r" (hi) : "I" (bits), "r" (hi), "I" (shift)); - asm volatile("pkhbt %0, %1, %2, lsl #16" : "=r" (val) : "r" (lo), "r" (hi)); // pack + asm volatile ("smulwb %0, %1, %2" : "=r" (lo) : "r" (mul), "r" (val)); + asm volatile ("smulwt %0, %1, %2" : "=r" (hi) : "r" (mul), "r" (val)); + asm volatile ("ssat %0, %1, %2, asr %3" : "=r" (lo) : "I" (bits), "r" (lo), "I" (shift)); + asm volatile ("ssat %0, %1, %2, asr %3" : "=r" (hi) : "I" (bits), "r" (hi), "I" (shift)); + asm volatile ("pkhbt %0, %1, %2, lsl #16" : "=r" (val) : "r" (lo), "r" (hi)); // pack return val; } @@ -140,9 +140,9 @@ static inline uint32_t pack8(uint32_t val) { return ((val & 0xff000000) >> 16) | ((val & 0xff00) >> 8); } -static void mix_down_one_voice(audiomixer_mixer_obj_t* self, - audiomixer_mixervoice_obj_t* voice, bool voices_active, - uint32_t* word_buffer, uint32_t length) { +static void mix_down_one_voice(audiomixer_mixer_obj_t *self, + audiomixer_mixervoice_obj_t *voice, bool voices_active, + uint32_t *word_buffer, uint32_t length) { while (length != 0) { if (voice->buffer_length == 0) { if (!voice->more_data) { @@ -155,7 +155,7 @@ static void mix_down_one_voice(audiomixer_mixer_obj_t* self, } if (voice->sample) { // Load another buffer - audioio_get_buffer_result_t result = audiosample_get_buffer(voice->sample, false, 0, (uint8_t**) &voice->remaining_buffer, &voice->buffer_length); + audioio_get_buffer_result_t result = audiosample_get_buffer(voice->sample, false, 0, (uint8_t **)&voice->remaining_buffer, &voice->buffer_length); // Track length in terms of words. voice->buffer_length /= sizeof(uint32_t); voice->more_data = result == GET_BUFFER_MORE_DATA; @@ -170,21 +170,21 @@ static void mix_down_one_voice(audiomixer_mixer_obj_t* self, if (!voices_active) { if (MP_LIKELY(self->bits_per_sample == 16)) { if (MP_LIKELY(self->samples_signed)) { - for (uint32_t i = 0; isamples_signed)) { word = tosigned16(word); @@ -196,21 +196,21 @@ static void mix_down_one_voice(audiomixer_mixer_obj_t* self, } else { if (MP_LIKELY(self->bits_per_sample == 16)) { if (MP_LIKELY(self->samples_signed)) { - for (uint32_t i = 0; isamples_signed)) { word = tosigned16(word); @@ -228,17 +228,17 @@ static void mix_down_one_voice(audiomixer_mixer_obj_t* self, } if (length && !voices_active) { - for (uint32_t i = 0; iread_count == channel_read_count; if (need_more_data) { - uint32_t* word_buffer; + uint32_t *word_buffer; if (self->use_first_buffer) { - *buffer = (uint8_t*) self->first_buffer; + *buffer = (uint8_t *)self->first_buffer; word_buffer = self->first_buffer; } else { - *buffer = (uint8_t*) self->second_buffer; + *buffer = (uint8_t *)self->second_buffer; word_buffer = self->second_buffer; } self->use_first_buffer = !self->use_first_buffer; @@ -264,15 +264,15 @@ audioio_get_buffer_result_t audiomixer_mixer_get_buffer(audiomixer_mixer_obj_t* uint32_t length = self->len / sizeof(uint32_t); for (int32_t v = 0; v < self->voice_count; v++) { - audiomixer_mixervoice_obj_t* voice = MP_OBJ_TO_PTR(self->voice[v]); - if(voice->sample) { + audiomixer_mixervoice_obj_t *voice = MP_OBJ_TO_PTR(self->voice[v]); + if (voice->sample) { mix_down_one_voice(self, voice, voices_active, word_buffer, length); voices_active = true; } } if (!voices_active) { - for (uint32_t i = 0; iread_count += 1; } else if (!self->use_first_buffer) { - *buffer = (uint8_t*) self->first_buffer; + *buffer = (uint8_t *)self->first_buffer; } else { - *buffer = (uint8_t*) self->second_buffer; + *buffer = (uint8_t *)self->second_buffer; } @@ -306,9 +306,9 @@ audioio_get_buffer_result_t audiomixer_mixer_get_buffer(audiomixer_mixer_obj_t* return GET_BUFFER_MORE_DATA; } -void audiomixer_mixer_get_buffer_structure(audiomixer_mixer_obj_t* self, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing) { +void audiomixer_mixer_get_buffer_structure(audiomixer_mixer_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing) { *single_buffer = false; *samples_signed = self->samples_signed; *max_buffer_length = self->len; diff --git a/shared-module/audiomixer/Mixer.h b/shared-module/audiomixer/Mixer.h index ab4780efc6..ceb04772ec 100644 --- a/shared-module/audiomixer/Mixer.h +++ b/shared-module/audiomixer/Mixer.h @@ -34,8 +34,8 @@ typedef struct { mp_obj_base_t base; - uint32_t* first_buffer; - uint32_t* second_buffer; + uint32_t *first_buffer; + uint32_t *second_buffer; uint32_t len; // in words uint8_t bits_per_sample; bool use_first_buffer; @@ -54,16 +54,16 @@ typedef struct { // These are not available from Python because it may be called in an interrupt. -void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t* self, - bool single_channel, - uint8_t channel); -audioio_get_buffer_result_t audiomixer_mixer_get_buffer(audiomixer_mixer_obj_t* self, - bool single_channel, - uint8_t channel, - uint8_t** buffer, - uint32_t* buffer_length); // length in bytes -void audiomixer_mixer_get_buffer_structure(audiomixer_mixer_obj_t* self, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing); +void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t *self, + bool single_channel, + uint8_t channel); +audioio_get_buffer_result_t audiomixer_mixer_get_buffer(audiomixer_mixer_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes +void audiomixer_mixer_get_buffer_structure(audiomixer_mixer_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing); #endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOMIXER_MIXER_H diff --git a/shared-module/audiomixer/MixerVoice.c b/shared-module/audiomixer/MixerVoice.c index 9be104afcf..34fa907a5b 100644 --- a/shared-module/audiomixer/MixerVoice.c +++ b/shared-module/audiomixer/MixerVoice.c @@ -37,19 +37,19 @@ void common_hal_audiomixer_mixervoice_construct(audiomixer_mixervoice_obj_t *sel self->level = 1 << 15; } -void common_hal_audiomixer_mixervoice_set_parent(audiomixer_mixervoice_obj_t* self, audiomixer_mixer_obj_t *parent) { - self->parent = parent; +void common_hal_audiomixer_mixervoice_set_parent(audiomixer_mixervoice_obj_t *self, audiomixer_mixer_obj_t *parent) { + self->parent = parent; } -float common_hal_audiomixer_mixervoice_get_level(audiomixer_mixervoice_obj_t* self) { - return ((float) self->level / (1 << 15)); +float common_hal_audiomixer_mixervoice_get_level(audiomixer_mixervoice_obj_t *self) { + return (float)self->level / (1 << 15); } -void common_hal_audiomixer_mixervoice_set_level(audiomixer_mixervoice_obj_t* self, float level) { - self->level = level * (1 << 15); +void common_hal_audiomixer_mixervoice_set_level(audiomixer_mixervoice_obj_t *self, float level) { + self->level = level * (1 << 15); } -void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t* self, mp_obj_t sample, bool loop) { +void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t *self, mp_obj_t sample, bool loop) { if (audiosample_sample_rate(sample) != self->parent->sample_rate) { mp_raise_ValueError(translate("The sample's sample rate does not match the mixer's")); } @@ -64,7 +64,7 @@ void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t* self, mp uint32_t max_buffer_length; uint8_t spacing; audiosample_get_buffer_structure(sample, false, &single_buffer, &samples_signed, - &max_buffer_length, &spacing); + &max_buffer_length, &spacing); if (samples_signed != self->parent->samples_signed) { mp_raise_ValueError(translate("The sample's signedness does not match the mixer's")); } @@ -72,16 +72,16 @@ void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t* self, mp self->loop = loop; audiosample_reset_buffer(sample, false, 0); - audioio_get_buffer_result_t result = audiosample_get_buffer(sample, false, 0, (uint8_t**) &self->remaining_buffer, &self->buffer_length); + audioio_get_buffer_result_t result = audiosample_get_buffer(sample, false, 0, (uint8_t **)&self->remaining_buffer, &self->buffer_length); // Track length in terms of words. self->buffer_length /= sizeof(uint32_t); self->more_data = result == GET_BUFFER_MORE_DATA; } -bool common_hal_audiomixer_mixervoice_get_playing(audiomixer_mixervoice_obj_t* self) { - return self->sample != NULL; +bool common_hal_audiomixer_mixervoice_get_playing(audiomixer_mixervoice_obj_t *self) { + return self->sample != NULL; } -void common_hal_audiomixer_mixervoice_stop(audiomixer_mixervoice_obj_t* self) { +void common_hal_audiomixer_mixervoice_stop(audiomixer_mixervoice_obj_t *self) { self->sample = NULL; } diff --git a/shared-module/audiomixer/MixerVoice.h b/shared-module/audiomixer/MixerVoice.h index a85316e3d0..1fdc91d11b 100644 --- a/shared-module/audiomixer/MixerVoice.h +++ b/shared-module/audiomixer/MixerVoice.h @@ -32,12 +32,12 @@ #include "shared-module/audiomixer/Mixer.h" typedef struct { - mp_obj_base_t base; - audiomixer_mixer_obj_t *parent; + mp_obj_base_t base; + audiomixer_mixer_obj_t *parent; mp_obj_t sample; bool loop; bool more_data; - uint32_t* remaining_buffer; + uint32_t *remaining_buffer; uint32_t buffer_length; uint16_t level; } audiomixer_mixervoice_obj_t; diff --git a/shared-module/audiomp3/MP3Decoder.c b/shared-module/audiomp3/MP3Decoder.c index 5f3f42a51b..2b623233e0 100644 --- a/shared-module/audiomp3/MP3Decoder.c +++ b/shared-module/audiomp3/MP3Decoder.c @@ -51,7 +51,7 @@ * * Sets self->eof if any read of the file returns 0 bytes */ -STATIC bool mp3file_update_inbuf_always(audiomp3_mp3file_obj_t* self) { +STATIC bool mp3file_update_inbuf_always(audiomp3_mp3file_obj_t *self) { // If we didn't previously reach the end of file, we can try reading now if (!self->eof) { @@ -90,7 +90,7 @@ STATIC bool mp3file_update_inbuf_always(audiomp3_mp3file_obj_t* self) { * This variant is introduced so that at the site of the * add_background_callback_core call, the prototype matches. */ -STATIC void mp3file_update_inbuf_cb(void* self) { +STATIC void mp3file_update_inbuf_cb(void *self) { mp3file_update_inbuf_always(self); } @@ -98,9 +98,11 @@ STATIC void mp3file_update_inbuf_cb(void* self) { * * Returns the same as mp3file_update_inbuf_always. */ -STATIC bool mp3file_update_inbuf_half(audiomp3_mp3file_obj_t* self) { +STATIC bool mp3file_update_inbuf_half(audiomp3_mp3file_obj_t *self) { // If buffer is over half full, do nothing - if (self->inbuf_offset < self->inbuf_length/2) return true; + if (self->inbuf_offset < self->inbuf_length / 2) { + return true; + } return mp3file_update_inbuf_always(self); } @@ -111,23 +113,23 @@ STATIC bool mp3file_update_inbuf_half(audiomp3_mp3file_obj_t* self) { // http://id3.org/d3v2.3.0 // http://id3.org/id3v2.3.0 -STATIC void mp3file_skip_id3v2(audiomp3_mp3file_obj_t* self) { +STATIC void mp3file_skip_id3v2(audiomp3_mp3file_obj_t *self) { mp3file_update_inbuf_half(self); if (BYTES_LEFT(self) < 10) { return; } uint8_t *data = READ_PTR(self); if (!( - data[0] == 'I' && - data[1] == 'D' && - data[2] == '3' && - data[3] != 0xff && - data[4] != 0xff && - (data[5] & 0x1f) == 0 && - (data[6] & 0x80) == 0 && - (data[7] & 0x80) == 0 && - (data[8] & 0x80) == 0 && - (data[9] & 0x80) == 0)) { + data[0] == 'I' && + data[1] == 'D' && + data[2] == '3' && + data[3] != 0xff && + data[4] != 0xff && + (data[5] & 0x1f) == 0 && + (data[6] & 0x80) == 0 && + (data[7] & 0x80) == 0 && + (data[8] & 0x80) == 0 && + (data[9] & 0x80) == 0)) { return; } uint32_t size = (data[6] << 21) | (data[7] << 14) | (data[8] << 7) | (data[9]); @@ -145,7 +147,7 @@ STATIC void mp3file_skip_id3v2(audiomp3_mp3file_obj_t* self) { /* If a sync word can be found, advance to it and return true. Otherwise, * return false. */ -STATIC bool mp3file_find_sync_word(audiomp3_mp3file_obj_t* self) { +STATIC bool mp3file_find_sync_word(audiomp3_mp3file_obj_t *self) { do { mp3file_update_inbuf_half(self); int offset = MP3FindSyncWord(READ_PTR(self), BYTES_LEFT(self)); @@ -159,7 +161,7 @@ STATIC bool mp3file_find_sync_word(audiomp3_mp3file_obj_t* self) { return false; } -STATIC bool mp3file_get_next_frame_info(audiomp3_mp3file_obj_t* self, MP3FrameInfo* fi) { +STATIC bool mp3file_get_next_frame_info(audiomp3_mp3file_obj_t *self, MP3FrameInfo *fi) { int err; do { err = MP3GetNextFrameInfo(self->decoder, fi, READ_PTR(self)); @@ -172,10 +174,10 @@ STATIC bool mp3file_get_next_frame_info(audiomp3_mp3file_obj_t* self, MP3FrameIn return err == ERR_MP3_NONE; } -void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t* self, - pyb_file_obj_t* file, - uint8_t *buffer, - size_t buffer_size) { +void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t *self, + pyb_file_obj_t *file, + uint8_t *buffer, + size_t buffer_size) { // XXX Adafruit_MP3 uses a 2kB input buffer and two 4kB output buffers. // for a whopping total of 10kB buffers (+mp3 decoder state and frame buffer) // At 44kHz, that's 23ms of output audio data. @@ -192,41 +194,42 @@ void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t* self, if (self->inbuf == NULL) { common_hal_audiomp3_mp3file_deinit(self); mp_raise_msg(&mp_type_MemoryError, - translate("Couldn't allocate input buffer")); + translate("Couldn't allocate input buffer")); } self->decoder = MP3InitDecoder(); if (self->decoder == NULL) { common_hal_audiomp3_mp3file_deinit(self); mp_raise_msg(&mp_type_MemoryError, - translate("Couldn't allocate decoder")); + translate("Couldn't allocate decoder")); } if ((intptr_t)buffer & 1) { - buffer += 1; buffer_size -= 1; + buffer += 1; + buffer_size -= 1; } if (buffer_size >= 2 * MAX_BUFFER_LEN) { - self->buffers[0] = (int16_t*)(void*)buffer; - self->buffers[1] = (int16_t*)(void*)(buffer + MAX_BUFFER_LEN); + self->buffers[0] = (int16_t *)(void *)buffer; + self->buffers[1] = (int16_t *)(void *)(buffer + MAX_BUFFER_LEN); } else { self->buffers[0] = m_malloc(MAX_BUFFER_LEN, false); if (self->buffers[0] == NULL) { common_hal_audiomp3_mp3file_deinit(self); mp_raise_msg(&mp_type_MemoryError, - translate("Couldn't allocate first buffer")); + translate("Couldn't allocate first buffer")); } self->buffers[1] = m_malloc(MAX_BUFFER_LEN, false); if (self->buffers[1] == NULL) { common_hal_audiomp3_mp3file_deinit(self); mp_raise_msg(&mp_type_MemoryError, - translate("Couldn't allocate second buffer")); + translate("Couldn't allocate second buffer")); } } common_hal_audiomp3_mp3file_set_file(self, file); } -void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t* self, pyb_file_obj_t* file) { +void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t *self, pyb_file_obj_t *file) { background_callback_begin_critical_section(); self->file = file; @@ -248,16 +251,16 @@ void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t* self, pyb_file background_callback_end_critical_section(); if (!result) { mp_raise_msg(&mp_type_RuntimeError, - translate("Failed to parse MP3 file")); + translate("Failed to parse MP3 file")); } self->sample_rate = fi.samprate; self->channel_count = fi.nChans; - self->frame_buffer_size = fi.outputSamps*sizeof(int16_t); + self->frame_buffer_size = fi.outputSamps * sizeof(int16_t); self->len = 2 * self->frame_buffer_size; } -void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t* self) { +void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t *self) { MP3FreeDecoder(self->decoder); self->decoder = NULL; self->inbuf = NULL; @@ -266,34 +269,34 @@ void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t* self) { self->file = NULL; } -bool common_hal_audiomp3_mp3file_deinited(audiomp3_mp3file_obj_t* self) { +bool common_hal_audiomp3_mp3file_deinited(audiomp3_mp3file_obj_t *self) { return self->buffers[0] == NULL; } -uint32_t common_hal_audiomp3_mp3file_get_sample_rate(audiomp3_mp3file_obj_t* self) { +uint32_t common_hal_audiomp3_mp3file_get_sample_rate(audiomp3_mp3file_obj_t *self) { return self->sample_rate; } -void common_hal_audiomp3_mp3file_set_sample_rate(audiomp3_mp3file_obj_t* self, - uint32_t sample_rate) { +void common_hal_audiomp3_mp3file_set_sample_rate(audiomp3_mp3file_obj_t *self, + uint32_t sample_rate) { self->sample_rate = sample_rate; } -uint8_t common_hal_audiomp3_mp3file_get_bits_per_sample(audiomp3_mp3file_obj_t* self) { +uint8_t common_hal_audiomp3_mp3file_get_bits_per_sample(audiomp3_mp3file_obj_t *self) { return 16; } -uint8_t common_hal_audiomp3_mp3file_get_channel_count(audiomp3_mp3file_obj_t* self) { +uint8_t common_hal_audiomp3_mp3file_get_channel_count(audiomp3_mp3file_obj_t *self) { return self->channel_count; } -bool audiomp3_mp3file_samples_signed(audiomp3_mp3file_obj_t* self) { +bool audiomp3_mp3file_samples_signed(audiomp3_mp3file_obj_t *self) { return true; } -void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t* self, - bool single_channel, - uint8_t channel) { +void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t *self, + bool single_channel, + uint8_t channel) { if (single_channel && channel == 1) { return; } @@ -310,11 +313,11 @@ void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t* self, background_callback_end_critical_section(); } -audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t* self, - bool single_channel, - uint8_t channel, - uint8_t** bufptr, - uint32_t* buffer_length) { +audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **bufptr, + uint32_t *buffer_length) { if (!self->inbuf) { return GET_BUFFER_ERROR; } @@ -325,17 +328,17 @@ audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t* *buffer_length = self->frame_buffer_size; if (channel == self->other_channel) { - *bufptr = (uint8_t*)(self->buffers[self->other_buffer_index] + channel); + *bufptr = (uint8_t *)(self->buffers[self->other_buffer_index] + channel); self->other_channel = -1; return GET_BUFFER_MORE_DATA; } self->buffer_index = !self->buffer_index; - self->other_channel = 1-channel; + self->other_channel = 1 - channel; self->other_buffer_index = self->buffer_index; int16_t *buffer = (int16_t *)(void *)self->buffers[self->buffer_index]; - *bufptr = (uint8_t*)buffer; + *bufptr = (uint8_t *)buffer; mp3file_skip_id3v2(self); if (!mp3file_find_sync_word(self)) { @@ -360,9 +363,9 @@ audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t* return GET_BUFFER_MORE_DATA; } -void audiomp3_mp3file_get_buffer_structure(audiomp3_mp3file_obj_t* self, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing) { +void audiomp3_mp3file_get_buffer_structure(audiomp3_mp3file_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing) { *single_buffer = false; *samples_signed = true; *max_buffer_length = self->frame_buffer_size; @@ -373,11 +376,11 @@ void audiomp3_mp3file_get_buffer_structure(audiomp3_mp3file_obj_t* self, bool si } } -float common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t* self) { +float common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t *self) { float sumsq = 0.f; // Assumes no DC component to the audio. Is that a safe assumption? int16_t *buffer = (int16_t *)(void *)self->buffers[self->buffer_index]; - for(size_t i=0; iframe_buffer_size / sizeof(int16_t); i++) { + for (size_t i = 0; i < self->frame_buffer_size / sizeof(int16_t); i++) { sumsq += (float)buffer[i] * buffer[i]; } return sqrtf(sumsq) / (self->frame_buffer_size / sizeof(int16_t)); diff --git a/shared-module/audiomp3/MP3Decoder.h b/shared-module/audiomp3/MP3Decoder.h index f91f102a27..c1e6178465 100644 --- a/shared-module/audiomp3/MP3Decoder.h +++ b/shared-module/audiomp3/MP3Decoder.h @@ -38,15 +38,15 @@ typedef struct { mp_obj_base_t base; struct _MP3DecInfo *decoder; background_callback_t inbuf_fill_cb; - uint8_t* inbuf; + uint8_t *inbuf; uint32_t inbuf_length; uint32_t inbuf_offset; - int16_t* buffers[2]; + int16_t *buffers[2]; uint32_t len; uint32_t frame_buffer_size; uint32_t sample_rate; - pyb_file_obj_t* file; + pyb_file_obj_t *file; uint8_t buffer_index; uint8_t channel_count; @@ -57,18 +57,18 @@ typedef struct { } audiomp3_mp3file_obj_t; // These are not available from Python because it may be called in an interrupt. -void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t* self, - bool single_channel, - uint8_t channel); -audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t* self, - bool single_channel, - uint8_t channel, - uint8_t** buffer, - uint32_t* buffer_length); // length in bytes -void audiomp3_mp3file_get_buffer_structure(audiomp3_mp3file_obj_t* self, bool single_channel, - bool* single_buffer, bool* samples_signed, - uint32_t* max_buffer_length, uint8_t* spacing); +void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t *self, + bool single_channel, + uint8_t channel); +audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t *self, + bool single_channel, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes +void audiomp3_mp3file_get_buffer_structure(audiomp3_mp3file_obj_t *self, bool single_channel, + bool *single_buffer, bool *samples_signed, + uint32_t *max_buffer_length, uint8_t *spacing); -float audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t* self); +float audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_MODULE_AUDIOIO_MP3FILE_H diff --git a/shared-module/bitbangio/I2C.c b/shared-module/bitbangio/I2C.c index 170630df63..7d7380e214 100644 --- a/shared-module/bitbangio/I2C.c +++ b/shared-module/bitbangio/I2C.c @@ -143,10 +143,10 @@ STATIC bool read_byte(bitbangio_i2c_obj_t *self, uint8_t *val, bool ack) { } void shared_module_bitbangio_i2c_construct(bitbangio_i2c_obj_t *self, - const mcu_pin_obj_t * scl, - const mcu_pin_obj_t * sda, - uint32_t frequency, - uint32_t us_timeout) { + const mcu_pin_obj_t *scl, + const mcu_pin_obj_t *sda, + uint32_t frequency, + uint32_t us_timeout) { self->us_timeout = us_timeout; self->us_delay = 500000 / frequency; @@ -208,7 +208,7 @@ bool shared_module_bitbangio_i2c_probe(bitbangio_i2c_obj_t *self, uint8_t addr) } uint8_t shared_module_bitbangio_i2c_write(bitbangio_i2c_obj_t *self, uint16_t addr, - const uint8_t *data, size_t len, bool transmit_stop_bit) { + const uint8_t *data, size_t len, bool transmit_stop_bit) { // start the I2C transaction start(self); uint8_t status = 0; @@ -232,7 +232,7 @@ uint8_t shared_module_bitbangio_i2c_write(bitbangio_i2c_obj_t *self, uint16_t ad } uint8_t shared_module_bitbangio_i2c_read(bitbangio_i2c_obj_t *self, uint16_t addr, - uint8_t * data, size_t len) { + uint8_t *data, size_t len) { // start the I2C transaction start(self); uint8_t status = 0; diff --git a/shared-module/bitbangio/OneWire.c b/shared-module/bitbangio/OneWire.c index 3e4ec8426e..8a73817f37 100644 --- a/shared-module/bitbangio/OneWire.c +++ b/shared-module/bitbangio/OneWire.c @@ -31,17 +31,17 @@ // Durations are taken from here: https://www.maximintegrated.com/en/app-notes/index.mvp/id/126 -void shared_module_bitbangio_onewire_construct(bitbangio_onewire_obj_t* self, - const mcu_pin_obj_t* pin) { +void shared_module_bitbangio_onewire_construct(bitbangio_onewire_obj_t *self, + const mcu_pin_obj_t *pin) { self->pin.base.type = &digitalio_digitalinout_type; common_hal_digitalio_digitalinout_construct(&self->pin, pin); } -bool shared_module_bitbangio_onewire_deinited(bitbangio_onewire_obj_t* self) { +bool shared_module_bitbangio_onewire_deinited(bitbangio_onewire_obj_t *self) { return common_hal_digitalio_digitalinout_deinited(&self->pin); } -void shared_module_bitbangio_onewire_deinit(bitbangio_onewire_obj_t* self) { +void shared_module_bitbangio_onewire_deinit(bitbangio_onewire_obj_t *self) { if (shared_module_bitbangio_onewire_deinited(self)) { return; } @@ -51,7 +51,7 @@ void shared_module_bitbangio_onewire_deinit(bitbangio_onewire_obj_t* self) { // We use common_hal_mcu_delay_us(). It should not be dependent on interrupts // to do accurate timekeeping, since we disable interrupts during the delays below. -bool shared_module_bitbangio_onewire_reset(bitbangio_onewire_obj_t* self) { +bool shared_module_bitbangio_onewire_reset(bitbangio_onewire_obj_t *self) { common_hal_mcu_disable_interrupts(); common_hal_digitalio_digitalinout_switch_to_output(&self->pin, false, DRIVE_MODE_OPEN_DRAIN); common_hal_mcu_delay_us(480); @@ -63,7 +63,7 @@ bool shared_module_bitbangio_onewire_reset(bitbangio_onewire_obj_t* self) { return value; } -bool shared_module_bitbangio_onewire_read_bit(bitbangio_onewire_obj_t* self) { +bool shared_module_bitbangio_onewire_read_bit(bitbangio_onewire_obj_t *self) { common_hal_mcu_disable_interrupts(); common_hal_digitalio_digitalinout_switch_to_output(&self->pin, false, DRIVE_MODE_OPEN_DRAIN); common_hal_mcu_delay_us(6); @@ -78,8 +78,8 @@ bool shared_module_bitbangio_onewire_read_bit(bitbangio_onewire_obj_t* self) { return value; } -void shared_module_bitbangio_onewire_write_bit(bitbangio_onewire_obj_t* self, - bool bit) { +void shared_module_bitbangio_onewire_write_bit(bitbangio_onewire_obj_t *self, + bool bit) { common_hal_mcu_disable_interrupts(); common_hal_digitalio_digitalinout_switch_to_output(&self->pin, false, DRIVE_MODE_OPEN_DRAIN); common_hal_mcu_delay_us(bit? 6 : 60); diff --git a/shared-module/bitbangio/SPI.c b/shared-module/bitbangio/SPI.c index 9ed3d660a5..8be6cac5fa 100644 --- a/shared-module/bitbangio/SPI.c +++ b/shared-module/bitbangio/SPI.c @@ -37,8 +37,8 @@ #define MAX_BAUDRATE (common_hal_mcu_get_clock_frequency() / 48) void shared_module_bitbangio_spi_construct(bitbangio_spi_obj_t *self, - const mcu_pin_obj_t * clock, const mcu_pin_obj_t * mosi, - const mcu_pin_obj_t * miso) { + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso) { digitalinout_result_t result = common_hal_digitalio_digitalinout_construct(&self->clock, clock); if (result != DIGITALINOUT_OK) { mp_raise_ValueError(translate("Clock pin init failed.")); @@ -90,7 +90,7 @@ void shared_module_bitbangio_spi_deinit(bitbangio_spi_obj_t *self) { } void shared_module_bitbangio_spi_configure(bitbangio_spi_obj_t *self, - uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { + uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { self->delay_half = 500000 / baudrate; // round delay_half up so that: actual_baudrate <= requested_baudrate if (500000 % baudrate != 0) { @@ -241,7 +241,7 @@ bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data, // transfer bool shared_module_bitbangio_spi_transfer(bitbangio_spi_obj_t *self, const uint8_t *dout, uint8_t *din, size_t len) { - if (len > 0 && (!self->has_mosi || !self->has_miso) ) { + if (len > 0 && (!self->has_mosi || !self->has_miso)) { mp_raise_ValueError(translate("Cannot transfer without MOSI and MISO pins.")); } uint32_t delay_half = self->delay_half; diff --git a/shared-module/bitbangio/SPI.h b/shared-module/bitbangio/SPI.h index f3e02c206c..cc71a0319a 100644 --- a/shared-module/bitbangio/SPI.h +++ b/shared-module/bitbangio/SPI.h @@ -37,11 +37,11 @@ typedef struct { digitalio_digitalinout_obj_t mosi; digitalio_digitalinout_obj_t miso; uint32_t delay_half; - bool has_miso:1; - bool has_mosi:1; - uint8_t polarity:1; - uint8_t phase:1; - volatile bool locked:1; + bool has_miso : 1; + bool has_mosi : 1; + uint8_t polarity : 1; + uint8_t phase : 1; + volatile bool locked : 1; } bitbangio_spi_obj_t; #endif // MICROPY_INCLUDED_SHARED_MODULE_BITBANGIO_SPI_H diff --git a/shared-module/bitmaptools/__init__.c b/shared-module/bitmaptools/__init__.c index 6f168b5552..2d0d4ec4fb 100644 --- a/shared-module/bitmaptools/__init__.c +++ b/shared-module/bitmaptools/__init__.c @@ -34,14 +34,14 @@ #include "stdlib.h" void common_hal_bitmaptools_rotozoom(displayio_bitmap_t *self, int16_t ox, int16_t oy, - int16_t dest_clip0_x, int16_t dest_clip0_y, - int16_t dest_clip1_x, int16_t dest_clip1_y, - displayio_bitmap_t *source, int16_t px, int16_t py, - int16_t source_clip0_x, int16_t source_clip0_y, - int16_t source_clip1_x, int16_t source_clip1_y, - float angle, - float scale, - uint32_t skip_index, bool skip_index_none) { + int16_t dest_clip0_x, int16_t dest_clip0_y, + int16_t dest_clip1_x, int16_t dest_clip1_y, + displayio_bitmap_t *source, int16_t px, int16_t py, + int16_t source_clip0_x, int16_t source_clip0_y, + int16_t source_clip1_x, int16_t source_clip1_y, + float angle, + float scale, + uint32_t skip_index, bool skip_index_none) { // Copies region from source to the destination bitmap, including rotation, // scaling and clipping of either the source or destination regions @@ -113,37 +113,77 @@ void common_hal_bitmaptools_rotozoom(displayio_bitmap_t *self, int16_t ox, int16 will be on the destination to get a bounding box for scanning */ dx = -cosAngle * px * scale + sinAngle * py * scale + ox; dy = -sinAngle * px * scale - cosAngle * py * scale + oy; - if(dx < minx) minx = (int16_t)dx; - if(dx > maxx) maxx = (int16_t)dx; - if(dy < miny) miny = (int16_t)dy; - if(dy > maxy) maxy = (int16_t)dy; + if (dx < minx) { + minx = (int16_t)dx; + } + if (dx > maxx) { + maxx = (int16_t)dx; + } + if (dy < miny) { + miny = (int16_t)dy; + } + if (dy > maxy) { + maxy = (int16_t)dy; + } dx = cosAngle * (source->width - px) * scale + sinAngle * py * scale + ox; dy = sinAngle * (source->width - px) * scale - cosAngle * py * scale + oy; - if(dx < minx) minx = (int16_t)dx; - if(dx > maxx) maxx = (int16_t)dx; - if(dy < miny) miny = (int16_t)dy; - if(dy > maxy) maxy = (int16_t)dy; + if (dx < minx) { + minx = (int16_t)dx; + } + if (dx > maxx) { + maxx = (int16_t)dx; + } + if (dy < miny) { + miny = (int16_t)dy; + } + if (dy > maxy) { + maxy = (int16_t)dy; + } dx = cosAngle * (source->width - px) * scale - sinAngle * (source->height - py) * scale + ox; dy = sinAngle * (source->width - px) * scale + cosAngle * (source->height - py) * scale + oy; - if(dx < minx) minx = (int16_t)dx; - if(dx > maxx) maxx = (int16_t)dx; - if(dy < miny) miny = (int16_t)dy; - if(dy > maxy) maxy = (int16_t)dy; + if (dx < minx) { + minx = (int16_t)dx; + } + if (dx > maxx) { + maxx = (int16_t)dx; + } + if (dy < miny) { + miny = (int16_t)dy; + } + if (dy > maxy) { + maxy = (int16_t)dy; + } dx = -cosAngle * px * scale - sinAngle * (source->height - py) * scale + ox; dy = -sinAngle * px * scale + cosAngle * (source->height - py) * scale + oy; - if(dx < minx) minx = (int16_t)dx; - if(dx > maxx) maxx = (int16_t)dx; - if(dy < miny) miny = (int16_t)dy; - if(dy > maxy) maxy = (int16_t)dy; + if (dx < minx) { + minx = (int16_t)dx; + } + if (dx > maxx) { + maxx = (int16_t)dx; + } + if (dy < miny) { + miny = (int16_t)dy; + } + if (dy > maxy) { + maxy = (int16_t)dy; + } /* Clipping */ - if(minx < dest_clip0_x) minx = dest_clip0_x; - if(maxx > dest_clip1_x - 1) maxx = dest_clip1_x - 1; - if(miny < dest_clip0_y) miny = dest_clip0_y; - if(maxy > dest_clip1_y - 1) maxy = dest_clip1_y - 1; + if (minx < dest_clip0_x) { + minx = dest_clip0_x; + } + if (maxx > dest_clip1_x - 1) { + maxx = dest_clip1_x - 1; + } + if (miny < dest_clip0_y) { + miny = dest_clip0_y; + } + if (maxy > dest_clip1_y - 1) { + maxy = dest_clip1_y - 1; + } float dvCol = cosAngle / scale; float duCol = sinAngle / scale; @@ -157,13 +197,13 @@ void common_hal_bitmaptools_rotozoom(displayio_bitmap_t *self, int16_t ox, int16 float rowu = startu + miny * duCol; float rowv = startv + miny * dvCol; - for(y = miny; y <= maxy; y++) { + for (y = miny; y <= maxy; y++) { float u = rowu + minx * duRow; float v = rowv + minx * dvRow; - for(x = minx; x <= maxx; x++) { - if(u >= source_clip0_x && u < source_clip1_x && v >= source_clip0_y && v < source_clip1_y) { + for (x = minx; x <= maxx; x++) { + if (u >= source_clip0_x && u < source_clip1_x && v >= source_clip0_y && v < source_clip1_y) { uint32_t c = common_hal_displayio_bitmap_get_pixel(source, u, v); - if( (skip_index_none) || (c != skip_index) ) { + if ((skip_index_none) || (c != skip_index)) { common_hal_displayio_bitmap_set_pixel(self, x, y, c); } } @@ -187,9 +227,9 @@ int16_t constrain(int16_t input, int16_t min, int16_t max) { } void common_hal_bitmaptools_fill_region(displayio_bitmap_t *destination, - int16_t x1, int16_t y1, - int16_t x2, int16_t y2, - uint32_t value) { + int16_t x1, int16_t y1, + int16_t x2, int16_t y2, + uint32_t value) { // writes the value (a bitmap color index) into a bitmap in the specified rectangular region // // input checks should ensure that x1 < x2 and y1 < y2 and are within the bitmap region @@ -200,14 +240,14 @@ void common_hal_bitmaptools_fill_region(displayio_bitmap_t *destination, // Ensure x1 < x2 and y1 < y2 if (x1 > x2) { - int16_t temp=x2; - x2=x1; - x1=temp; + int16_t temp = x2; + x2 = x1; + x1 = temp; } if (y1 > y2) { - int16_t temp=y2; - y2=y1; - y1=temp; + int16_t temp = y2; + y2 = y1; + y1 = temp; } // constrain to bitmap dimensions @@ -221,16 +261,16 @@ void common_hal_bitmaptools_fill_region(displayio_bitmap_t *destination, int16_t x, y; for (x = x1; x < x2; x++) { - for (y = y1; y < y2; y++ ) { + for (y = y1; y < y2; y++) { displayio_bitmap_write_pixel(destination, x, y, value); } } } void common_hal_bitmaptools_draw_line(displayio_bitmap_t *destination, - int16_t x0, int16_t y0, - int16_t x1, int16_t y1, - uint32_t value) { + int16_t x0, int16_t y0, + int16_t x1, int16_t y1, + uint32_t value) { if (destination->read_only) { mp_raise_RuntimeError(translate("Read-only object")); @@ -275,8 +315,7 @@ void common_hal_bitmaptools_draw_line(displayio_bitmap_t *destination, for (y = y0; y < (y1 + 1); y++) { // write a horizontal line displayio_bitmap_write_pixel(destination, x0, y, value); } - } - else if (y0 == y1) { // horizontal line + } else if (y0 == y1) { // horizontal line if (x0 > x1) { // ensure y1 > y0 temp = x0; x0 = x1; @@ -285,12 +324,11 @@ void common_hal_bitmaptools_draw_line(displayio_bitmap_t *destination, for (x = x0; x < (x1 + 1); x++) { // write a horizontal line displayio_bitmap_write_pixel(destination, x, y0, value); } - } - else { + } else { bool steep; - steep = ( abs(y1 - y0) > abs(x1 - x0) ); + steep = (abs(y1 - y0) > abs(x1 - x0)); - if ( steep ) { // flip x0<->y0 and x1<->y1 + if (steep) { // flip x0<->y0 and x1<->y1 temp = x0; x0 = y0; y0 = temp; @@ -316,16 +354,14 @@ void common_hal_bitmaptools_draw_line(displayio_bitmap_t *destination, if (y0 < y1) { ystep = 1; - } - else { + } else { ystep = -1; } for (x = x0; x < (x1 + 1); x++) { if (steep) { displayio_bitmap_write_pixel(destination, y0, x, value); - } - else { + } else { displayio_bitmap_write_pixel(destination, x, y0, value); } err -= dy; diff --git a/shared-module/bitops/__init__.c b/shared-module/bitops/__init__.c index cf0ac7bd1f..1689892181 100644 --- a/shared-module/bitops/__init__.c +++ b/shared-module/bitops/__init__.c @@ -49,49 +49,53 @@ static void transpose_var(uint32_t *result, const uint8_t *src, int src_stride, int num_strands) { uint32_t x = 0, y = 0, t; - src += (num_strands-1) * src_stride; + src += (num_strands - 1) * src_stride; - switch(num_strands) { - case 7: - x |= *src << 16; - src -= src_stride; - FALLTHROUGH; - case 6: - x |= *src << 8; - src -= src_stride; - FALLTHROUGH; - case 5: - x |= *src; - src -= src_stride; - FALLTHROUGH; - case 4: - y |= *src << 24; - src -= src_stride; - FALLTHROUGH; - case 3: - y |= *src << 16; - src -= src_stride; - FALLTHROUGH; - case 2: - y |= *src << 8; - src -= src_stride; - y |= *src; + switch (num_strands) { + case 7: + x |= *src << 16; + src -= src_stride; + FALLTHROUGH; + case 6: + x |= *src << 8; + src -= src_stride; + FALLTHROUGH; + case 5: + x |= *src; + src -= src_stride; + FALLTHROUGH; + case 4: + y |= *src << 24; + src -= src_stride; + FALLTHROUGH; + case 3: + y |= *src << 16; + src -= src_stride; + FALLTHROUGH; + case 2: + y |= *src << 8; + src -= src_stride; + y |= *src; } - t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7); - t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7); + t = (x ^ (x >> 7)) & 0x00AA00AA; + x = x ^ t ^ (t << 7); + t = (y ^ (y >> 7)) & 0x00AA00AA; + y = y ^ t ^ (t << 7); - t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14); - t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14); + t = (x ^ (x >> 14)) & 0x0000CCCC; + x = x ^ t ^ (t << 14); + t = (y ^ (y >> 14)) & 0x0000CCCC; + y = y ^ t ^ (t << 14); t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F); y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F); x = t; -#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ x = __builtin_bswap32(x); y = __builtin_bswap32(y); -#endif + #endif result[0] = x; result[1] = y; } @@ -99,35 +103,47 @@ static void transpose_var(uint32_t *result, const uint8_t *src, int src_stride, static void transpose_8(uint32_t *result, const uint8_t *src, int src_stride) { uint32_t x, y, t; - y = *src; src += src_stride; - y |= (*src << 8); src += src_stride; - y |= (*src << 16); src += src_stride; - y |= (*src << 24); src += src_stride; - x = *src; src += src_stride; - x |= (*src << 8); src += src_stride; - x |= (*src << 16); src += src_stride; - x |= (*src << 24); src += src_stride; + y = *src; + src += src_stride; + y |= (*src << 8); + src += src_stride; + y |= (*src << 16); + src += src_stride; + y |= (*src << 24); + src += src_stride; + x = *src; + src += src_stride; + x |= (*src << 8); + src += src_stride; + x |= (*src << 16); + src += src_stride; + x |= (*src << 24); + src += src_stride; - t = (x ^ (x >> 7)) & 0x00AA00AA; x = x ^ t ^ (t << 7); - t = (y ^ (y >> 7)) & 0x00AA00AA; y = y ^ t ^ (t << 7); + t = (x ^ (x >> 7)) & 0x00AA00AA; + x = x ^ t ^ (t << 7); + t = (y ^ (y >> 7)) & 0x00AA00AA; + y = y ^ t ^ (t << 7); - t = (x ^ (x >>14)) & 0x0000CCCC; x = x ^ t ^ (t <<14); - t = (y ^ (y >>14)) & 0x0000CCCC; y = y ^ t ^ (t <<14); + t = (x ^ (x >> 14)) & 0x0000CCCC; + x = x ^ t ^ (t << 14); + t = (y ^ (y >> 14)) & 0x0000CCCC; + y = y ^ t ^ (t << 14); t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F); y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F); x = t; -#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ + #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ x = __builtin_bswap32(x); y = __builtin_bswap32(y); -#endif + #endif result[0] = x; result[1] = y; } static void bit_transpose_8(uint32_t *result, const uint8_t *src, size_t src_stride, size_t n) { - for(size_t i=0; ibase.type = &busio_spi_type; - const mcu_pin_obj_t* clock = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_SCK); - const mcu_pin_obj_t* mosi = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_MOSI); - const mcu_pin_obj_t* miso = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_MISO); + const mcu_pin_obj_t *clock = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_SCK); + const mcu_pin_obj_t *mosi = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_MOSI); + const mcu_pin_obj_t *miso = MP_OBJ_TO_PTR(DEFAULT_SPI_BUS_MISO); common_hal_busio_spi_construct(self, clock, mosi, miso); spi_singleton = (mp_obj_t)self; return spi_singleton; @@ -101,39 +101,39 @@ mp_obj_t common_hal_board_create_uart(void) { busio_uart_obj_t *self = m_new_ll_obj(busio_uart_obj_t); self->base.type = &busio_uart_type; - const mcu_pin_obj_t* rx = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RX); - const mcu_pin_obj_t* tx = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_TX); -#ifdef DEFAULT_UART_BUS_RTS - const mcu_pin_obj_t* rts = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RTS); -#else - const mcu_pin_obj_t* rts = NULL; -#endif -#ifdef DEFAULT_UART_BUS_CTS - const mcu_pin_obj_t* cts = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_CTS); -#else - const mcu_pin_obj_t* cts = NULL; -#endif -#ifdef DEFAULT_UART_IS_RS485 - const mcu_pin_obj_t* rs485_dir = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RS485DIR); -#ifdef DEFAULT_UART_RS485_INVERT + const mcu_pin_obj_t *rx = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RX); + const mcu_pin_obj_t *tx = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_TX); + #ifdef DEFAULT_UART_BUS_RTS + const mcu_pin_obj_t *rts = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RTS); + #else + const mcu_pin_obj_t *rts = NULL; + #endif + #ifdef DEFAULT_UART_BUS_CTS + const mcu_pin_obj_t *cts = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_CTS); + #else + const mcu_pin_obj_t *cts = NULL; + #endif + #ifdef DEFAULT_UART_IS_RS485 + const mcu_pin_obj_t *rs485_dir = MP_OBJ_TO_PTR(DEFAULT_UART_BUS_RS485DIR); + #ifdef DEFAULT_UART_RS485_INVERT const bool rs485_invert = true; -#else + #else const bool rs485_invert = false; -#endif -#else - const mcu_pin_obj_t* rs485_dir = NULL; + #endif + #else + const mcu_pin_obj_t *rs485_dir = NULL; const bool rs485_invert = false; -#endif + #endif common_hal_busio_uart_construct(self, tx, rx, rts, cts, rs485_dir, rs485_invert, - 9600, 8, BUSIO_UART_PARITY_NONE, 1, 1.0f, 64, NULL, false); + 9600, 8, BUSIO_UART_PARITY_NONE, 1, 1.0f, 64, NULL, false); MP_STATE_VM(shared_uart_bus) = MP_OBJ_FROM_PTR(self); return MP_STATE_VM(shared_uart_bus); } #endif void reset_board_busses(void) { -#if BOARD_I2C + #if BOARD_I2C bool display_using_i2c = false; #if CIRCUITPY_DISPLAYIO for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { @@ -149,8 +149,8 @@ void reset_board_busses(void) { i2c_singleton = NULL; } } -#endif -#if BOARD_SPI + #endif + #if BOARD_SPI bool display_using_spi = false; #if CIRCUITPY_DISPLAYIO for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { @@ -175,8 +175,8 @@ void reset_board_busses(void) { spi_singleton = NULL; } } -#endif -#if BOARD_UART + #endif + #if BOARD_UART MP_STATE_VM(shared_uart_bus) = NULL; -#endif + #endif } diff --git a/shared-module/busio/I2C.c b/shared-module/busio/I2C.c index 06e1af10a1..d3db18e3ad 100644 --- a/shared-module/busio/I2C.c +++ b/shared-module/busio/I2C.c @@ -30,7 +30,7 @@ #include "py/nlr.h" void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, - const mcu_pin_obj_t* scl, const mcu_pin_obj_t* sda, uint32_t freq, uint32_t timeout) { + const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint32_t freq, uint32_t timeout) { shared_module_bitbangio_i2c_construct(&self->bitbang, scl, sda, freq, timeout); } @@ -59,12 +59,12 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { } uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, - const uint8_t * data, size_t len, bool transmit_stop_bit) { + const uint8_t *data, size_t len, bool transmit_stop_bit) { return shared_module_bitbangio_i2c_write(&self->bitbang, addr, data, len, transmit_stop_bit); } uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t * data, size_t len) { + uint8_t *data, size_t len) { return shared_module_bitbangio_i2c_read(&self->bitbang, addr, data, len); } diff --git a/shared-module/busio/OneWire.c b/shared-module/busio/OneWire.c index 6bb7dedcd1..80c55c7b2b 100644 --- a/shared-module/busio/OneWire.c +++ b/shared-module/busio/OneWire.c @@ -29,31 +29,31 @@ #include "shared-bindings/bitbangio/OneWire.h" #include "shared-module/busio/OneWire.h" -void common_hal_busio_onewire_construct(busio_onewire_obj_t* self, - const mcu_pin_obj_t* pin) { +void common_hal_busio_onewire_construct(busio_onewire_obj_t *self, + const mcu_pin_obj_t *pin) { shared_module_bitbangio_onewire_construct(&self->bitbang, pin); } -bool common_hal_busio_onewire_deinited(busio_onewire_obj_t* self) { +bool common_hal_busio_onewire_deinited(busio_onewire_obj_t *self) { return shared_module_bitbangio_onewire_deinited(&self->bitbang); } -void common_hal_busio_onewire_deinit(busio_onewire_obj_t* self) { +void common_hal_busio_onewire_deinit(busio_onewire_obj_t *self) { if (common_hal_busio_onewire_deinited(self)) { return; } shared_module_bitbangio_onewire_deinit(&self->bitbang); } -bool common_hal_busio_onewire_reset(busio_onewire_obj_t* self) { +bool common_hal_busio_onewire_reset(busio_onewire_obj_t *self) { return shared_module_bitbangio_onewire_reset(&self->bitbang); } -bool common_hal_busio_onewire_read_bit(busio_onewire_obj_t* self) { +bool common_hal_busio_onewire_read_bit(busio_onewire_obj_t *self) { return shared_module_bitbangio_onewire_read_bit(&self->bitbang); } -void common_hal_busio_onewire_write_bit(busio_onewire_obj_t* self, - bool bit) { +void common_hal_busio_onewire_write_bit(busio_onewire_obj_t *self, + bool bit) { shared_module_bitbangio_onewire_write_bit(&self->bitbang, bit); } diff --git a/shared-module/canio/Message.c b/shared-module/canio/Message.c index a1df4f693d..08e4d9fda7 100644 --- a/shared-module/canio/Message.c +++ b/shared-module/canio/Message.c @@ -28,8 +28,7 @@ #include -void common_hal_canio_message_construct(canio_message_obj_t *self, int id, void *data, size_t size, bool extended) -{ +void common_hal_canio_message_construct(canio_message_obj_t *self, int id, void *data, size_t size, bool extended) { self->id = id; self->size = size; self->extended = extended; @@ -38,40 +37,33 @@ void common_hal_canio_message_construct(canio_message_obj_t *self, int id, void } } -int common_hal_canio_message_get_id(const canio_message_obj_t *self) -{ +int common_hal_canio_message_get_id(const canio_message_obj_t *self) { return self->id; } -void common_hal_canio_message_set_id(canio_message_obj_t *self, int id) -{ +void common_hal_canio_message_set_id(canio_message_obj_t *self, int id) { self->id = id; } -const void *common_hal_canio_message_get_data(const canio_message_obj_t *self) -{ +const void *common_hal_canio_message_get_data(const canio_message_obj_t *self) { return self->data; } -const void common_hal_canio_message_set_data(canio_message_obj_t *self, const void *data, size_t size) -{ +const void common_hal_canio_message_set_data(canio_message_obj_t *self, const void *data, size_t size) { self->size = size; memcpy(self->data, data, size); } -size_t common_hal_canio_message_get_length(const canio_message_obj_t *self) -{ +size_t common_hal_canio_message_get_length(const canio_message_obj_t *self) { return self->size; } -bool common_hal_canio_message_get_extended(const canio_message_obj_t *self) -{ +bool common_hal_canio_message_get_extended(const canio_message_obj_t *self) { return self->extended; } -void common_hal_canio_message_set_extended(canio_message_obj_t *self, bool extended) -{ +void common_hal_canio_message_set_extended(canio_message_obj_t *self, bool extended) { self->extended = extended; } diff --git a/shared-module/canio/Message.h b/shared-module/canio/Message.h index 1ca0d42e2c..fafcaffe7a 100644 --- a/shared-module/canio/Message.h +++ b/shared-module/canio/Message.h @@ -32,6 +32,6 @@ typedef struct { mp_obj_base_t base; int id; uint8_t data[8]; - size_t size:4; - bool extended:1; + size_t size : 4; + bool extended : 1; } canio_message_obj_t; diff --git a/shared-module/canio/RemoteTransmissionRequest.c b/shared-module/canio/RemoteTransmissionRequest.c index 9b4d5632f8..55c0d3ba22 100644 --- a/shared-module/canio/RemoteTransmissionRequest.c +++ b/shared-module/canio/RemoteTransmissionRequest.c @@ -29,39 +29,32 @@ #include -void common_hal_canio_remote_transmission_request_construct(canio_remote_transmission_request_obj_t *self, int id, size_t size, bool extended) -{ +void common_hal_canio_remote_transmission_request_construct(canio_remote_transmission_request_obj_t *self, int id, size_t size, bool extended) { self->id = id; self->size = size; self->extended = extended; } -int common_hal_canio_remote_transmission_request_get_id(const canio_remote_transmission_request_obj_t *self) -{ +int common_hal_canio_remote_transmission_request_get_id(const canio_remote_transmission_request_obj_t *self) { return self->id; } -void common_hal_canio_remote_transmission_request_set_id(canio_remote_transmission_request_obj_t *self, int id) -{ +void common_hal_canio_remote_transmission_request_set_id(canio_remote_transmission_request_obj_t *self, int id) { self->id = id; } -size_t common_hal_canio_remote_transmission_request_get_length(const canio_remote_transmission_request_obj_t *self) -{ +size_t common_hal_canio_remote_transmission_request_get_length(const canio_remote_transmission_request_obj_t *self) { return self->size; } -void common_hal_canio_remote_transmission_request_set_length(canio_remote_transmission_request_obj_t *self, size_t size) -{ +void common_hal_canio_remote_transmission_request_set_length(canio_remote_transmission_request_obj_t *self, size_t size) { self->size = size; } -bool common_hal_canio_remote_transmission_request_get_extended(const canio_remote_transmission_request_obj_t *self) -{ +bool common_hal_canio_remote_transmission_request_get_extended(const canio_remote_transmission_request_obj_t *self) { return self->extended; } -void common_hal_canio_remote_transmission_request_set_extended(canio_remote_transmission_request_obj_t *self, bool extended) -{ +void common_hal_canio_remote_transmission_request_set_extended(canio_remote_transmission_request_obj_t *self, bool extended) { self->extended = extended; } diff --git a/shared-module/displayio/Bitmap.c b/shared-module/displayio/Bitmap.c index 1831ac697d..f03ade84b1 100644 --- a/shared-module/displayio/Bitmap.c +++ b/shared-module/displayio/Bitmap.c @@ -57,7 +57,7 @@ void common_hal_displayio_bitmap_construct(displayio_bitmap_t *self, uint32_t wi self->x_shift = 0; // Used to divide the index by the number of pixels per word. Its used in a // shift which effectively divides by 2 ** x_shift. uint32_t power_of_two = 1; - while (power_of_two < align_bits / bits_per_value ) { + while (power_of_two < align_bits / bits_per_value) { self->x_shift++; power_of_two <<= 1; } @@ -93,13 +93,13 @@ uint32_t common_hal_displayio_bitmap_get_pixel(displayio_bitmap_t *self, int16_t return (word >> (sizeof(size_t) * 8 - ((x & self->x_mask) + 1) * self->bits_per_value)) & self->bitmask; } else { - size_t* row = self->data + row_start; + size_t *row = self->data + row_start; if (bytes_per_value == 1) { - return ((uint8_t*) row)[x]; + return ((uint8_t *)row)[x]; } else if (bytes_per_value == 2) { - return ((uint16_t*) row)[x]; + return ((uint16_t *)row)[x]; } else if (bytes_per_value == 4) { - return ((uint32_t*) row)[x]; + return ((uint32_t *)row)[x]; } } return 0; @@ -157,19 +157,19 @@ void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y word |= (value & self->bitmask) << bit_position; self->data[index] = word; } else { - size_t* row = self->data + row_start; + size_t *row = self->data + row_start; if (bytes_per_value == 1) { - ((uint8_t*) row)[x] = value; + ((uint8_t *)row)[x] = value; } else if (bytes_per_value == 2) { - ((uint16_t*) row)[x] = value; + ((uint16_t *)row)[x] = value; } else if (bytes_per_value == 4) { - ((uint32_t*) row)[x] = value; + ((uint32_t *)row)[x] = value; } } } void common_hal_displayio_bitmap_blit(displayio_bitmap_t *self, int16_t x, int16_t y, displayio_bitmap_t *source, - int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint32_t skip_index, bool skip_index_none) { + int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint32_t skip_index, bool skip_index_none) { // Copy region of "source" bitmap into "self" bitmap at location x,y in the "self" // If skip_value is encountered in the source bitmap, it will not be copied. // If skip_value is `None`, then all pixels are copied. @@ -180,11 +180,11 @@ void common_hal_displayio_bitmap_blit(displayio_bitmap_t *self, int16_t x, int16 } // Update the dirty area - int16_t dirty_x_max = (x + (x2-x1)); + int16_t dirty_x_max = (x + (x2 - x1)); if (dirty_x_max > self->width) { dirty_x_max = self->width; } - int16_t dirty_y_max = y + (y2-y1); + int16_t dirty_y_max = y + (y2 - y1); if (dirty_y_max > self->height) { dirty_y_max = self->height; } @@ -203,21 +203,21 @@ void common_hal_displayio_bitmap_blit(displayio_bitmap_t *self, int16_t x, int16 } // simplest version - use internal functions for get/set pixels - for (int16_t i=0; i < (x2-x1); i++) { + for (int16_t i = 0; i < (x2 - x1); i++) { - const int xs_index = x_reverse ? ( (x2) - i - 1) : x1+i; // x-index into the source bitmap - const int xd_index = x_reverse ? ((x + (x2-x1)) - i - 1) : x+i; // x-index into the destination bitmap + const int xs_index = x_reverse ? ((x2) - i - 1) : x1 + i; // x-index into the source bitmap + const int xd_index = x_reverse ? ((x + (x2 - x1)) - i - 1) : x + i; // x-index into the destination bitmap - if ( (xd_index >= 0) && (xd_index < self->width) ) { - for (int16_t j=0; j < (y2-y1) ; j++){ + if ((xd_index >= 0) && (xd_index < self->width)) { + for (int16_t j = 0; j < (y2 - y1); j++) { - const int ys_index = y_reverse ? ( (y2 ) - j - 1) : y1+j ; // y-index into the source bitmap - const int yd_index = y_reverse ? ((y + (y2-y1)) - j - 1) : y+j ; // y-index into the destination bitmap + const int ys_index = y_reverse ? ((y2) - j - 1) : y1 + j; // y-index into the source bitmap + const int yd_index = y_reverse ? ((y + (y2 - y1)) - j - 1) : y + j; // y-index into the destination bitmap - if ((yd_index >= 0) && (yd_index < self->height) ) { + if ((yd_index >= 0) && (yd_index < self->height)) { uint32_t value = common_hal_displayio_bitmap_get_pixel(source, xs_index, ys_index); - if ( (skip_index_none) || (value != skip_index) ) { // write if skip_value_none is True - displayio_bitmap_write_pixel(self, xd_index, yd_index, value); + if ((skip_index_none) || (value != skip_index)) { // write if skip_value_none is True + displayio_bitmap_write_pixel(self, xd_index, yd_index, value); } } } @@ -231,14 +231,14 @@ void common_hal_displayio_bitmap_set_pixel(displayio_bitmap_t *self, int16_t x, } // update the dirty region - displayio_bitmap_set_dirty_area(self, x, y, x+1, y+1); + displayio_bitmap_set_dirty_area(self, x, y, x + 1, y + 1); // write the pixel displayio_bitmap_write_pixel(self, x, y, value); } -displayio_area_t* displayio_bitmap_get_refresh_areas(displayio_bitmap_t *self, displayio_area_t* tail) { +displayio_area_t *displayio_bitmap_get_refresh_areas(displayio_bitmap_t *self, displayio_area_t *tail) { if (self->dirty_area.x1 == self->dirty_area.x2) { return tail; } @@ -263,11 +263,11 @@ void common_hal_displayio_bitmap_fill(displayio_bitmap_t *self, uint32_t value) // build the packed word uint32_t word = 0; - for (uint8_t i=0; i<32 / self->bits_per_value; i++) { - word |= (value & self->bitmask) << (32 - ((i+1)*self->bits_per_value)); + for (uint8_t i = 0; i < 32 / self->bits_per_value; i++) { + word |= (value & self->bitmask) << (32 - ((i + 1) * self->bits_per_value)); } // copy it in - for (uint32_t i=0; istride * self->height; i++) { + for (uint32_t i = 0; i < self->stride * self->height; i++) { self->data[i] = word; } } diff --git a/shared-module/displayio/Bitmap.h b/shared-module/displayio/Bitmap.h index d6aaaa8bac..c1ce9612b1 100644 --- a/shared-module/displayio/Bitmap.h +++ b/shared-module/displayio/Bitmap.h @@ -37,7 +37,7 @@ typedef struct { mp_obj_base_t base; uint16_t width; uint16_t height; - size_t* data; + size_t *data; uint16_t stride; // size_t's uint8_t bits_per_value; uint8_t x_shift; @@ -48,7 +48,7 @@ typedef struct { } displayio_bitmap_t; void displayio_bitmap_finish_refresh(displayio_bitmap_t *self); -displayio_area_t* displayio_bitmap_get_refresh_areas(displayio_bitmap_t *self, displayio_area_t* tail); +displayio_area_t *displayio_bitmap_get_refresh_areas(displayio_bitmap_t *self, displayio_area_t *tail); void displayio_bitmap_set_dirty_area(displayio_bitmap_t *self, int16_t x1, int16_t y1, int16_t x2, int16_t y2); void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value); diff --git a/shared-module/displayio/ColorConverter.c b/shared-module/displayio/ColorConverter.c index 40dcd9d167..be9e9dc1a5 100644 --- a/shared-module/displayio/ColorConverter.c +++ b/shared-module/displayio/ColorConverter.c @@ -31,18 +31,17 @@ #define NO_TRANSPARENT_COLOR (0x1000000) -uint32_t displayio_colorconverter_dither_noise_1 (uint32_t n) -{ - n = (n >> 13) ^ n; - int nn = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff; - return (uint32_t) (((float)nn / (1073741824.0f*2)) * 255); +uint32_t displayio_colorconverter_dither_noise_1(uint32_t n) { + n = (n >> 13) ^ n; + int nn = (n * (n * n * 60493 + 19990303) + 1376312589) & 0x7fffffff; + return (uint32_t)(((float)nn / (1073741824.0f * 2)) * 255); } uint32_t displayio_colorconverter_dither_noise_2(uint32_t x, uint32_t y) { return displayio_colorconverter_dither_noise_1(x + y * 0xFFFF); } -void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t* self, bool dither) { +void common_hal_displayio_colorconverter_construct(displayio_colorconverter_t *self, bool dither) { self->dither = dither; self->transparent_color = NO_TRANSPARENT_COLOR; } @@ -83,11 +82,11 @@ uint8_t displayio_colorconverter_compute_hue(uint32_t color_rgb888) { int32_t hue = 0; if (max == r8) { - hue = (((int32_t) (g8 - b8) * 40) / c) % 240; + hue = (((int32_t)(g8 - b8) * 40) / c) % 240; } else if (max == g8) { - hue = (((int32_t) (b8 - r8) + (2 * c)) * 40) / c; + hue = (((int32_t)(b8 - r8) + (2 * c)) * 40) / c; } else if (max == b8) { - hue = (((int32_t) (r8 - g8) + (4 * c)) * 40) / c; + hue = (((int32_t)(r8 - g8) + (4 * c)) * 40) / c; } if (hue < 0) { hue += 240; @@ -96,7 +95,7 @@ uint8_t displayio_colorconverter_compute_hue(uint32_t color_rgb888) { return hue; } -void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t* colorspace, uint8_t pixel_hue, uint8_t pixel_luma, uint32_t* color) { +void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_hue, uint8_t pixel_luma, uint32_t *color) { int16_t hue_diff = colorspace->tricolor_hue - pixel_hue; if ((-10 <= hue_diff && hue_diff <= 10) || hue_diff <= -220 || hue_diff >= 220) { @@ -110,7 +109,7 @@ void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t* co } } -void common_hal_displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t* colorspace, uint32_t input_color, uint32_t* output_color) { +void common_hal_displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t *colorspace, uint32_t input_color, uint32_t *output_color) { displayio_input_pixel_t input_pixel; input_pixel.pixel = input_color; input_pixel.x = input_pixel.y = input_pixel.tile = input_pixel.tile_x = input_pixel.tile_y = 0; @@ -124,28 +123,28 @@ void common_hal_displayio_colorconverter_convert(displayio_colorconverter_t *sel (*output_color) = output_pixel.pixel; } -void common_hal_displayio_colorconverter_set_dither(displayio_colorconverter_t* self, bool dither) { +void common_hal_displayio_colorconverter_set_dither(displayio_colorconverter_t *self, bool dither) { self->dither = dither; } -bool common_hal_displayio_colorconverter_get_dither(displayio_colorconverter_t* self) { +bool common_hal_displayio_colorconverter_get_dither(displayio_colorconverter_t *self) { return self->dither; } -void common_hal_displayio_colorconverter_make_transparent(displayio_colorconverter_t* self, uint32_t transparent_color) { +void common_hal_displayio_colorconverter_make_transparent(displayio_colorconverter_t *self, uint32_t transparent_color) { if (self->transparent_color != NO_TRANSPARENT_COLOR) { mp_raise_RuntimeError(translate("Only one color can be transparent at a time")); } self->transparent_color = transparent_color; } -void common_hal_displayio_colorconverter_make_opaque(displayio_colorconverter_t* self, uint32_t transparent_color) { - (void) transparent_color; +void common_hal_displayio_colorconverter_make_opaque(displayio_colorconverter_t *self, uint32_t transparent_color) { + (void)transparent_color; // NO_TRANSPARENT_COLOR will never equal a valid color self->transparent_color = NO_TRANSPARENT_COLOR; } -void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t* colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color) { +void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t *colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color) { uint32_t pixel = input_pixel->pixel; if (self->transparent_color == pixel) { @@ -153,19 +152,19 @@ void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _d return; } - if (self->dither){ + if (self->dither) { uint8_t randr = (displayio_colorconverter_dither_noise_2(input_pixel->tile_x,input_pixel->tile_y)); - uint8_t randg = (displayio_colorconverter_dither_noise_2(input_pixel->tile_x+33,input_pixel->tile_y)); - uint8_t randb = (displayio_colorconverter_dither_noise_2(input_pixel->tile_x,input_pixel->tile_y+33)); + uint8_t randg = (displayio_colorconverter_dither_noise_2(input_pixel->tile_x + 33,input_pixel->tile_y)); + uint8_t randb = (displayio_colorconverter_dither_noise_2(input_pixel->tile_x,input_pixel->tile_y + 33)); uint32_t r8 = (pixel >> 16); uint32_t g8 = (pixel >> 8) & 0xff; uint32_t b8 = pixel & 0xff; if (colorspace->depth == 16) { - b8 = MIN(255,b8 + (randb&0x07)); - r8 = MIN(255,r8 + (randr&0x07)); - g8 = MIN(255,g8 + (randg&0x03)); + b8 = MIN(255,b8 + (randb & 0x07)); + r8 = MIN(255,r8 + (randr & 0x07)); + g8 = MIN(255,g8 + (randg & 0x03)); } else { int bitmask = 0xFF >> colorspace->depth; b8 = MIN(255,b8 + (randb & bitmask)); @@ -197,7 +196,7 @@ void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _d uint8_t pixel_hue = displayio_colorconverter_compute_hue(pixel); displayio_colorconverter_compute_tricolor(colorspace, pixel_hue, luma, &output_color->pixel); return; - } else if (colorspace->grayscale && colorspace->depth <= 8) { + } else if (colorspace->grayscale && colorspace->depth <= 8) { uint8_t luma = displayio_colorconverter_compute_luma(pixel); size_t bitmask = (1 << colorspace->depth) - 1; output_color->pixel = (luma >> colorspace->grayscale_bit) & bitmask; diff --git a/shared-module/displayio/ColorConverter.h b/shared-module/displayio/ColorConverter.h index b402625ef7..ebe4b27194 100644 --- a/shared-module/displayio/ColorConverter.h +++ b/shared-module/displayio/ColorConverter.h @@ -41,15 +41,15 @@ typedef struct { bool displayio_colorconverter_needs_refresh(displayio_colorconverter_t *self); void displayio_colorconverter_finish_refresh(displayio_colorconverter_t *self); -void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t* colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color); +void displayio_colorconverter_convert(displayio_colorconverter_t *self, const _displayio_colorspace_t *colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color); -uint32_t displayio_colorconverter_dither_noise_1 (uint32_t n); +uint32_t displayio_colorconverter_dither_noise_1(uint32_t n); uint32_t displayio_colorconverter_dither_noise_2(uint32_t x, uint32_t y); uint16_t displayio_colorconverter_compute_rgb565(uint32_t color_rgb888); uint8_t displayio_colorconverter_compute_luma(uint32_t color_rgb888); uint8_t displayio_colorconverter_compute_chroma(uint32_t color_rgb888); uint8_t displayio_colorconverter_compute_hue(uint32_t color_rgb888); -void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t* colorspace, uint8_t pixel_hue, uint8_t pixel_luma, uint32_t* color); +void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_hue, uint8_t pixel_luma, uint32_t *color); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_COLORCONVERTER_H diff --git a/shared-module/displayio/Display.c b/shared-module/displayio/Display.c index 7c8c9280b5..63e098e081 100644 --- a/shared-module/displayio/Display.c +++ b/shared-module/displayio/Display.c @@ -41,15 +41,15 @@ #include #include -void common_hal_displayio_display_construct(displayio_display_obj_t* self, - mp_obj_t bus, uint16_t width, uint16_t height, int16_t colstart, int16_t rowstart, - uint16_t rotation, uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, - uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word, uint8_t set_column_command, - uint8_t set_row_command, uint8_t write_ram_command, uint8_t set_vertical_scroll, - uint8_t* init_sequence, uint16_t init_sequence_len, const mcu_pin_obj_t* backlight_pin, - uint16_t brightness_command, mp_float_t brightness, bool auto_brightness, - bool single_byte_bounds, bool data_as_commands, bool auto_refresh, uint16_t native_frames_per_second, - bool backlight_on_high, bool SH1107_addressing) { +void common_hal_displayio_display_construct(displayio_display_obj_t *self, + mp_obj_t bus, uint16_t width, uint16_t height, int16_t colstart, int16_t rowstart, + uint16_t rotation, uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, + uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word, uint8_t set_column_command, + uint8_t set_row_command, uint8_t write_ram_command, uint8_t set_vertical_scroll, + uint8_t *init_sequence, uint16_t init_sequence_len, const mcu_pin_obj_t *backlight_pin, + uint16_t brightness_command, mp_float_t brightness, bool auto_brightness, + bool single_byte_bounds, bool data_as_commands, bool auto_refresh, uint16_t native_frames_per_second, + bool backlight_on_high, bool SH1107_addressing) { // Turn off auto-refresh as we init. self->auto_refresh = false; @@ -141,34 +141,34 @@ void common_hal_displayio_display_construct(displayio_display_obj_t* self, common_hal_displayio_display_set_auto_refresh(self, auto_refresh); } -bool common_hal_displayio_display_show(displayio_display_obj_t* self, displayio_group_t* root_group) { +bool common_hal_displayio_display_show(displayio_display_obj_t *self, displayio_group_t *root_group) { return displayio_display_core_show(&self->core, root_group); } -uint16_t common_hal_displayio_display_get_width(displayio_display_obj_t* self){ +uint16_t common_hal_displayio_display_get_width(displayio_display_obj_t *self) { return displayio_display_core_get_width(&self->core); } -uint16_t common_hal_displayio_display_get_height(displayio_display_obj_t* self){ +uint16_t common_hal_displayio_display_get_height(displayio_display_obj_t *self) { return displayio_display_core_get_height(&self->core); } -bool common_hal_displayio_display_get_auto_brightness(displayio_display_obj_t* self) { +bool common_hal_displayio_display_get_auto_brightness(displayio_display_obj_t *self) { return self->auto_brightness; } -void common_hal_displayio_display_set_auto_brightness(displayio_display_obj_t* self, bool auto_brightness) { +void common_hal_displayio_display_set_auto_brightness(displayio_display_obj_t *self, bool auto_brightness) { self->auto_brightness = auto_brightness; } -mp_float_t common_hal_displayio_display_get_brightness(displayio_display_obj_t* self) { +mp_float_t common_hal_displayio_display_get_brightness(displayio_display_obj_t *self) { return self->current_brightness; } -bool common_hal_displayio_display_set_brightness(displayio_display_obj_t* self, mp_float_t brightness) { +bool common_hal_displayio_display_set_brightness(displayio_display_obj_t *self, mp_float_t brightness) { self->updating_backlight = true; - if (!self->backlight_on_high){ - brightness = 1.0-brightness; + if (!self->backlight_on_high) { + brightness = 1.0 - brightness; } bool ok = false; @@ -181,7 +181,7 @@ bool common_hal_displayio_display_set_brightness(displayio_display_obj_t* self, if (ispwm) { #if (CIRCUITPY_PULSEIO) - common_hal_pwmio_pwmout_set_duty_cycle(&self->backlight_pwm, (uint16_t) (0xffff * brightness)); + common_hal_pwmio_pwmout_set_duty_cycle(&self->backlight_pwm, (uint16_t)(0xffff * brightness)); ok = true; #else ok = false; @@ -193,7 +193,7 @@ bool common_hal_displayio_display_set_brightness(displayio_display_obj_t* self, ok = displayio_display_core_begin_transaction(&self->core); if (ok) { if (self->data_as_commands) { - uint8_t set_brightness[2] = {self->brightness_command, (uint8_t) (0xff * brightness)}; + uint8_t set_brightness[2] = {self->brightness_command, (uint8_t)(0xff * brightness)}; self->core.send(self->core.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, set_brightness, 2); } else { uint8_t command = self->brightness_command; @@ -212,11 +212,11 @@ bool common_hal_displayio_display_set_brightness(displayio_display_obj_t* self, return ok; } -mp_obj_t common_hal_displayio_display_get_bus(displayio_display_obj_t* self) { +mp_obj_t common_hal_displayio_display_get_bus(displayio_display_obj_t *self) { return self->core.bus; } -STATIC const displayio_area_t* _get_refresh_areas(displayio_display_obj_t *self) { +STATIC const displayio_area_t *_get_refresh_areas(displayio_display_obj_t *self) { if (self->core.full_refresh) { self->core.area.next = NULL; return &self->core.area; @@ -226,14 +226,14 @@ STATIC const displayio_area_t* _get_refresh_areas(displayio_display_obj_t *self) return NULL; } -STATIC void _send_pixels(displayio_display_obj_t* self, uint8_t* pixels, uint32_t length) { +STATIC void _send_pixels(displayio_display_obj_t *self, uint8_t *pixels, uint32_t length) { if (!self->data_as_commands) { self->core.send(self->core.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &self->write_ram_command, 1); } self->core.send(self->core.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, pixels, length); } -STATIC bool _refresh_area(displayio_display_obj_t* self, const displayio_area_t* area) { +STATIC bool _refresh_area(displayio_display_obj_t *self, const displayio_area_t *area) { uint16_t buffer_size = 128; // In uint32_ts displayio_area_t clipped; @@ -294,8 +294,8 @@ STATIC bool _refresh_area(displayio_display_obj_t* self, const displayio_area_t* remaining_rows -= rows_per_buffer; displayio_display_core_set_region_to_update(&self->core, self->set_column_command, - self->set_row_command, NO_COMMAND, NO_COMMAND, self->data_as_commands, false, - &subrectangle, self->SH1107_addressing); + self->set_row_command, NO_COMMAND, NO_COMMAND, self->data_as_commands, false, + &subrectangle, self->SH1107_addressing); uint16_t subrectangle_size_bytes; if (self->core.colorspace.depth >= 8) { @@ -315,7 +315,7 @@ STATIC bool _refresh_area(displayio_display_obj_t* self, const displayio_area_t* } displayio_display_core_begin_transaction(&self->core); - _send_pixels(self, (uint8_t*) buffer, subrectangle_size_bytes); + _send_pixels(self, (uint8_t *)buffer, subrectangle_size_bytes); displayio_display_core_end_transaction(&self->core); // TODO(tannewt): Make refresh displays faster so we don't starve other @@ -325,12 +325,12 @@ STATIC bool _refresh_area(displayio_display_obj_t* self, const displayio_area_t* return true; } -STATIC void _refresh_display(displayio_display_obj_t* self) { +STATIC void _refresh_display(displayio_display_obj_t *self) { if (!displayio_display_core_start_refresh(&self->core)) { // A refresh on this bus is already in progress. Try next display. return; } - const displayio_area_t* current_area = _get_refresh_areas(self); + const displayio_area_t *current_area = _get_refresh_areas(self); while (current_area != NULL) { _refresh_area(self, current_area); current_area = current_area->next; @@ -338,10 +338,10 @@ STATIC void _refresh_display(displayio_display_obj_t* self) { displayio_display_core_finish_refresh(&self->core); } -void common_hal_displayio_display_set_rotation(displayio_display_obj_t* self, int rotation){ +void common_hal_displayio_display_set_rotation(displayio_display_obj_t *self, int rotation) { bool transposed = (self->core.rotation == 90 || self->core.rotation == 270); bool will_transposed = (rotation == 90 || rotation == 270); - if(transposed != will_transposed) { + if (transposed != will_transposed) { int tmp = self->core.width; self->core.width = self->core.height; self->core.height = tmp; @@ -356,13 +356,13 @@ void common_hal_displayio_display_set_rotation(displayio_display_obj_t* self, in } } -uint16_t common_hal_displayio_display_get_rotation(displayio_display_obj_t* self){ +uint16_t common_hal_displayio_display_get_rotation(displayio_display_obj_t *self) { return self->core.rotation; } -bool common_hal_displayio_display_refresh(displayio_display_obj_t* self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame) { - if (!self->auto_refresh && !self->first_manual_refresh && (target_ms_per_frame != 0xffffffff) ) { +bool common_hal_displayio_display_refresh(displayio_display_obj_t *self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame) { + if (!self->auto_refresh && !self->first_manual_refresh && (target_ms_per_frame != 0xffffffff)) { uint64_t current_time = supervisor_ticks_ms64(); uint32_t current_ms_since_real_refresh = current_time - self->core.last_refresh; // Test to see if the real frame time is below our minimum. @@ -386,12 +386,12 @@ bool common_hal_displayio_display_refresh(displayio_display_obj_t* self, uint32_ return true; } -bool common_hal_displayio_display_get_auto_refresh(displayio_display_obj_t* self) { +bool common_hal_displayio_display_get_auto_refresh(displayio_display_obj_t *self) { return self->auto_refresh; } -void common_hal_displayio_display_set_auto_refresh(displayio_display_obj_t* self, - bool auto_refresh) { +void common_hal_displayio_display_set_auto_refresh(displayio_display_obj_t *self, + bool auto_refresh) { self->first_manual_refresh = !auto_refresh; if (auto_refresh != self->auto_refresh) { if (auto_refresh) { @@ -403,7 +403,7 @@ void common_hal_displayio_display_set_auto_refresh(displayio_display_obj_t* self self->auto_refresh = auto_refresh; } -STATIC void _update_backlight(displayio_display_obj_t* self) { +STATIC void _update_backlight(displayio_display_obj_t *self) { if (!self->auto_brightness || self->updating_backlight) { return; } @@ -417,7 +417,7 @@ STATIC void _update_backlight(displayio_display_obj_t* self) { self->last_backlight_refresh = supervisor_ticks_ms64(); } -void displayio_display_background(displayio_display_obj_t* self) { +void displayio_display_background(displayio_display_obj_t *self) { _update_backlight(self); if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) { @@ -425,7 +425,7 @@ void displayio_display_background(displayio_display_obj_t* self) { } } -void release_display(displayio_display_obj_t* self) { +void release_display(displayio_display_obj_t *self) { common_hal_displayio_display_set_auto_refresh(self, false); release_display_core(&self->core); #if (CIRCUITPY_PULSEIO) @@ -440,12 +440,12 @@ void release_display(displayio_display_obj_t* self) { #endif } -void reset_display(displayio_display_obj_t* self) { +void reset_display(displayio_display_obj_t *self) { common_hal_displayio_display_set_auto_refresh(self, true); self->auto_brightness = true; common_hal_displayio_display_show(self, NULL); } -void displayio_display_collect_ptrs(displayio_display_obj_t* self) { +void displayio_display_collect_ptrs(displayio_display_obj_t *self) { displayio_display_core_collect_ptrs(&self->core); } diff --git a/shared-module/displayio/Display.h b/shared-module/displayio/Display.h index cc9cd54c40..a0049f00c0 100644 --- a/shared-module/displayio/Display.h +++ b/shared-module/displayio/Display.h @@ -64,10 +64,10 @@ typedef struct { bool SH1107_addressing; } displayio_display_obj_t; -void displayio_display_background(displayio_display_obj_t* self); -void release_display(displayio_display_obj_t* self); -void reset_display(displayio_display_obj_t* self); +void displayio_display_background(displayio_display_obj_t *self); +void release_display(displayio_display_obj_t *self); +void reset_display(displayio_display_obj_t *self); -void displayio_display_collect_ptrs(displayio_display_obj_t* self); +void displayio_display_collect_ptrs(displayio_display_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_DISPLAY_H diff --git a/shared-module/displayio/EPaperDisplay.c b/shared-module/displayio/EPaperDisplay.c index 3fb37ff219..7eff587757 100644 --- a/shared-module/displayio/EPaperDisplay.c +++ b/shared-module/displayio/EPaperDisplay.c @@ -42,15 +42,15 @@ #include #include -void common_hal_displayio_epaperdisplay_construct(displayio_epaperdisplay_obj_t* self, - mp_obj_t bus, const uint8_t* start_sequence, uint16_t start_sequence_len, - const uint8_t* stop_sequence, uint16_t stop_sequence_len, - uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, - int16_t colstart, int16_t rowstart, uint16_t rotation, - uint16_t set_column_window_command, uint16_t set_row_window_command, - uint16_t set_current_column_command, uint16_t set_current_row_command, - uint16_t write_black_ram_command, bool black_bits_inverted, uint16_t write_color_ram_command, bool color_bits_inverted, uint32_t highlight_color, uint16_t refresh_display_command, mp_float_t refresh_time, - const mcu_pin_obj_t* busy_pin, bool busy_state, mp_float_t seconds_per_frame, bool chip_select, bool grayscale) { +void common_hal_displayio_epaperdisplay_construct(displayio_epaperdisplay_obj_t *self, + mp_obj_t bus, const uint8_t *start_sequence, uint16_t start_sequence_len, + const uint8_t *stop_sequence, uint16_t stop_sequence_len, + uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, + int16_t colstart, int16_t rowstart, uint16_t rotation, + uint16_t set_column_window_command, uint16_t set_row_window_command, + uint16_t set_current_column_command, uint16_t set_current_row_command, + uint16_t write_black_ram_command, bool black_bits_inverted, uint16_t write_color_ram_command, bool color_bits_inverted, uint32_t highlight_color, uint16_t refresh_display_command, mp_float_t refresh_time, + const mcu_pin_obj_t *busy_pin, bool busy_state, mp_float_t seconds_per_frame, bool chip_select, bool grayscale) { if (highlight_color != 0x000000) { self->core.colorspace.tricolor = true; self->core.colorspace.tricolor_hue = displayio_colorconverter_compute_hue(highlight_color); @@ -97,16 +97,16 @@ void common_hal_displayio_epaperdisplay_construct(displayio_epaperdisplay_obj_t* common_hal_displayio_epaperdisplay_show(self, &circuitpython_splash); } -bool common_hal_displayio_epaperdisplay_show(displayio_epaperdisplay_obj_t* self, displayio_group_t* root_group) { +bool common_hal_displayio_epaperdisplay_show(displayio_epaperdisplay_obj_t *self, displayio_group_t *root_group) { return displayio_display_core_show(&self->core, root_group); } -const displayio_area_t* displayio_epaperdisplay_get_refresh_areas(displayio_epaperdisplay_obj_t *self) { +const displayio_area_t *displayio_epaperdisplay_get_refresh_areas(displayio_epaperdisplay_obj_t *self) { if (self->core.full_refresh) { self->core.area.next = NULL; return &self->core.area; } - const displayio_area_t* first_area = NULL; + const displayio_area_t *first_area = NULL; if (self->core.current_group != NULL) { first_area = displayio_group_get_refresh_areas(self->core.current_group, NULL); } @@ -117,15 +117,15 @@ const displayio_area_t* displayio_epaperdisplay_get_refresh_areas(displayio_epap return first_area; } -uint16_t common_hal_displayio_epaperdisplay_get_width(displayio_epaperdisplay_obj_t* self){ +uint16_t common_hal_displayio_epaperdisplay_get_width(displayio_epaperdisplay_obj_t *self) { return displayio_display_core_get_width(&self->core); } -uint16_t common_hal_displayio_epaperdisplay_get_height(displayio_epaperdisplay_obj_t* self){ +uint16_t common_hal_displayio_epaperdisplay_get_height(displayio_epaperdisplay_obj_t *self) { return displayio_display_core_get_height(&self->core); } -STATIC void wait_for_busy(displayio_epaperdisplay_obj_t* self) { +STATIC void wait_for_busy(displayio_epaperdisplay_obj_t *self) { if (self->busy.base.type == &mp_type_NoneType) { return; } @@ -134,8 +134,8 @@ STATIC void wait_for_busy(displayio_epaperdisplay_obj_t* self) { } } -STATIC void send_command_sequence(displayio_epaperdisplay_obj_t* self, - bool should_wait_for_busy, const uint8_t* sequence, uint32_t sequence_len) { +STATIC void send_command_sequence(displayio_epaperdisplay_obj_t *self, + bool should_wait_for_busy, const uint8_t *sequence, uint32_t sequence_len) { uint32_t i = 0; while (i < sequence_len) { const uint8_t *cmd = sequence + i; @@ -163,7 +163,7 @@ STATIC void send_command_sequence(displayio_epaperdisplay_obj_t* self, } } -void displayio_epaperdisplay_start_refresh(displayio_epaperdisplay_obj_t* self) { +void displayio_epaperdisplay_start_refresh(displayio_epaperdisplay_obj_t *self) { // run start sequence self->core.bus_reset(self->core.bus); @@ -171,7 +171,7 @@ void displayio_epaperdisplay_start_refresh(displayio_epaperdisplay_obj_t* self) displayio_display_core_start_refresh(&self->core); } -uint32_t common_hal_displayio_epaperdisplay_get_time_to_refresh(displayio_epaperdisplay_obj_t* self) { +uint32_t common_hal_displayio_epaperdisplay_get_time_to_refresh(displayio_epaperdisplay_obj_t *self) { if (self->core.last_refresh == 0) { return 0; } @@ -183,7 +183,7 @@ uint32_t common_hal_displayio_epaperdisplay_get_time_to_refresh(displayio_epaper return self->milliseconds_per_frame - elapsed_time; } -void displayio_epaperdisplay_finish_refresh(displayio_epaperdisplay_obj_t* self) { +void displayio_epaperdisplay_finish_refresh(displayio_epaperdisplay_obj_t *self) { // Actually refresh the display now that all pixel RAM has been updated. displayio_display_core_begin_transaction(&self->core); self->core.send(self->core.bus, DISPLAY_COMMAND, self->chip_select, &self->refresh_display_command, 1); @@ -194,14 +194,14 @@ void displayio_epaperdisplay_finish_refresh(displayio_epaperdisplay_obj_t* self) displayio_display_core_finish_refresh(&self->core); } -mp_obj_t common_hal_displayio_epaperdisplay_get_bus(displayio_epaperdisplay_obj_t* self) { +mp_obj_t common_hal_displayio_epaperdisplay_get_bus(displayio_epaperdisplay_obj_t *self) { return self->core.bus; } -void common_hal_displayio_epaperdisplay_set_rotation(displayio_epaperdisplay_obj_t* self, int rotation){ +void common_hal_displayio_epaperdisplay_set_rotation(displayio_epaperdisplay_obj_t *self, int rotation) { bool transposed = (self->core.rotation == 90 || self->core.rotation == 270); bool will_transposed = (rotation == 90 || rotation == 270); - if(transposed != will_transposed) { + if (transposed != will_transposed) { int tmp = self->core.width; self->core.width = self->core.height; self->core.height = tmp; @@ -216,12 +216,12 @@ void common_hal_displayio_epaperdisplay_set_rotation(displayio_epaperdisplay_obj } } -uint16_t common_hal_displayio_epaperdisplay_get_rotation(displayio_epaperdisplay_obj_t* self){ +uint16_t common_hal_displayio_epaperdisplay_get_rotation(displayio_epaperdisplay_obj_t *self) { return self->core.rotation; } -bool displayio_epaperdisplay_refresh_area(displayio_epaperdisplay_obj_t* self, const displayio_area_t* area) { +bool displayio_epaperdisplay_refresh_area(displayio_epaperdisplay_obj_t *self, const displayio_area_t *area) { uint16_t buffer_size = 128; // In uint32_ts displayio_area_t clipped; @@ -264,8 +264,8 @@ bool displayio_epaperdisplay_refresh_area(displayio_epaperdisplay_obj_t* self, c if (self->set_row_window_command != NO_COMMAND) { displayio_display_core_set_region_to_update(&self->core, self->set_column_window_command, - self->set_row_window_command, self->set_current_column_command, self->set_current_row_command, - false, self->chip_select, &clipped, false /* SH1107_addressing */); + self->set_row_window_command, self->set_current_column_command, self->set_current_row_command, + false, self->chip_select, &clipped, false /* SH1107_addressing */); } uint8_t write_command = self->write_black_ram_command; @@ -317,7 +317,7 @@ bool displayio_epaperdisplay_refresh_area(displayio_epaperdisplay_obj_t* self, c // Can't acquire display bus; skip the rest of the data. Try next display. return false; } - self->core.send(self->core.bus, DISPLAY_DATA, self->chip_select, (uint8_t*) buffer, subrectangle_size_bytes); + self->core.send(self->core.bus, DISPLAY_DATA, self->chip_select, (uint8_t *)buffer, subrectangle_size_bytes); displayio_display_core_end_transaction(&self->core); // TODO(tannewt): Make refresh displays faster so we don't starve other @@ -329,7 +329,7 @@ bool displayio_epaperdisplay_refresh_area(displayio_epaperdisplay_obj_t* self, c return true; } -bool common_hal_displayio_epaperdisplay_refresh(displayio_epaperdisplay_obj_t* self) { +bool common_hal_displayio_epaperdisplay_refresh(displayio_epaperdisplay_obj_t *self) { if (self->refreshing && self->busy.base.type == &digitalio_digitalinout_type) { if (common_hal_digitalio_digitalinout_get_value(&self->busy) != self->busy_state) { @@ -352,7 +352,7 @@ bool common_hal_displayio_epaperdisplay_refresh(displayio_epaperdisplay_obj_t* s // Can't acquire display bus; skip updating this display. Try next display. return false; } - const displayio_area_t* current_area = displayio_epaperdisplay_get_refresh_areas(self); + const displayio_area_t *current_area = displayio_epaperdisplay_get_refresh_areas(self); if (current_area == NULL) { return true; } @@ -365,7 +365,7 @@ bool common_hal_displayio_epaperdisplay_refresh(displayio_epaperdisplay_obj_t* s return true; } -void displayio_epaperdisplay_background(displayio_epaperdisplay_obj_t* self) { +void displayio_epaperdisplay_background(displayio_epaperdisplay_obj_t *self) { if (self->refreshing) { bool refresh_done = false; if (self->busy.base.type == &digitalio_digitalinout_type) { @@ -383,12 +383,12 @@ void displayio_epaperdisplay_background(displayio_epaperdisplay_obj_t* self) { } } -bool common_hal_displayio_epaperdisplay_get_busy(displayio_epaperdisplay_obj_t* self) { +bool common_hal_displayio_epaperdisplay_get_busy(displayio_epaperdisplay_obj_t *self) { displayio_epaperdisplay_background(self); return self->refreshing; } -void release_epaperdisplay(displayio_epaperdisplay_obj_t* self) { +void release_epaperdisplay(displayio_epaperdisplay_obj_t *self) { if (self->refreshing) { wait_for_busy(self); supervisor_disable_tick(); @@ -403,10 +403,10 @@ void release_epaperdisplay(displayio_epaperdisplay_obj_t* self) { } } -void displayio_epaperdisplay_collect_ptrs(displayio_epaperdisplay_obj_t* self) { +void displayio_epaperdisplay_collect_ptrs(displayio_epaperdisplay_obj_t *self) { displayio_display_core_collect_ptrs(&self->core); - gc_collect_ptr((void *) self->start_sequence); - gc_collect_ptr((void *) self->stop_sequence); + gc_collect_ptr((void *)self->start_sequence); + gc_collect_ptr((void *)self->stop_sequence); } bool maybe_refresh_epaperdisplay(void) { @@ -416,7 +416,7 @@ bool maybe_refresh_epaperdisplay(void) { // Skip regular displays and those not showing the splash. continue; } - displayio_epaperdisplay_obj_t* display = &displays[i].epaper_display; + displayio_epaperdisplay_obj_t *display = &displays[i].epaper_display; if (common_hal_displayio_epaperdisplay_get_time_to_refresh(display) != 0) { return false; } diff --git a/shared-module/displayio/EPaperDisplay.h b/shared-module/displayio/EPaperDisplay.h index d0668ff444..988cc57fa3 100644 --- a/shared-module/displayio/EPaperDisplay.h +++ b/shared-module/displayio/EPaperDisplay.h @@ -38,9 +38,9 @@ typedef struct { displayio_display_core_t core; digitalio_digitalinout_obj_t busy; uint32_t milliseconds_per_frame; - const uint8_t* start_sequence; + const uint8_t *start_sequence; uint32_t start_sequence_len; - const uint8_t* stop_sequence; + const uint8_t *stop_sequence; uint32_t stop_sequence_len; uint16_t refresh_time; uint16_t set_column_window_command; @@ -59,10 +59,10 @@ typedef struct { display_chip_select_behavior_t chip_select; } displayio_epaperdisplay_obj_t; -void displayio_epaperdisplay_background(displayio_epaperdisplay_obj_t* self); -void release_epaperdisplay(displayio_epaperdisplay_obj_t* self); +void displayio_epaperdisplay_background(displayio_epaperdisplay_obj_t *self); +void release_epaperdisplay(displayio_epaperdisplay_obj_t *self); bool maybe_refresh_epaperdisplay(void); -void displayio_epaperdisplay_collect_ptrs(displayio_epaperdisplay_obj_t* self); +void displayio_epaperdisplay_collect_ptrs(displayio_epaperdisplay_obj_t *self); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_EPAPERDISPLAY_H diff --git a/shared-module/displayio/FourWire.c b/shared-module/displayio/FourWire.c index e993f2480c..59e2021bd8 100644 --- a/shared-module/displayio/FourWire.c +++ b/shared-module/displayio/FourWire.c @@ -36,9 +36,9 @@ #include "shared-bindings/time/__init__.h" #include "shared-module/displayio/display_core.h" -void common_hal_displayio_fourwire_construct(displayio_fourwire_obj_t* self, - busio_spi_obj_t* spi, const mcu_pin_obj_t* command, - const mcu_pin_obj_t* chip_select, const mcu_pin_obj_t* reset, uint32_t baudrate, +void common_hal_displayio_fourwire_construct(displayio_fourwire_obj_t *self, + busio_spi_obj_t *spi, const mcu_pin_obj_t *command, + const mcu_pin_obj_t *chip_select, const mcu_pin_obj_t *reset, uint32_t baudrate, uint8_t polarity, uint8_t phase) { self->bus = spi; @@ -69,7 +69,7 @@ void common_hal_displayio_fourwire_construct(displayio_fourwire_obj_t* self, common_hal_never_reset_pin(chip_select); } -void common_hal_displayio_fourwire_deinit(displayio_fourwire_obj_t* self) { +void common_hal_displayio_fourwire_deinit(displayio_fourwire_obj_t *self) { if (self->bus == &self->inline_bus) { common_hal_busio_spi_deinit(self->bus); } @@ -80,7 +80,7 @@ void common_hal_displayio_fourwire_deinit(displayio_fourwire_obj_t* self) { } bool common_hal_displayio_fourwire_reset(mp_obj_t obj) { - displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); if (self->reset.base.type == &mp_type_NoneType) { return false; } @@ -92,7 +92,7 @@ bool common_hal_displayio_fourwire_reset(mp_obj_t obj) { } bool common_hal_displayio_fourwire_bus_free(mp_obj_t obj) { - displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); if (!common_hal_busio_spi_try_lock(self->bus)) { return false; } @@ -101,19 +101,19 @@ bool common_hal_displayio_fourwire_bus_free(mp_obj_t obj) { } bool common_hal_displayio_fourwire_begin_transaction(mp_obj_t obj) { - displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); if (!common_hal_busio_spi_try_lock(self->bus)) { return false; } common_hal_busio_spi_configure(self->bus, self->frequency, self->polarity, - self->phase, 8); + self->phase, 8); common_hal_digitalio_digitalinout_set_value(&self->chip_select, false); return true; } void common_hal_displayio_fourwire_send(mp_obj_t obj, display_byte_type_t data_type, - display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { - displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj); + display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { + displayio_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_digitalio_digitalinout_set_value(&self->command, data_type == DISPLAY_DATA); if (chip_select == CHIP_SELECT_TOGGLE_EVERY_BYTE) { // Toggle chip select after each command byte in case the display driver @@ -130,7 +130,7 @@ void common_hal_displayio_fourwire_send(mp_obj_t obj, display_byte_type_t data_t } void common_hal_displayio_fourwire_end_transaction(mp_obj_t obj) { - displayio_fourwire_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_digitalio_digitalinout_set_value(&self->chip_select, true); common_hal_busio_spi_unlock(self->bus); } diff --git a/shared-module/displayio/FourWire.h b/shared-module/displayio/FourWire.h index a4260a3ac5..b28c1ef840 100644 --- a/shared-module/displayio/FourWire.h +++ b/shared-module/displayio/FourWire.h @@ -33,7 +33,7 @@ typedef struct { mp_obj_base_t base; - busio_spi_obj_t* bus; + busio_spi_obj_t *bus; busio_spi_obj_t inline_bus; digitalio_digitalinout_obj_t command; digitalio_digitalinout_obj_t chip_select; diff --git a/shared-module/displayio/Group.c b/shared-module/displayio/Group.c index a36acc1c39..c50f034bf0 100644 --- a/shared-module/displayio/Group.c +++ b/shared-module/displayio/Group.c @@ -35,16 +35,16 @@ #endif -void common_hal_displayio_group_construct(displayio_group_t* self, uint32_t scale, mp_int_t x, mp_int_t y) { +void common_hal_displayio_group_construct(displayio_group_t *self, uint32_t scale, mp_int_t x, mp_int_t y) { mp_obj_list_t *members = mp_obj_new_list(0, NULL); displayio_group_construct(self, members, scale, x, y); } -bool common_hal_displayio_group_get_hidden(displayio_group_t* self) { +bool common_hal_displayio_group_get_hidden(displayio_group_t *self) { return self->hidden; } -void common_hal_displayio_group_set_hidden(displayio_group_t* self, bool hidden) { +void common_hal_displayio_group_set_hidden(displayio_group_t *self, bool hidden) { if (self->hidden == hidden) { return; } @@ -95,11 +95,11 @@ void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden) } } -uint32_t common_hal_displayio_group_get_scale(displayio_group_t* self) { +uint32_t common_hal_displayio_group_get_scale(displayio_group_t *self) { return self->scale; } -bool displayio_group_get_previous_area(displayio_group_t *self, displayio_area_t* area) { +bool displayio_group_get_previous_area(displayio_group_t *self, displayio_area_t *area) { bool first = true; for (size_t i = 0; i < self->members->len; i++) { mp_obj_t layer; @@ -137,20 +137,20 @@ bool displayio_group_get_previous_area(displayio_group_t *self, displayio_area_t return !first; } -static void _update_child_transforms(displayio_group_t* self) { +static void _update_child_transforms(displayio_group_t *self) { if (!self->in_group) { return; } for (size_t i = 0; i < self->members->len; i++) { mp_obj_t layer; -#if CIRCUITPY_VECTORIO + #if CIRCUITPY_VECTORIO layer = mp_instance_cast_to_native_base( self->members->items[i], &vectorio_vector_shape_type); if (layer != MP_OBJ_NULL) { vectorio_vector_shape_update_transform(layer, &self->absolute_transform); continue; } -#endif + #endif layer = mp_instance_cast_to_native_base( self->members->items[i], &displayio_tilegrid_type); if (layer != MP_OBJ_NULL) { @@ -167,7 +167,7 @@ static void _update_child_transforms(displayio_group_t* self) { } void displayio_group_update_transform(displayio_group_t *self, - const displayio_buffer_transform_t* parent_transform) { + const displayio_buffer_transform_t *parent_transform) { self->in_group = parent_transform != NULL; if (self->in_group) { int16_t x = self->x; @@ -189,7 +189,7 @@ void displayio_group_update_transform(displayio_group_t *self, _update_child_transforms(self); } -void common_hal_displayio_group_set_scale(displayio_group_t* self, uint32_t scale) { +void common_hal_displayio_group_set_scale(displayio_group_t *self, uint32_t scale) { if (self->scale == scale) { return; } @@ -201,18 +201,18 @@ void common_hal_displayio_group_set_scale(displayio_group_t* self, uint32_t scal _update_child_transforms(self); } -mp_int_t common_hal_displayio_group_get_x(displayio_group_t* self) { +mp_int_t common_hal_displayio_group_get_x(displayio_group_t *self) { return self->x; } -void common_hal_displayio_group_set_x(displayio_group_t* self, mp_int_t x) { +void common_hal_displayio_group_set_x(displayio_group_t *self, mp_int_t x) { if (self->x == x) { return; } if (self->absolute_transform.transpose_xy) { int16_t dy = self->absolute_transform.dy / self->scale; self->absolute_transform.y += dy * (x - self->x); - } else { + } else { int16_t dx = self->absolute_transform.dx / self->scale; self->absolute_transform.x += dx * (x - self->x); } @@ -221,18 +221,18 @@ void common_hal_displayio_group_set_x(displayio_group_t* self, mp_int_t x) { _update_child_transforms(self); } -mp_int_t common_hal_displayio_group_get_y(displayio_group_t* self) { +mp_int_t common_hal_displayio_group_get_y(displayio_group_t *self) { return self->y; } -void common_hal_displayio_group_set_y(displayio_group_t* self, mp_int_t y) { +void common_hal_displayio_group_set_y(displayio_group_t *self, mp_int_t y) { if (self->y == y) { return; } if (self->absolute_transform.transpose_xy) { int8_t dx = self->absolute_transform.dx / self->scale; self->absolute_transform.x += dx * (y - self->y); - } else { + } else { int8_t dy = self->absolute_transform.dy / self->scale; self->absolute_transform.y += dy * (y - self->y); } @@ -240,18 +240,18 @@ void common_hal_displayio_group_set_y(displayio_group_t* self, mp_int_t y) { _update_child_transforms(self); } -static void _add_layer(displayio_group_t* self, mp_obj_t layer) { +static void _add_layer(displayio_group_t *self, mp_obj_t layer) { mp_obj_t native_layer; -#if CIRCUITPY_VECTORIO + #if CIRCUITPY_VECTORIO native_layer = mp_instance_cast_to_native_base(layer, &vectorio_vector_shape_type); if (native_layer != MP_OBJ_NULL) { vectorio_vector_shape_update_transform(native_layer, &self->absolute_transform); return; } -#endif + #endif native_layer = mp_instance_cast_to_native_base(layer, &displayio_tilegrid_type); if (native_layer != MP_OBJ_NULL) { - displayio_tilegrid_t* tilegrid = native_layer; + displayio_tilegrid_t *tilegrid = native_layer; if (tilegrid->in_group) { mp_raise_ValueError(translate("Layer already in a group.")); } else { @@ -262,7 +262,7 @@ static void _add_layer(displayio_group_t* self, mp_obj_t layer) { } native_layer = mp_instance_cast_to_native_base(layer, &displayio_group_type); if (native_layer != MP_OBJ_NULL) { - displayio_group_t* group = native_layer; + displayio_group_t *group = native_layer; if (group->in_group) { mp_raise_ValueError(translate("Layer already in a group.")); } else { @@ -274,11 +274,11 @@ static void _add_layer(displayio_group_t* self, mp_obj_t layer) { mp_raise_ValueError(translate("Layer must be a Group or TileGrid subclass.")); } -static void _remove_layer(displayio_group_t* self, size_t index) { +static void _remove_layer(displayio_group_t *self, size_t index) { mp_obj_t layer; displayio_area_t layer_area; bool rendered_last_frame = false; -#if CIRCUITPY_VECTORIO + #if CIRCUITPY_VECTORIO layer = mp_instance_cast_to_native_base( self->members->items[index], &vectorio_vector_shape_type); if (layer != MP_OBJ_NULL) { @@ -286,18 +286,18 @@ static void _remove_layer(displayio_group_t* self, size_t index) { rendered_last_frame = has_dirty_area; vectorio_vector_shape_update_transform(layer, NULL); } -#endif + #endif layer = mp_instance_cast_to_native_base( self->members->items[index], &displayio_tilegrid_type); if (layer != MP_OBJ_NULL) { - displayio_tilegrid_t* tilegrid = layer; + displayio_tilegrid_t *tilegrid = layer; rendered_last_frame = displayio_tilegrid_get_previous_area(tilegrid, &layer_area); displayio_tilegrid_update_transform(tilegrid, NULL); } layer = mp_instance_cast_to_native_base( self->members->items[index], &displayio_group_type); if (layer != MP_OBJ_NULL) { - displayio_group_t* group = layer; + displayio_group_t *group = layer; rendered_last_frame = displayio_group_get_previous_area(group, &layer_area); displayio_group_update_transform(group, NULL); } @@ -312,38 +312,38 @@ static void _remove_layer(displayio_group_t* self, size_t index) { self->item_removed = true; } -void common_hal_displayio_group_insert(displayio_group_t* self, size_t index, mp_obj_t layer) { +void common_hal_displayio_group_insert(displayio_group_t *self, size_t index, mp_obj_t layer) { _add_layer(self, layer); mp_obj_list_insert(self->members, index, layer); } -mp_obj_t common_hal_displayio_group_pop(displayio_group_t* self, size_t index) { +mp_obj_t common_hal_displayio_group_pop(displayio_group_t *self, size_t index) { _remove_layer(self, index); return mp_obj_list_pop(self->members, index); } -mp_int_t common_hal_displayio_group_index(displayio_group_t* self, mp_obj_t layer) { +mp_int_t common_hal_displayio_group_index(displayio_group_t *self, mp_obj_t layer) { mp_obj_t args[] = {self->members, layer}; mp_obj_t *index = mp_seq_index_obj( self->members->items, self->members->len, 2, args); return MP_OBJ_SMALL_INT_VALUE(index); } -size_t common_hal_displayio_group_get_len(displayio_group_t* self) { +size_t common_hal_displayio_group_get_len(displayio_group_t *self) { return self->members->len; } -mp_obj_t common_hal_displayio_group_get(displayio_group_t* self, size_t index) { +mp_obj_t common_hal_displayio_group_get(displayio_group_t *self, size_t index) { return self->members->items[index]; } -void common_hal_displayio_group_set(displayio_group_t* self, size_t index, mp_obj_t layer) { +void common_hal_displayio_group_set(displayio_group_t *self, size_t index, mp_obj_t layer) { _add_layer(self, layer); _remove_layer(self, index); mp_obj_list_store(self->members, MP_OBJ_NEW_SMALL_INT(index), layer); } -void displayio_group_construct(displayio_group_t* self, mp_obj_list_t* members, uint32_t scale, mp_int_t x, mp_int_t y) { +void displayio_group_construct(displayio_group_t *self, mp_obj_list_t *members, uint32_t scale, mp_int_t x, mp_int_t y) { self->x = x; self->y = y; self->members = members; @@ -352,12 +352,12 @@ void displayio_group_construct(displayio_group_t* self, mp_obj_list_t* members, self->in_group = false; } -bool displayio_group_fill_area(displayio_group_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t* buffer) { +bool displayio_group_fill_area(displayio_group_t *self, const _displayio_colorspace_t *colorspace, const displayio_area_t *area, uint32_t *mask, uint32_t *buffer) { // Track if any of the layers finishes filling in the given area. We can ignore any remaining // layers at that point. - for (int32_t i = self->members->len - 1; i >= 0 ; i--) { + for (int32_t i = self->members->len - 1; i >= 0; i--) { mp_obj_t layer; -#if CIRCUITPY_VECTORIO + #if CIRCUITPY_VECTORIO layer = mp_instance_cast_to_native_base( self->members->items[i], &vectorio_vector_shape_type); if (layer != MP_OBJ_NULL) { @@ -366,7 +366,7 @@ bool displayio_group_fill_area(displayio_group_t *self, const _displayio_colorsp } continue; } -#endif + #endif layer = mp_instance_cast_to_native_base( self->members->items[i], &displayio_tilegrid_type); if (layer != MP_OBJ_NULL) { @@ -389,16 +389,16 @@ bool displayio_group_fill_area(displayio_group_t *self, const _displayio_colorsp void displayio_group_finish_refresh(displayio_group_t *self) { self->item_removed = false; - for (int32_t i = self->members->len - 1; i >= 0 ; i--) { + for (int32_t i = self->members->len - 1; i >= 0; i--) { mp_obj_t layer; -#if CIRCUITPY_VECTORIO + #if CIRCUITPY_VECTORIO layer = mp_instance_cast_to_native_base( self->members->items[i], &vectorio_vector_shape_type); if (layer != MP_OBJ_NULL) { vectorio_vector_shape_finish_refresh(layer); continue; } -#endif + #endif layer = mp_instance_cast_to_native_base( self->members->items[i], &displayio_tilegrid_type); if (layer != MP_OBJ_NULL) { @@ -414,22 +414,22 @@ void displayio_group_finish_refresh(displayio_group_t *self) { } } -displayio_area_t* displayio_group_get_refresh_areas(displayio_group_t *self, displayio_area_t* tail) { +displayio_area_t *displayio_group_get_refresh_areas(displayio_group_t *self, displayio_area_t *tail) { if (self->item_removed) { self->dirty_area.next = tail; tail = &self->dirty_area; } - for (int32_t i = self->members->len - 1; i >= 0 ; i--) { + for (int32_t i = self->members->len - 1; i >= 0; i--) { mp_obj_t layer; -#if CIRCUITPY_VECTORIO + #if CIRCUITPY_VECTORIO layer = mp_instance_cast_to_native_base( self->members->items[i], &vectorio_vector_shape_type); if (layer != MP_OBJ_NULL) { tail = vectorio_vector_shape_get_refresh_areas(layer, tail); continue; } -#endif + #endif layer = mp_instance_cast_to_native_base( self->members->items[i], &displayio_tilegrid_type); if (layer != MP_OBJ_NULL) { diff --git a/shared-module/displayio/Group.h b/shared-module/displayio/Group.h index 0964e0a0ba..f684223154 100644 --- a/shared-module/displayio/Group.h +++ b/shared-module/displayio/Group.h @@ -43,19 +43,19 @@ typedef struct { int16_t x; int16_t y; uint16_t scale; - bool item_removed :1; - bool in_group :1; - bool hidden :1; - bool hidden_by_parent :1; - uint8_t padding :4; + bool item_removed : 1; + bool in_group : 1; + bool hidden : 1; + bool hidden_by_parent : 1; + uint8_t padding : 4; } displayio_group_t; -void displayio_group_construct(displayio_group_t* self, mp_obj_list_t* members, uint32_t scale, mp_int_t x, mp_int_t y); +void displayio_group_construct(displayio_group_t *self, mp_obj_list_t *members, uint32_t scale, mp_int_t x, mp_int_t y); void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden); -bool displayio_group_get_previous_area(displayio_group_t *group, displayio_area_t* area); -bool displayio_group_fill_area(displayio_group_t *group, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer); -void displayio_group_update_transform(displayio_group_t *group, const displayio_buffer_transform_t* parent_transform); +bool displayio_group_get_previous_area(displayio_group_t *group, displayio_area_t *area); +bool displayio_group_fill_area(displayio_group_t *group, const _displayio_colorspace_t *colorspace, const displayio_area_t *area, uint32_t *mask, uint32_t *buffer); +void displayio_group_update_transform(displayio_group_t *group, const displayio_buffer_transform_t *parent_transform); void displayio_group_finish_refresh(displayio_group_t *self); -displayio_area_t* displayio_group_get_refresh_areas(displayio_group_t *self, displayio_area_t* tail); +displayio_area_t *displayio_group_get_refresh_areas(displayio_group_t *self, displayio_area_t *tail); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_GROUP_H diff --git a/shared-module/displayio/I2CDisplay.c b/shared-module/displayio/I2CDisplay.c index cc811e83d7..6446e3198f 100644 --- a/shared-module/displayio/I2CDisplay.c +++ b/shared-module/displayio/I2CDisplay.c @@ -38,8 +38,8 @@ #include "shared-bindings/time/__init__.h" #include "shared-module/displayio/display_core.h" -void common_hal_displayio_i2cdisplay_construct(displayio_i2cdisplay_obj_t* self, - busio_i2c_obj_t* i2c, uint16_t device_address, const mcu_pin_obj_t* reset) { +void common_hal_displayio_i2cdisplay_construct(displayio_i2cdisplay_obj_t *self, + busio_i2c_obj_t *i2c, uint16_t device_address, const mcu_pin_obj_t *reset) { // Reset the display before probing self->reset.base.type = &mp_type_NoneType; @@ -67,7 +67,7 @@ void common_hal_displayio_i2cdisplay_construct(displayio_i2cdisplay_obj_t* self, self->address = device_address; } -void common_hal_displayio_i2cdisplay_deinit(displayio_i2cdisplay_obj_t* self) { +void common_hal_displayio_i2cdisplay_deinit(displayio_i2cdisplay_obj_t *self) { if (self->bus == &self->inline_bus) { common_hal_busio_i2c_deinit(self->bus); } @@ -78,7 +78,7 @@ void common_hal_displayio_i2cdisplay_deinit(displayio_i2cdisplay_obj_t* self) { } bool common_hal_displayio_i2cdisplay_reset(mp_obj_t obj) { - displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_i2cdisplay_obj_t *self = MP_OBJ_TO_PTR(obj); if (self->reset.base.type == &mp_type_NoneType) { return false; } @@ -90,7 +90,7 @@ bool common_hal_displayio_i2cdisplay_reset(mp_obj_t obj) { } bool common_hal_displayio_i2cdisplay_bus_free(mp_obj_t obj) { - displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_i2cdisplay_obj_t *self = MP_OBJ_TO_PTR(obj); if (!common_hal_busio_i2c_try_lock(self->bus)) { return false; } @@ -99,13 +99,13 @@ bool common_hal_displayio_i2cdisplay_bus_free(mp_obj_t obj) { } bool common_hal_displayio_i2cdisplay_begin_transaction(mp_obj_t obj) { - displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_i2cdisplay_obj_t *self = MP_OBJ_TO_PTR(obj); return common_hal_busio_i2c_try_lock(self->bus); } void common_hal_displayio_i2cdisplay_send(mp_obj_t obj, display_byte_type_t data_type, - display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { - displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj); + display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length) { + displayio_i2cdisplay_obj_t *self = MP_OBJ_TO_PTR(obj); if (data_type == DISPLAY_COMMAND) { uint8_t command_bytes[2 * data_length]; for (uint32_t i = 0; i < data_length; i++) { @@ -122,6 +122,6 @@ void common_hal_displayio_i2cdisplay_send(mp_obj_t obj, display_byte_type_t data } void common_hal_displayio_i2cdisplay_end_transaction(mp_obj_t obj) { - displayio_i2cdisplay_obj_t* self = MP_OBJ_TO_PTR(obj); + displayio_i2cdisplay_obj_t *self = MP_OBJ_TO_PTR(obj); common_hal_busio_i2c_unlock(self->bus); } diff --git a/shared-module/displayio/I2CDisplay.h b/shared-module/displayio/I2CDisplay.h index 4636c3f73a..cc5bcf1eb7 100644 --- a/shared-module/displayio/I2CDisplay.h +++ b/shared-module/displayio/I2CDisplay.h @@ -32,7 +32,7 @@ typedef struct { mp_obj_base_t base; - busio_i2c_obj_t* bus; + busio_i2c_obj_t *bus; busio_i2c_obj_t inline_bus; digitalio_digitalinout_obj_t reset; uint16_t address; diff --git a/shared-module/displayio/OnDiskBitmap.c b/shared-module/displayio/OnDiskBitmap.c index c1a0ddeb7e..5c7e00a583 100644 --- a/shared-module/displayio/OnDiskBitmap.c +++ b/shared-module/displayio/OnDiskBitmap.c @@ -31,11 +31,11 @@ #include "py/mperrno.h" #include "py/runtime.h" -static uint32_t read_word(uint16_t* bmp_header, uint16_t index) { +static uint32_t read_word(uint16_t *bmp_header, uint16_t index) { return bmp_header[index] | bmp_header[index + 1] << 16; } -void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, pyb_file_obj_t* file) { +void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, pyb_file_obj_t *file) { // Load the wave self->file = file; uint16_t bmp_header[69]; @@ -58,12 +58,12 @@ void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, uint32_t number_of_colors = read_word(bmp_header, 23); bool indexed = bits_per_pixel <= 8; - self->bitfield_compressed = (compression == 3); + self->bitfield_compressed = (compression == 3); self->bits_per_pixel = bits_per_pixel; self->width = read_word(bmp_header, 9); self->height = read_word(bmp_header, 11); - if (bits_per_pixel == 16){ + if (bits_per_pixel == 16) { if (((header_size >= 56)) || (self->bitfield_compressed)) { self->r_bitmask = read_word(bmp_header, 27); self->g_bitmask = read_word(bmp_header, 29); @@ -101,9 +101,9 @@ void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, mp_raise_ValueError_varg(translate("Only monochrome, indexed 4bpp or 8bpp, and 16bpp or greater BMPs supported: %d bpp given"), bits_per_pixel); } - uint8_t bytes_per_pixel = (self->bits_per_pixel / 8) ? (self->bits_per_pixel /8) : 1; + uint8_t bytes_per_pixel = (self->bits_per_pixel / 8) ? (self->bits_per_pixel / 8) : 1; uint8_t pixels_per_byte = 8 / self->bits_per_pixel; - if (pixels_per_byte == 0){ + if (pixels_per_byte == 0) { self->stride = (self->width * bytes_per_pixel); // Rows are word aligned. if (self->stride % 4 != 0) { @@ -121,15 +121,15 @@ void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, uint32_t common_hal_displayio_ondiskbitmap_get_pixel(displayio_ondiskbitmap_t *self, - int16_t x, int16_t y) { + int16_t x, int16_t y) { if (x < 0 || x >= self->width || y < 0 || y >= self->height) { return 0; } uint32_t location; - uint8_t bytes_per_pixel = (self->bits_per_pixel / 8) ? (self->bits_per_pixel /8) : 1; + uint8_t bytes_per_pixel = (self->bits_per_pixel / 8) ? (self->bits_per_pixel / 8) : 1; uint8_t pixels_per_byte = 8 / self->bits_per_pixel; - if (pixels_per_byte == 0){ + if (pixels_per_byte == 0) { location = self->data_offset + (self->height - y - 1) * self->stride + x * bytes_per_pixel; } else { location = self->data_offset + (self->height - y - 1) * self->stride + x / pixels_per_byte; @@ -159,12 +159,12 @@ uint32_t common_hal_displayio_ondiskbitmap_get_pixel(displayio_ondiskbitmap_t *s return self->palette_data[index]; } else if (bytes_per_pixel == 2) { if (self->g_bitmask == 0x07e0) { // 565 - red =((pixel_data & self->r_bitmask) >>11); - green = ((pixel_data & self->g_bitmask) >>5); + red = ((pixel_data & self->r_bitmask) >> 11); + green = ((pixel_data & self->g_bitmask) >> 5); blue = ((pixel_data & self->b_bitmask) >> 0); } else { // 555 - red =((pixel_data & self->r_bitmask) >>10); - green = ((pixel_data & self->g_bitmask) >>4); + red = ((pixel_data & self->r_bitmask) >> 10); + green = ((pixel_data & self->g_bitmask) >> 4); blue = ((pixel_data & self->b_bitmask) >> 0); } tmp = (red << 19 | green << 10 | blue << 3); diff --git a/shared-module/displayio/OnDiskBitmap.h b/shared-module/displayio/OnDiskBitmap.h index 28426f11b8..610b114910 100644 --- a/shared-module/displayio/OnDiskBitmap.h +++ b/shared-module/displayio/OnDiskBitmap.h @@ -44,9 +44,9 @@ typedef struct { uint32_t g_bitmask; uint32_t b_bitmask; bool bitfield_compressed; - pyb_file_obj_t* file; + pyb_file_obj_t *file; uint8_t bits_per_pixel; - uint32_t* palette_data; + uint32_t *palette_data; } displayio_ondiskbitmap_t; #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_ONDISKBITMAP_H diff --git a/shared-module/displayio/Palette.c b/shared-module/displayio/Palette.c index ba5ff665c9..6dde3a80f1 100644 --- a/shared-module/displayio/Palette.c +++ b/shared-module/displayio/Palette.c @@ -28,26 +28,26 @@ #include "shared-module/displayio/ColorConverter.h" -void common_hal_displayio_palette_construct(displayio_palette_t* self, uint16_t color_count) { +void common_hal_displayio_palette_construct(displayio_palette_t *self, uint16_t color_count) { self->color_count = color_count; - self->colors = (_displayio_color_t *) m_malloc(color_count * sizeof(_displayio_color_t), false); + self->colors = (_displayio_color_t *)m_malloc(color_count * sizeof(_displayio_color_t), false); } -void common_hal_displayio_palette_make_opaque(displayio_palette_t* self, uint32_t palette_index) { +void common_hal_displayio_palette_make_opaque(displayio_palette_t *self, uint32_t palette_index) { self->colors[palette_index].transparent = false; self->needs_refresh = true; } -void common_hal_displayio_palette_make_transparent(displayio_palette_t* self, uint32_t palette_index) { +void common_hal_displayio_palette_make_transparent(displayio_palette_t *self, uint32_t palette_index) { self->colors[palette_index].transparent = true; self->needs_refresh = true; } -uint32_t common_hal_displayio_palette_get_len(displayio_palette_t* self) { +uint32_t common_hal_displayio_palette_get_len(displayio_palette_t *self) { return self->color_count; } -void common_hal_displayio_palette_set_color(displayio_palette_t* self, uint32_t palette_index, uint32_t color) { +void common_hal_displayio_palette_set_color(displayio_palette_t *self, uint32_t palette_index, uint32_t color) { if (self->colors[palette_index].rgb888 == color) { return; } @@ -61,11 +61,11 @@ void common_hal_displayio_palette_set_color(displayio_palette_t* self, uint32_t self->needs_refresh = true; } -uint32_t common_hal_displayio_palette_get_color(displayio_palette_t* self, uint32_t palette_index) { +uint32_t common_hal_displayio_palette_get_color(displayio_palette_t *self, uint32_t palette_index) { return self->colors[palette_index].rgb888; } -bool displayio_palette_get_color(displayio_palette_t *self, const _displayio_colorspace_t* colorspace, uint32_t palette_index, uint32_t* color) { +bool displayio_palette_get_color(displayio_palette_t *self, const _displayio_colorspace_t *colorspace, uint32_t palette_index, uint32_t *color) { if (palette_index > self->color_count || self->colors[palette_index].transparent) { return false; // returns opaque } @@ -74,7 +74,7 @@ bool displayio_palette_get_color(displayio_palette_t *self, const _displayio_col uint8_t luma = self->colors[palette_index].luma; *color = luma >> (8 - colorspace->depth); // Chroma 0 means the color is a gray and has no hue so never color based on it. - if (self->colors[palette_index].chroma <= 16) { + if (self->colors[palette_index].chroma <= 16) { if (!colorspace->grayscale) { *color = 0; } diff --git a/shared-module/displayio/Palette.h b/shared-module/displayio/Palette.h index 993912cc51..82504b7ed1 100644 --- a/shared-module/displayio/Palette.h +++ b/shared-module/displayio/Palette.h @@ -71,14 +71,14 @@ typedef struct { typedef struct { mp_obj_base_t base; - _displayio_color_t* colors; + _displayio_color_t *colors; uint32_t color_count; bool needs_refresh; } displayio_palette_t; // Returns false if color fetch did not succeed (out of range or transparent). // Returns true if color is opaque, and sets color. -bool displayio_palette_get_color(displayio_palette_t *palette, const _displayio_colorspace_t* colorspace, uint32_t palette_index, uint32_t* color); +bool displayio_palette_get_color(displayio_palette_t *palette, const _displayio_colorspace_t *colorspace, uint32_t palette_index, uint32_t *color); bool displayio_palette_needs_refresh(displayio_palette_t *self); void displayio_palette_finish_refresh(displayio_palette_t *self); diff --git a/shared-module/displayio/Shape.c b/shared-module/displayio/Shape.c index b94a392bc6..4a32c7a606 100644 --- a/shared-module/displayio/Shape.c +++ b/shared-module/displayio/Shape.c @@ -56,10 +56,10 @@ void common_hal_displayio_shape_construct(displayio_shape_t *self, uint32_t widt self->data[2 * i + 1] = width; } - self->dirty_area.x1=0; - self->dirty_area.x2=width; - self->dirty_area.y1=0; - self->dirty_area.y2=height; + self->dirty_area.x1 = 0; + self->dirty_area.x2 = width; + self->dirty_area.y1 = 0; + self->dirty_area.y2 = height; } void common_hal_displayio_shape_set_boundary(displayio_shape_t *self, uint16_t y, uint16_t start_x, uint16_t end_x) { @@ -130,7 +130,7 @@ uint32_t common_hal_displayio_shape_get_pixel(void *obj, int16_t x, int16_t y) { return 1; } -displayio_area_t* displayio_shape_get_refresh_areas(displayio_shape_t *self, displayio_area_t* tail) { +displayio_area_t *displayio_shape_get_refresh_areas(displayio_shape_t *self, displayio_area_t *tail) { if (self->dirty_area.x1 == self->dirty_area.x2) { return tail; } diff --git a/shared-module/displayio/Shape.h b/shared-module/displayio/Shape.h index e59ad586e7..2cac5d73b2 100644 --- a/shared-module/displayio/Shape.h +++ b/shared-module/displayio/Shape.h @@ -39,13 +39,13 @@ typedef struct { uint16_t height; uint16_t half_width; uint16_t half_height; - uint16_t* data; + uint16_t *data; bool mirror_x; bool mirror_y; displayio_area_t dirty_area; } displayio_shape_t; void displayio_shape_finish_refresh(displayio_shape_t *self); -displayio_area_t* displayio_shape_get_refresh_areas(displayio_shape_t *self, displayio_area_t* tail); +displayio_area_t *displayio_shape_get_refresh_areas(displayio_shape_t *self, displayio_area_t *tail); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_SHAPE_H diff --git a/shared-module/displayio/TileGrid.c b/shared-module/displayio/TileGrid.c index 96473d4a86..347eba577e 100644 --- a/shared-module/displayio/TileGrid.c +++ b/shared-module/displayio/TileGrid.c @@ -34,21 +34,21 @@ #include "shared-bindings/displayio/Shape.h" void common_hal_displayio_tilegrid_construct(displayio_tilegrid_t *self, mp_obj_t bitmap, - uint16_t bitmap_width_in_tiles, uint16_t bitmap_height_in_tiles, - mp_obj_t pixel_shader, uint16_t width, uint16_t height, - uint16_t tile_width, uint16_t tile_height, uint16_t x, uint16_t y, uint8_t default_tile) { + uint16_t bitmap_width_in_tiles, uint16_t bitmap_height_in_tiles, + mp_obj_t pixel_shader, uint16_t width, uint16_t height, + uint16_t tile_width, uint16_t tile_height, uint16_t x, uint16_t y, uint8_t default_tile) { uint32_t total_tiles = width * height; // Sprites will only have one tile so save a little memory by inlining values in the pointer. - uint8_t inline_tiles = sizeof(uint8_t*); + uint8_t inline_tiles = sizeof(uint8_t *); if (total_tiles <= inline_tiles) { self->tiles = 0; // Pack values into the pointer since there are only a few. for (uint32_t i = 0; i < inline_tiles; i++) { - ((uint8_t*) &self->tiles)[i] = default_tile; + ((uint8_t *)&self->tiles)[i] = default_tile; } self->inline_tiles = true; } else { - self->tiles = (uint8_t*) m_malloc(total_tiles, false); + self->tiles = (uint8_t *)m_malloc(total_tiles, false); for (uint32_t i = 0; i < total_tiles; i++) { self->tiles[i] = default_tile; } @@ -78,25 +78,25 @@ void common_hal_displayio_tilegrid_construct(displayio_tilegrid_t *self, mp_obj_ } -bool common_hal_displayio_tilegrid_get_hidden(displayio_tilegrid_t* self) { +bool common_hal_displayio_tilegrid_get_hidden(displayio_tilegrid_t *self) { return self->hidden; } -void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t* self, bool hidden) { +void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t *self, bool hidden) { self->hidden = hidden; - if(!hidden){ + if (!hidden) { self->full_change = true; } } void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden) { self->hidden_by_parent = hidden; - if(!hidden){ + if (!hidden) { self->full_change = true; } } -bool displayio_tilegrid_get_previous_area(displayio_tilegrid_t *self, displayio_area_t* area) { +bool displayio_tilegrid_get_previous_area(displayio_tilegrid_t *self, displayio_area_t *area) { if (self->previous_area.x1 == self->previous_area.x2) { return false; } @@ -113,8 +113,8 @@ void _update_current_x(displayio_tilegrid_t *self) { } // If there's no transform, substitute an identity transform so the calculations will work. - const displayio_buffer_transform_t* absolute_transform = - self->absolute_transform == NULL + const displayio_buffer_transform_t *absolute_transform = + self->absolute_transform == NULL ? &null_transform : self->absolute_transform; @@ -146,8 +146,8 @@ void _update_current_y(displayio_tilegrid_t *self) { } // If there's no transform, substitute an identity transform so the calculations will work. - const displayio_buffer_transform_t* absolute_transform = - self->absolute_transform == NULL + const displayio_buffer_transform_t *absolute_transform = + self->absolute_transform == NULL ? &null_transform : self->absolute_transform; @@ -171,7 +171,7 @@ void _update_current_y(displayio_tilegrid_t *self) { } void displayio_tilegrid_update_transform(displayio_tilegrid_t *self, - const displayio_buffer_transform_t* absolute_transform) { + const displayio_buffer_transform_t *absolute_transform) { self->in_group = absolute_transform != NULL; self->absolute_transform = absolute_transform; if (absolute_transform != NULL) { @@ -230,9 +230,9 @@ uint16_t common_hal_displayio_tilegrid_get_height(displayio_tilegrid_t *self) { } uint8_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { - uint8_t* tiles = self->tiles; + uint8_t *tiles = self->tiles; if (self->inline_tiles) { - tiles = (uint8_t*) &self->tiles; + tiles = (uint8_t *)&self->tiles; } if (tiles == NULL) { return 0; @@ -244,16 +244,16 @@ void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t if (tile_index >= self->tiles_in_bitmap) { mp_raise_ValueError(translate("Tile index out of bounds")); } - uint8_t* tiles = self->tiles; + uint8_t *tiles = self->tiles; if (self->inline_tiles) { - tiles = (uint8_t*) &self->tiles; + tiles = (uint8_t *)&self->tiles; } if (tiles == NULL) { return; } tiles[y * self->width_in_tiles + x] = tile_index; displayio_area_t temp_area; - displayio_area_t* tile_area; + displayio_area_t *tile_area; if (!self->partial_change) { tile_area = &self->dirty_area; } else { @@ -331,11 +331,11 @@ void common_hal_displayio_tilegrid_set_top_left(displayio_tilegrid_t *self, uint self->full_change = true; } -bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer) { +bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_colorspace_t *colorspace, const displayio_area_t *area, uint32_t *mask, uint32_t *buffer) { // If no tiles are present we have no impact. - uint8_t* tiles = self->tiles; + uint8_t *tiles = self->tiles; if (self->inline_tiles) { - tiles = (uint8_t*) &self->tiles; + tiles = (uint8_t *)&self->tiles; } if (tiles == NULL) { return false; @@ -384,9 +384,9 @@ bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_c // can either return full coverage or bulk update the mask. displayio_area_t transformed; displayio_area_transform_within(flip_x != (self->absolute_transform->dx < 0), flip_y != (self->absolute_transform->dy < 0), self->transpose_xy != self->absolute_transform->transpose_xy, - &overlap, - &self->current_area, - &transformed); + &overlap, + &self->current_area, + &transformed); int16_t start_x = (transformed.x1 - self->current_area.x1); int16_t end_x = (transformed.x2 - self->current_area.x1); @@ -443,7 +443,7 @@ bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_c input_pixel.tile_x = (input_pixel.tile % self->bitmap_width_in_tiles) * self->tile_width + local_x % self->tile_width; input_pixel.tile_y = (input_pixel.tile / self->bitmap_width_in_tiles) * self->tile_height + local_y % self->tile_height; - //uint32_t value = 0; + // uint32_t value = 0; output_pixel.pixel = 0; input_pixel.pixel = 0; @@ -471,9 +471,9 @@ bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_c } else { mask[offset / 32] |= 1 << (offset % 32); if (colorspace->depth == 16) { - *(((uint16_t*) buffer) + offset) = output_pixel.pixel; + *(((uint16_t *)buffer) + offset) = output_pixel.pixel; } else if (colorspace->depth == 8) { - *(((uint8_t*) buffer) + offset) = output_pixel.pixel; + *(((uint8_t *)buffer) + offset) = output_pixel.pixel; } else if (colorspace->depth < 8) { // Reorder the offsets to pack multiple rows into a byte (meaning they share a column). if (!colorspace->pixels_in_byte_share_row) { @@ -492,7 +492,7 @@ bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_c // Reverse the shift by subtracting it from the leftmost shift. shift = (pixels_per_byte - 1) * colorspace->depth - shift; } - ((uint8_t*)buffer)[offset / pixels_per_byte] |= output_pixel.pixel << shift; + ((uint8_t *)buffer)[offset / pixels_per_byte] |= output_pixel.pixel << shift; } } } @@ -529,7 +529,7 @@ void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self) { // That way they won't change during a refresh and tear. } -displayio_area_t* displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *self, displayio_area_t* tail) { +displayio_area_t *displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *self, displayio_area_t *tail) { bool first_draw = self->previous_area.x1 == self->previous_area.x2; bool hidden = self->hidden || self->hidden_by_parent; // Check hidden first because it trumps all other changes. @@ -553,7 +553,7 @@ displayio_area_t* displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *sel // If we have an in-memory bitmap, then check it for modifications. if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_bitmap_type)) { - displayio_area_t* refresh_area = displayio_bitmap_get_refresh_areas(self->bitmap, tail); + displayio_area_t *refresh_area = displayio_bitmap_get_refresh_areas(self->bitmap, tail); if (refresh_area != tail) { // Special case a TileGrid that shows a full bitmap and use its // dirty area. Copy it to ours so we can transform it. @@ -565,7 +565,7 @@ displayio_area_t* displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *sel } } } else if (MP_OBJ_IS_TYPE(self->bitmap, &displayio_shape_type)) { - displayio_area_t* refresh_area = displayio_shape_get_refresh_areas(self->bitmap, tail); + displayio_area_t *refresh_area = displayio_shape_get_refresh_areas(self->bitmap, tail); if (refresh_area != tail) { displayio_area_copy(refresh_area, &self->dirty_area); self->partial_change = true; @@ -574,9 +574,9 @@ displayio_area_t* displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *sel self->full_change = self->full_change || (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type) && - displayio_palette_needs_refresh(self->pixel_shader)) || + displayio_palette_needs_refresh(self->pixel_shader)) || (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type) && - displayio_colorconverter_needs_refresh(self->pixel_shader)); + displayio_colorconverter_needs_refresh(self->pixel_shader)); if (self->full_change || first_draw) { self->current_area.next = tail; return &self->current_area; diff --git a/shared-module/displayio/TileGrid.h b/shared-module/displayio/TileGrid.h index e97d3dfd47..b5aab51348 100644 --- a/shared-module/displayio/TileGrid.h +++ b/shared-module/displayio/TileGrid.h @@ -42,7 +42,8 @@ typedef struct { int16_t y; uint16_t pixel_width; uint16_t pixel_height; - uint16_t bitmap_width_in_tiles;; + uint16_t bitmap_width_in_tiles; + ; uint16_t tiles_in_bitmap; uint16_t width_in_tiles; uint16_t height_in_tiles; @@ -50,22 +51,22 @@ typedef struct { uint16_t tile_height; uint16_t top_left_x; uint16_t top_left_y; - uint8_t* tiles; - const displayio_buffer_transform_t* absolute_transform; + uint8_t *tiles; + const displayio_buffer_transform_t *absolute_transform; displayio_area_t dirty_area; // Stored as a relative area until the refresh area is fetched. displayio_area_t previous_area; // Stored as an absolute area. displayio_area_t current_area; // Stored as an absolute area so it applies across frames. - bool partial_change :1; - bool full_change :1; - bool moved :1; - bool inline_tiles :1; - bool in_group :1; - bool flip_x :1; - bool flip_y :1; - bool transpose_xy :1; - bool hidden :1; - bool hidden_by_parent :1; - uint8_t padding :6; + bool partial_change : 1; + bool full_change : 1; + bool moved : 1; + bool inline_tiles : 1; + bool in_group : 1; + bool flip_x : 1; + bool flip_y : 1; + bool transpose_xy : 1; + bool hidden : 1; + bool hidden_by_parent : 1; + uint8_t padding : 6; } displayio_tilegrid_t; void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden); @@ -73,16 +74,16 @@ void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hi // Updating the screen is a three stage process. // The first stage is used to determine i -displayio_area_t* displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *self, displayio_area_t* tail); +displayio_area_t *displayio_tilegrid_get_refresh_areas(displayio_tilegrid_t *self, displayio_area_t *tail); // Area is always in absolute screen coordinates. Update transform is used to inform TileGrids how // they relate to it. -bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer); -void displayio_tilegrid_update_transform(displayio_tilegrid_t *group, const displayio_buffer_transform_t* parent_transform); +bool displayio_tilegrid_fill_area(displayio_tilegrid_t *self, const _displayio_colorspace_t *colorspace, const displayio_area_t *area, uint32_t *mask, uint32_t *buffer); +void displayio_tilegrid_update_transform(displayio_tilegrid_t *group, const displayio_buffer_transform_t *parent_transform); // Fills in area with the maximum bounds of all related pixels in the last rendered frame. Returns // false if the tilegrid wasn't rendered in the last frame. -bool displayio_tilegrid_get_previous_area(displayio_tilegrid_t *self, displayio_area_t* area); +bool displayio_tilegrid_get_previous_area(displayio_tilegrid_t *self, displayio_area_t *area); void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_TILEGRID_H diff --git a/shared-module/displayio/__init__.c b/shared-module/displayio/__init__.c index 740af0570c..3c9c2cc3ac 100644 --- a/shared-module/displayio/__init__.c +++ b/shared-module/displayio/__init__.c @@ -44,7 +44,7 @@ displayio_buffer_transform_t null_transform = { STATIC bool any_display_uses_this_framebuffer(mp_obj_base_t *obj) { for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { if (displays[i].display_base.type == &framebufferio_framebufferdisplay_type) { - framebufferio_framebufferdisplay_obj_t* display = &displays[i].framebuffer_display; + framebufferio_framebufferdisplay_obj_t *display = &displays[i].framebuffer_display; if (display->framebuffer == obj) { return true; } @@ -72,10 +72,10 @@ void displayio_background(void) { } if (displays[i].display.base.type == &displayio_display_type) { displayio_display_background(&displays[i].display); -#if CIRCUITPY_FRAMEBUFFERIO + #if CIRCUITPY_FRAMEBUFFERIO } else if (displays[i].framebuffer_display.base.type == &framebufferio_framebufferdisplay_type) { framebufferio_framebufferdisplay_background(&displays[i].framebuffer_display); -#endif + #endif } else if (displays[i].epaper_display.base.type == &displayio_epaperdisplay_type) { displayio_epaperdisplay_background(&displays[i].epaper_display); } @@ -94,10 +94,10 @@ void common_hal_displayio_release_displays(void) { release_display(&displays[i].display); } else if (display_type == &displayio_epaperdisplay_type) { release_epaperdisplay(&displays[i].epaper_display); -#if CIRCUITPY_FRAMEBUFFERIO + #if CIRCUITPY_FRAMEBUFFERIO } else if (display_type == &framebufferio_framebufferdisplay_type) { release_framebufferdisplay(&displays[i].framebuffer_display); -#endif + #endif } displays[i].display.base.type = &mp_type_NoneType; } @@ -111,14 +111,14 @@ void common_hal_displayio_release_displays(void) { common_hal_displayio_i2cdisplay_deinit(&displays[i].i2cdisplay_bus); } else if (bus_type == &displayio_parallelbus_type) { common_hal_displayio_parallelbus_deinit(&displays[i].parallel_bus); -#if CIRCUITPY_RGBMATRIX + #if CIRCUITPY_RGBMATRIX } else if (bus_type == &rgbmatrix_RGBMatrix_type) { common_hal_rgbmatrix_rgbmatrix_deinit(&displays[i].rgbmatrix); -#endif -#if CIRCUITPY_SHARPDISPLAY + #endif + #if CIRCUITPY_SHARPDISPLAY } else if (displays[i].bus_base.type == &sharpdisplay_framebuffer_type) { common_hal_sharpdisplay_framebuffer_deinit(&displays[i].sharpdisplay); -#endif + #endif } displays[i].fourwire_bus.base.type = &mp_type_NoneType; } @@ -130,68 +130,68 @@ void reset_displays(void) { // The SPI buses used by FourWires may be allocated on the heap so we need to move them inline. for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { if (displays[i].fourwire_bus.base.type == &displayio_fourwire_type) { - displayio_fourwire_obj_t* fourwire = &displays[i].fourwire_bus; - if (((uint32_t) fourwire->bus) < ((uint32_t) &displays) || - ((uint32_t) fourwire->bus) > ((uint32_t) &displays + CIRCUITPY_DISPLAY_LIMIT)) { - busio_spi_obj_t* original_spi = fourwire->bus; + displayio_fourwire_obj_t *fourwire = &displays[i].fourwire_bus; + if (((uint32_t)fourwire->bus) < ((uint32_t)&displays) || + ((uint32_t)fourwire->bus) > ((uint32_t)&displays + CIRCUITPY_DISPLAY_LIMIT)) { + busio_spi_obj_t *original_spi = fourwire->bus; #if BOARD_SPI - // We don't need to move original_spi if it is the board.SPI object because it is - // statically allocated already. (Doing so would also make it impossible to reference in - // a subsequent VM run.) - if (original_spi == common_hal_board_get_spi()) { - continue; - } + // We don't need to move original_spi if it is the board.SPI object because it is + // statically allocated already. (Doing so would also make it impossible to reference in + // a subsequent VM run.) + if (original_spi == common_hal_board_get_spi()) { + continue; + } #endif #ifdef BOARD_USE_INTERNAL_SPI - if (original_spi == (mp_obj_t)(&supervisor_flash_spi_bus)) { - continue; - } + if (original_spi == (mp_obj_t)(&supervisor_flash_spi_bus)) { + continue; + } #endif memcpy(&fourwire->inline_bus, original_spi, sizeof(busio_spi_obj_t)); fourwire->bus = &fourwire->inline_bus; // Check for other displays that use the same spi bus and swap them too. for (uint8_t j = i + 1; j < CIRCUITPY_DISPLAY_LIMIT; j++) { if (displays[i].fourwire_bus.base.type == &displayio_fourwire_type && - displays[i].fourwire_bus.bus == original_spi) { + displays[i].fourwire_bus.bus == original_spi) { displays[i].fourwire_bus.bus = &fourwire->inline_bus; } } } } else if (displays[i].i2cdisplay_bus.base.type == &displayio_i2cdisplay_type) { - displayio_i2cdisplay_obj_t* i2c = &displays[i].i2cdisplay_bus; - if (((uint32_t) i2c->bus) < ((uint32_t) &displays) || - ((uint32_t) i2c->bus) > ((uint32_t) &displays + CIRCUITPY_DISPLAY_LIMIT)) { - busio_i2c_obj_t* original_i2c = i2c->bus; + displayio_i2cdisplay_obj_t *i2c = &displays[i].i2cdisplay_bus; + if (((uint32_t)i2c->bus) < ((uint32_t)&displays) || + ((uint32_t)i2c->bus) > ((uint32_t)&displays + CIRCUITPY_DISPLAY_LIMIT)) { + busio_i2c_obj_t *original_i2c = i2c->bus; #if BOARD_I2C - // We don't need to move original_i2c if it is the board.I2C object because it is - // statically allocated already. (Doing so would also make it impossible to reference in - // a subsequent VM run.) - if (original_i2c == common_hal_board_get_i2c()) { - continue; - } + // We don't need to move original_i2c if it is the board.I2C object because it is + // statically allocated already. (Doing so would also make it impossible to reference in + // a subsequent VM run.) + if (original_i2c == common_hal_board_get_i2c()) { + continue; + } #endif memcpy(&i2c->inline_bus, original_i2c, sizeof(busio_i2c_obj_t)); i2c->bus = &i2c->inline_bus; // Check for other displays that use the same i2c bus and swap them too. for (uint8_t j = i + 1; j < CIRCUITPY_DISPLAY_LIMIT; j++) { if (displays[i].i2cdisplay_bus.base.type == &displayio_i2cdisplay_type && - displays[i].i2cdisplay_bus.bus == original_i2c) { + displays[i].i2cdisplay_bus.bus == original_i2c) { displays[i].i2cdisplay_bus.bus = &i2c->inline_bus; } } } -#if CIRCUITPY_RGBMATRIX + #if CIRCUITPY_RGBMATRIX } else if (displays[i].rgbmatrix.base.type == &rgbmatrix_RGBMatrix_type) { - rgbmatrix_rgbmatrix_obj_t * pm = &displays[i].rgbmatrix; - if(!any_display_uses_this_framebuffer(&pm->base)) { + rgbmatrix_rgbmatrix_obj_t *pm = &displays[i].rgbmatrix; + if (!any_display_uses_this_framebuffer(&pm->base)) { common_hal_rgbmatrix_rgbmatrix_deinit(pm); } -#endif -#if CIRCUITPY_SHARPDISPLAY + #endif + #if CIRCUITPY_SHARPDISPLAY } else if (displays[i].bus_base.type == &sharpdisplay_framebuffer_type) { - sharpdisplay_framebuffer_obj_t * sharp = &displays[i].sharpdisplay; + sharpdisplay_framebuffer_obj_t *sharp = &displays[i].sharpdisplay; common_hal_sharpdisplay_framebuffer_reset(sharp); -#endif + #endif } else { // Not an active display bus. continue; @@ -204,28 +204,28 @@ void reset_displays(void) { if (displays[i].display.base.type == &displayio_display_type) { reset_display(&displays[i].display); } else if (displays[i].epaper_display.base.type == &displayio_epaperdisplay_type) { - displayio_epaperdisplay_obj_t* display = &displays[i].epaper_display; + displayio_epaperdisplay_obj_t *display = &displays[i].epaper_display; common_hal_displayio_epaperdisplay_show(display, NULL); -#if CIRCUITPY_FRAMEBUFFERIO + #if CIRCUITPY_FRAMEBUFFERIO } else if (displays[i].framebuffer_display.base.type == &framebufferio_framebufferdisplay_type) { framebufferio_framebufferdisplay_reset(&displays[i].framebuffer_display); -#endif + #endif } } } void displayio_gc_collect(void) { for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { -#if CIRCUITPY_RGBMATRIX + #if CIRCUITPY_RGBMATRIX if (displays[i].rgbmatrix.base.type == &rgbmatrix_RGBMatrix_type) { rgbmatrix_rgbmatrix_collect_ptrs(&displays[i].rgbmatrix); } -#endif -#if CIRCUITPY_SHARPDISPLAY + #endif + #if CIRCUITPY_SHARPDISPLAY if (displays[i].bus_base.type == &sharpdisplay_framebuffer_type) { common_hal_sharpdisplay_framebuffer_collect_ptrs(&displays[i].sharpdisplay); } -#endif + #endif if (displays[i].display.base.type == NULL) { continue; @@ -235,17 +235,17 @@ void displayio_gc_collect(void) { // but this is more precise, and is the only field that needs marking. if (displays[i].display.base.type == &displayio_display_type) { displayio_display_collect_ptrs(&displays[i].display); -#if CIRCUITPY_FRAMEBUFFERIO + #if CIRCUITPY_FRAMEBUFFERIO } else if (displays[i].framebuffer_display.base.type == &framebufferio_framebufferdisplay_type) { framebufferio_framebufferdisplay_collect_ptrs(&displays[i].framebuffer_display); -#endif + #endif } else if (displays[i].epaper_display.base.type == &displayio_epaperdisplay_type) { displayio_epaperdisplay_collect_ptrs(&displays[i].epaper_display); } } } -void displayio_area_expand(displayio_area_t* original, const displayio_area_t* addition) { +void displayio_area_expand(displayio_area_t *original, const displayio_area_t *addition) { if (addition->x1 < original->x1) { original->x1 = addition->x1; } @@ -260,30 +260,30 @@ void displayio_area_expand(displayio_area_t* original, const displayio_area_t* a } } -void displayio_area_copy(const displayio_area_t* src, displayio_area_t* dst) { +void displayio_area_copy(const displayio_area_t *src, displayio_area_t *dst) { dst->x1 = src->x1; dst->y1 = src->y1; dst->x2 = src->x2; dst->y2 = src->y2; } -void displayio_area_scale(displayio_area_t* area, uint16_t scale) { +void displayio_area_scale(displayio_area_t *area, uint16_t scale) { area->x1 *= scale; area->y1 *= scale; area->x2 *= scale; area->y2 *= scale; } -void displayio_area_shift(displayio_area_t* area, int16_t dx, int16_t dy) { +void displayio_area_shift(displayio_area_t *area, int16_t dx, int16_t dy) { area->x1 += dx; area->y1 += dy; area->x2 += dx; area->y2 += dy; } -bool displayio_area_compute_overlap(const displayio_area_t* a, - const displayio_area_t* b, - displayio_area_t* overlap) { +bool displayio_area_compute_overlap(const displayio_area_t *a, + const displayio_area_t *b, + displayio_area_t *overlap) { overlap->x1 = a->x1; if (b->x1 > overlap->x1) { overlap->x1 = b->x1; @@ -309,9 +309,9 @@ bool displayio_area_compute_overlap(const displayio_area_t* a, return true; } -void displayio_area_union(const displayio_area_t* a, - const displayio_area_t* b, - displayio_area_t* u) { +void displayio_area_union(const displayio_area_t *a, + const displayio_area_t *b, + displayio_area_t *u) { u->x1 = a->x1; if (b->x1 < u->x1) { u->x1 = b->x1; @@ -331,19 +331,19 @@ void displayio_area_union(const displayio_area_t* a, } } -uint16_t displayio_area_width(const displayio_area_t* area) { +uint16_t displayio_area_width(const displayio_area_t *area) { return area->x2 - area->x1; } -uint16_t displayio_area_height(const displayio_area_t* area) { +uint16_t displayio_area_height(const displayio_area_t *area) { return area->y2 - area->y1; } -uint32_t displayio_area_size(const displayio_area_t* area) { +uint32_t displayio_area_size(const displayio_area_t *area) { return displayio_area_width(area) * displayio_area_height(area); } -bool displayio_area_equal(const displayio_area_t* a, const displayio_area_t* b) { +bool displayio_area_equal(const displayio_area_t *a, const displayio_area_t *b) { return a->x1 == b->x1 && a->y1 == b->y1 && a->x2 == b->x2 && @@ -352,9 +352,9 @@ bool displayio_area_equal(const displayio_area_t* a, const displayio_area_t* b) // Original and whole must be in the same coordinate space. void displayio_area_transform_within(bool mirror_x, bool mirror_y, bool transpose_xy, - const displayio_area_t* original, - const displayio_area_t* whole, - displayio_area_t* transformed) { + const displayio_area_t *original, + const displayio_area_t *whole, + displayio_area_t *transformed) { if (mirror_x) { transformed->x1 = whole->x1 + (whole->x2 - original->x2); transformed->x2 = whole->x2 - (original->x1 - whole->x1); diff --git a/shared-module/displayio/__init__.h b/shared-module/displayio/__init__.h index 44ad5a9a98..4a74b0e0e0 100644 --- a/shared-module/displayio/__init__.h +++ b/shared-module/displayio/__init__.h @@ -49,20 +49,20 @@ typedef struct { displayio_fourwire_obj_t fourwire_bus; displayio_i2cdisplay_obj_t i2cdisplay_bus; displayio_parallelbus_obj_t parallel_bus; -#if CIRCUITPY_RGBMATRIX + #if CIRCUITPY_RGBMATRIX rgbmatrix_rgbmatrix_obj_t rgbmatrix; -#endif -#if CIRCUITPY_SHARPDISPLAY + #endif + #if CIRCUITPY_SHARPDISPLAY sharpdisplay_framebuffer_obj_t sharpdisplay; -#endif + #endif }; union { mp_obj_base_t display_base; displayio_display_obj_t display; displayio_epaperdisplay_obj_t epaper_display; -#if CIRCUITPY_FRAMEBUFFERIO + #if CIRCUITPY_FRAMEBUFFERIO framebufferio_framebufferdisplay_obj_t framebuffer_display; -#endif + #endif }; } primary_display_t; diff --git a/shared-module/displayio/area.h b/shared-module/displayio/area.h index 7ad36883ce..21bf2f8b25 100644 --- a/shared-module/displayio/area.h +++ b/shared-module/displayio/area.h @@ -35,7 +35,7 @@ struct _displayio_area_t { int16_t y1; int16_t x2; // Second point is exclusive. int16_t y2; - const displayio_area_t* next; // Next area in the linked list. + const displayio_area_t *next; // Next area in the linked list. }; typedef struct { @@ -53,23 +53,23 @@ typedef struct { extern displayio_buffer_transform_t null_transform; -void displayio_area_union(const displayio_area_t* a, - const displayio_area_t* b, - displayio_area_t* u); -void displayio_area_expand(displayio_area_t* original, const displayio_area_t* addition); -void displayio_area_copy(const displayio_area_t* src, displayio_area_t* dst); -void displayio_area_scale(displayio_area_t* area, uint16_t scale); -void displayio_area_shift(displayio_area_t* area, int16_t dx, int16_t dy); -bool displayio_area_compute_overlap(const displayio_area_t* a, - const displayio_area_t* b, - displayio_area_t* overlap); -uint16_t displayio_area_width(const displayio_area_t* area); -uint16_t displayio_area_height(const displayio_area_t* area); -uint32_t displayio_area_size(const displayio_area_t* area); -bool displayio_area_equal(const displayio_area_t* a, const displayio_area_t* b); +void displayio_area_union(const displayio_area_t *a, + const displayio_area_t *b, + displayio_area_t *u); +void displayio_area_expand(displayio_area_t *original, const displayio_area_t *addition); +void displayio_area_copy(const displayio_area_t *src, displayio_area_t *dst); +void displayio_area_scale(displayio_area_t *area, uint16_t scale); +void displayio_area_shift(displayio_area_t *area, int16_t dx, int16_t dy); +bool displayio_area_compute_overlap(const displayio_area_t *a, + const displayio_area_t *b, + displayio_area_t *overlap); +uint16_t displayio_area_width(const displayio_area_t *area); +uint16_t displayio_area_height(const displayio_area_t *area); +uint32_t displayio_area_size(const displayio_area_t *area); +bool displayio_area_equal(const displayio_area_t *a, const displayio_area_t *b); void displayio_area_transform_within(bool mirror_x, bool mirror_y, bool transpose_xy, - const displayio_area_t* original, - const displayio_area_t* whole, - displayio_area_t* transformed); + const displayio_area_t *original, + const displayio_area_t *whole, + displayio_area_t *transformed); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_AREA_H diff --git a/shared-module/displayio/display_core.c b/shared-module/displayio/display_core.c index 57d33b5651..a0b3afa0ee 100644 --- a/shared-module/displayio/display_core.c +++ b/shared-module/displayio/display_core.c @@ -43,9 +43,9 @@ #define DISPLAYIO_CORE_DEBUG(...) (void)0 // #define DISPLAYIO_CORE_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) -void displayio_display_core_construct(displayio_display_core_t* self, - mp_obj_t bus, uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t rotation, - uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word) { +void displayio_display_core_construct(displayio_display_core_t *self, + mp_obj_t bus, uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t rotation, + uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word) { self->colorspace.depth = color_depth; self->colorspace.grayscale = grayscale; self->colorspace.grayscale_bit = 8 - color_depth; @@ -99,8 +99,8 @@ void displayio_display_core_construct(displayio_display_core_t* self, displayio_display_core_set_rotation(self, rotation); } -void displayio_display_core_set_rotation( displayio_display_core_t* self, - int rotation) { +void displayio_display_core_set_rotation(displayio_display_core_t *self, + int rotation) { int height = self->height; int width = self->width; @@ -157,7 +157,7 @@ void displayio_display_core_set_rotation( displayio_display_core_t* self, } } -bool displayio_display_core_show(displayio_display_core_t* self, displayio_group_t* root_group) { +bool displayio_display_core_show(displayio_display_core_t *self, displayio_group_t *root_group) { if (root_group == NULL) { if (!circuitpython_splash.in_group) { root_group = &circuitpython_splash; @@ -184,19 +184,19 @@ bool displayio_display_core_show(displayio_display_core_t* self, displayio_group return true; } -uint16_t displayio_display_core_get_width(displayio_display_core_t* self){ +uint16_t displayio_display_core_get_width(displayio_display_core_t *self) { return self->width; } -uint16_t displayio_display_core_get_height(displayio_display_core_t* self){ +uint16_t displayio_display_core_get_height(displayio_display_core_t *self) { return self->height; } -void displayio_display_core_set_dither(displayio_display_core_t* self, bool dither){ +void displayio_display_core_set_dither(displayio_display_core_t *self, bool dither) { self->colorspace.dither = dither; } -bool displayio_display_core_get_dither(displayio_display_core_t* self){ +bool displayio_display_core_get_dither(displayio_display_core_t *self) { return self->colorspace.dither; } @@ -204,18 +204,18 @@ bool displayio_display_core_bus_free(displayio_display_core_t *self) { return !self->bus || self->bus_free(self->bus); } -bool displayio_display_core_begin_transaction(displayio_display_core_t* self) { +bool displayio_display_core_begin_transaction(displayio_display_core_t *self) { return self->begin_transaction(self->bus); } -void displayio_display_core_end_transaction(displayio_display_core_t* self) { +void displayio_display_core_end_transaction(displayio_display_core_t *self) { self->end_transaction(self->bus); } -void displayio_display_core_set_region_to_update(displayio_display_core_t* self, uint8_t column_command, - uint8_t row_command, uint16_t set_current_column_command, uint16_t set_current_row_command, - bool data_as_commands, bool always_toggle_chip_select, - displayio_area_t* area, bool SH1107_addressing) { +void displayio_display_core_set_region_to_update(displayio_display_core_t *self, uint8_t column_command, + uint8_t row_command, uint16_t set_current_column_command, uint16_t set_current_row_command, + bool data_as_commands, bool always_toggle_chip_select, + displayio_area_t *area, bool SH1107_addressing) { uint16_t x1 = area->x1; uint16_t x2 = area->x2; uint16_t y1 = area->y1; @@ -320,7 +320,7 @@ void displayio_display_core_set_region_to_update(displayio_display_core_t* self, } } -bool displayio_display_core_start_refresh(displayio_display_core_t* self) { +bool displayio_display_core_start_refresh(displayio_display_core_t *self) { if (!displayio_display_core_bus_free(self)) { // Can't acquire display bus; skip updating this display. Try next display. return false; @@ -333,7 +333,7 @@ bool displayio_display_core_start_refresh(displayio_display_core_t* self) { return true; } -void displayio_display_core_finish_refresh(displayio_display_core_t* self) { +void displayio_display_core_finish_refresh(displayio_display_core_t *self) { if (self->current_group != NULL) { DISPLAYIO_CORE_DEBUG("displayiocore group_finish_refresh\n"); displayio_group_finish_refresh(self->current_group); @@ -343,21 +343,21 @@ void displayio_display_core_finish_refresh(displayio_display_core_t* self) { self->last_refresh = supervisor_ticks_ms64(); } -void release_display_core(displayio_display_core_t* self) { +void release_display_core(displayio_display_core_t *self) { if (self->current_group != NULL) { self->current_group->in_group = false; } } -void displayio_display_core_collect_ptrs(displayio_display_core_t* self) { +void displayio_display_core_collect_ptrs(displayio_display_core_t *self) { gc_collect_ptr(self->current_group); } -bool displayio_display_core_fill_area(displayio_display_core_t *self, displayio_area_t* area, uint32_t* mask, uint32_t *buffer) { +bool displayio_display_core_fill_area(displayio_display_core_t *self, displayio_area_t *area, uint32_t *mask, uint32_t *buffer) { return displayio_group_fill_area(self->current_group, &self->colorspace, area, mask, buffer); } -bool displayio_display_core_clip_area(displayio_display_core_t *self, const displayio_area_t* area, displayio_area_t* clipped) { +bool displayio_display_core_clip_area(displayio_display_core_t *self, const displayio_area_t *area, displayio_area_t *clipped) { bool overlaps = displayio_area_compute_overlap(&self->area, area, clipped); if (!overlaps) { return false; diff --git a/shared-module/displayio/display_core.h b/shared-module/displayio/display_core.h index fe6cb6f3f5..8c2ba21b5e 100644 --- a/shared-module/displayio/display_core.h +++ b/shared-module/displayio/display_core.h @@ -57,38 +57,38 @@ typedef struct { bool refresh_in_progress; } displayio_display_core_t; -void displayio_display_core_construct(displayio_display_core_t* self, - mp_obj_t bus, uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t rotation, - uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word); +void displayio_display_core_construct(displayio_display_core_t *self, + mp_obj_t bus, uint16_t width, uint16_t height, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t rotation, + uint16_t color_depth, bool grayscale, bool pixels_in_byte_share_row, uint8_t bytes_per_cell, bool reverse_pixels_in_byte, bool reverse_bytes_in_word); -bool displayio_display_core_show(displayio_display_core_t* self, displayio_group_t* root_group); +bool displayio_display_core_show(displayio_display_core_t *self, displayio_group_t *root_group); -uint16_t displayio_display_core_get_width(displayio_display_core_t* self); -uint16_t displayio_display_core_get_height(displayio_display_core_t* self); +uint16_t displayio_display_core_get_width(displayio_display_core_t *self); +uint16_t displayio_display_core_get_height(displayio_display_core_t *self); -void displayio_display_core_set_dither(displayio_display_core_t* self, bool dither); -bool displayio_display_core_get_dither(displayio_display_core_t* self); +void displayio_display_core_set_dither(displayio_display_core_t *self, bool dither); +bool displayio_display_core_get_dither(displayio_display_core_t *self); -void displayio_display_core_set_rotation(displayio_display_core_t* self, int rotation); +void displayio_display_core_set_rotation(displayio_display_core_t *self, int rotation); bool displayio_display_core_bus_free(displayio_display_core_t *self); -bool displayio_display_core_begin_transaction(displayio_display_core_t* self); -void displayio_display_core_end_transaction(displayio_display_core_t* self); +bool displayio_display_core_begin_transaction(displayio_display_core_t *self); +void displayio_display_core_end_transaction(displayio_display_core_t *self); -void displayio_display_core_set_region_to_update(displayio_display_core_t* self, uint8_t column_command, - uint8_t row_command, uint16_t set_current_column_command, uint16_t set_current_row_command, - bool data_as_commands, bool always_toggle_chip_select, - displayio_area_t* area, bool SH1107_addressing); +void displayio_display_core_set_region_to_update(displayio_display_core_t *self, uint8_t column_command, + uint8_t row_command, uint16_t set_current_column_command, uint16_t set_current_row_command, + bool data_as_commands, bool always_toggle_chip_select, + displayio_area_t *area, bool SH1107_addressing); -void release_display_core(displayio_display_core_t* self); +void release_display_core(displayio_display_core_t *self); -bool displayio_display_core_start_refresh(displayio_display_core_t* self); -void displayio_display_core_finish_refresh(displayio_display_core_t* self); +bool displayio_display_core_start_refresh(displayio_display_core_t *self); +void displayio_display_core_finish_refresh(displayio_display_core_t *self); -void displayio_display_core_collect_ptrs(displayio_display_core_t* self); +void displayio_display_core_collect_ptrs(displayio_display_core_t *self); -bool displayio_display_core_fill_area(displayio_display_core_t *self, displayio_area_t* area, uint32_t* mask, uint32_t *buffer); +bool displayio_display_core_fill_area(displayio_display_core_t *self, displayio_area_t *area, uint32_t *mask, uint32_t *buffer); -bool displayio_display_core_clip_area(displayio_display_core_t *self, const displayio_area_t* area, displayio_area_t* clipped); +bool displayio_display_core_clip_area(displayio_display_core_t *self, const displayio_area_t *area, displayio_area_t *clipped); #endif // MICROPY_INCLUDED_SHARED_MODULE_DISPLAYIO_DISPLAY_CORE_H diff --git a/shared-module/fontio/BuiltinFont.c b/shared-module/fontio/BuiltinFont.c index 58820d5240..b77a6a1c8b 100644 --- a/shared-module/fontio/BuiltinFont.c +++ b/shared-module/fontio/BuiltinFont.c @@ -47,7 +47,7 @@ uint8_t fontio_builtinfont_get_glyph_index(const fontio_builtinfont_t *self, mp_ return codepoint - 0x20; } // Do a linear search of the mapping for unicode. - const byte* j = self->unicode_characters; + const byte *j = self->unicode_characters; uint8_t k = 0; while (j < self->unicode_characters + self->unicode_characters_len) { unichar potential_c = utf8_get_char(j); @@ -75,5 +75,5 @@ mp_obj_t common_hal_fontio_builtinfont_get_glyph(const fontio_builtinfont_t *sel MP_OBJ_NEW_SMALL_INT(self->width), MP_OBJ_NEW_SMALL_INT(0) }; - return namedtuple_make_new((const mp_obj_type_t*) &fontio_glyph_type, 8, field_values, NULL); + return namedtuple_make_new((const mp_obj_type_t *)&fontio_glyph_type, 8, field_values, NULL); } diff --git a/shared-module/fontio/BuiltinFont.h b/shared-module/fontio/BuiltinFont.h index 30b4ade8c6..79c8614194 100644 --- a/shared-module/fontio/BuiltinFont.h +++ b/shared-module/fontio/BuiltinFont.h @@ -35,10 +35,10 @@ typedef struct { mp_obj_base_t base; - const displayio_bitmap_t* bitmap; + const displayio_bitmap_t *bitmap; uint8_t width; uint8_t height; - const byte* unicode_characters; + const byte *unicode_characters; uint16_t unicode_characters_len; } fontio_builtinfont_t; diff --git a/shared-module/framebufferio/FramebufferDisplay.c b/shared-module/framebufferio/FramebufferDisplay.c index 03e121c914..e236616f93 100644 --- a/shared-module/framebufferio/FramebufferDisplay.c +++ b/shared-module/framebufferio/FramebufferDisplay.c @@ -45,10 +45,10 @@ ? self->framebuffer_protocol->method(self->framebuffer) \ : (default_value)) -void common_hal_framebufferio_framebufferdisplay_construct(framebufferio_framebufferdisplay_obj_t* self, - mp_obj_t framebuffer, - uint16_t rotation, - bool auto_refresh) { +void common_hal_framebufferio_framebufferdisplay_construct(framebufferio_framebufferdisplay_obj_t *self, + mp_obj_t framebuffer, + uint16_t rotation, + bool auto_refresh) { // Turn off auto-refresh as we init. self->auto_refresh = false; self->framebuffer = framebuffer; @@ -73,12 +73,12 @@ void common_hal_framebufferio_framebufferdisplay_construct(framebufferio_framebu fb_getter_default(get_bytes_per_cell, 2), fb_getter_default(get_reverse_pixels_in_byte, false), fb_getter_default(get_reverse_pixels_in_word, false) - ); + ); self->first_pixel_offset = fb_getter_default(get_first_pixel_offset, 0); self->row_stride = fb_getter_default(get_row_stride, 0); if (self->row_stride == 0) { - self->row_stride = self->core.width * self->core.colorspace.depth/8; + self->row_stride = self->core.width * self->core.colorspace.depth / 8; } self->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); @@ -102,40 +102,40 @@ void common_hal_framebufferio_framebufferdisplay_construct(framebufferio_framebu common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, auto_refresh); } -bool common_hal_framebufferio_framebufferdisplay_show(framebufferio_framebufferdisplay_obj_t* self, displayio_group_t* root_group) { +bool common_hal_framebufferio_framebufferdisplay_show(framebufferio_framebufferdisplay_obj_t *self, displayio_group_t *root_group) { return displayio_display_core_show(&self->core, root_group); } -uint16_t common_hal_framebufferio_framebufferdisplay_get_width(framebufferio_framebufferdisplay_obj_t* self){ +uint16_t common_hal_framebufferio_framebufferdisplay_get_width(framebufferio_framebufferdisplay_obj_t *self) { return displayio_display_core_get_width(&self->core); } -uint16_t common_hal_framebufferio_framebufferdisplay_get_height(framebufferio_framebufferdisplay_obj_t* self){ +uint16_t common_hal_framebufferio_framebufferdisplay_get_height(framebufferio_framebufferdisplay_obj_t *self) { return displayio_display_core_get_height(&self->core); } -bool common_hal_framebufferio_framebufferdisplay_get_auto_brightness(framebufferio_framebufferdisplay_obj_t* self) { +bool common_hal_framebufferio_framebufferdisplay_get_auto_brightness(framebufferio_framebufferdisplay_obj_t *self) { if (self->framebuffer_protocol->get_auto_brightness) { return self->framebuffer_protocol->get_auto_brightness(self->framebuffer); } return true; } -bool common_hal_framebufferio_framebufferdisplay_set_auto_brightness(framebufferio_framebufferdisplay_obj_t* self, bool auto_brightness) { +bool common_hal_framebufferio_framebufferdisplay_set_auto_brightness(framebufferio_framebufferdisplay_obj_t *self, bool auto_brightness) { if (self->framebuffer_protocol->set_auto_brightness) { return self->framebuffer_protocol->set_auto_brightness(self->framebuffer, auto_brightness); } return false; } -mp_float_t common_hal_framebufferio_framebufferdisplay_get_brightness(framebufferio_framebufferdisplay_obj_t* self) { +mp_float_t common_hal_framebufferio_framebufferdisplay_get_brightness(framebufferio_framebufferdisplay_obj_t *self) { if (self->framebuffer_protocol->get_brightness) { return self->framebuffer_protocol->get_brightness(self->framebuffer); } return -1; } -bool common_hal_framebufferio_framebufferdisplay_set_brightness(framebufferio_framebufferdisplay_obj_t* self, mp_float_t brightness) { +bool common_hal_framebufferio_framebufferdisplay_set_brightness(framebufferio_framebufferdisplay_obj_t *self, mp_float_t brightness) { bool ok = false; if (self->framebuffer_protocol->set_brightness) { self->framebuffer_protocol->set_brightness(self->framebuffer, brightness); @@ -144,11 +144,11 @@ bool common_hal_framebufferio_framebufferdisplay_set_brightness(framebufferio_fr return ok; } -mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t* self) { +mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t *self) { return self->framebuffer; } -STATIC const displayio_area_t* _get_refresh_areas(framebufferio_framebufferdisplay_obj_t *self) { +STATIC const displayio_area_t *_get_refresh_areas(framebufferio_framebufferdisplay_obj_t *self) { if (self->core.full_refresh) { self->core.area.next = NULL; return &self->core.area; @@ -158,8 +158,8 @@ STATIC const displayio_area_t* _get_refresh_areas(framebufferio_framebufferdispl return NULL; } -#define MARK_ROW_DIRTY(r) (dirty_row_bitmask[r/8] |= (1 << (r & 7))) -STATIC bool _refresh_area(framebufferio_framebufferdisplay_obj_t* self, const displayio_area_t* area, uint8_t *dirty_row_bitmask) { +#define MARK_ROW_DIRTY(r) (dirty_row_bitmask[r / 8] |= (1 << (r & 7))) +STATIC bool _refresh_area(framebufferio_framebufferdisplay_obj_t *self, const displayio_area_t *area, uint8_t *dirty_row_bitmask) { uint16_t buffer_size = 128; // In uint32_ts displayio_area_t clipped; @@ -233,11 +233,11 @@ STATIC bool _refresh_area(framebufferio_framebufferdisplay_obj_t* self, const di size_t rowstride = self->row_stride; uint8_t *dest = buf + subrectangle.y1 * rowstride + subrectangle.x1 * self->core.colorspace.depth / 8; - uint8_t *src = (uint8_t*)buffer; + uint8_t *src = (uint8_t *)buffer; size_t rowsize = (subrectangle.x2 - subrectangle.x1) * self->core.colorspace.depth / 8; for (uint16_t i = subrectangle.y1; i < subrectangle.y2; i++) { - assert(dest >= buf && dest < endbuf && dest+rowsize <= endbuf); + assert(dest >= buf && dest < endbuf && dest + rowsize <= endbuf); MARK_ROW_DIRTY(i); memcpy(dest, src, rowsize); dest += rowstride; @@ -251,13 +251,13 @@ STATIC bool _refresh_area(framebufferio_framebufferdisplay_obj_t* self, const di return true; } -STATIC void _refresh_display(framebufferio_framebufferdisplay_obj_t* self) { +STATIC void _refresh_display(framebufferio_framebufferdisplay_obj_t *self) { self->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); - if(!self->bufinfo.buf) { + if (!self->bufinfo.buf) { return; } displayio_display_core_start_refresh(&self->core); - const displayio_area_t* current_area = _get_refresh_areas(self); + const displayio_area_t *current_area = _get_refresh_areas(self); if (current_area) { uint8_t dirty_row_bitmask[(self->core.height + 7) / 8]; memset(dirty_row_bitmask, 0, sizeof(dirty_row_bitmask)); @@ -271,10 +271,10 @@ STATIC void _refresh_display(framebufferio_framebufferdisplay_obj_t* self) { displayio_display_core_finish_refresh(&self->core); } -void common_hal_framebufferio_framebufferdisplay_set_rotation(framebufferio_framebufferdisplay_obj_t* self, int rotation){ +void common_hal_framebufferio_framebufferdisplay_set_rotation(framebufferio_framebufferdisplay_obj_t *self, int rotation) { bool transposed = (self->core.rotation == 90 || self->core.rotation == 270); bool will_transposed = (rotation == 90 || rotation == 270); - if(transposed != will_transposed) { + if (transposed != will_transposed) { int tmp = self->core.width; self->core.width = self->core.height; self->core.height = tmp; @@ -289,12 +289,12 @@ void common_hal_framebufferio_framebufferdisplay_set_rotation(framebufferio_fram } } -uint16_t common_hal_framebufferio_framebufferdisplay_get_rotation(framebufferio_framebufferdisplay_obj_t* self){ +uint16_t common_hal_framebufferio_framebufferdisplay_get_rotation(framebufferio_framebufferdisplay_obj_t *self) { return self->core.rotation; } -bool common_hal_framebufferio_framebufferdisplay_refresh(framebufferio_framebufferdisplay_obj_t* self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame) { +bool common_hal_framebufferio_framebufferdisplay_refresh(framebufferio_framebufferdisplay_obj_t *self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame) { if (!self->auto_refresh && !self->first_manual_refresh) { uint64_t current_time = supervisor_ticks_ms64(); uint32_t current_ms_since_real_refresh = current_time - self->core.last_refresh; @@ -319,12 +319,12 @@ bool common_hal_framebufferio_framebufferdisplay_refresh(framebufferio_framebuff return true; } -bool common_hal_framebufferio_framebufferdisplay_get_auto_refresh(framebufferio_framebufferdisplay_obj_t* self) { +bool common_hal_framebufferio_framebufferdisplay_get_auto_refresh(framebufferio_framebufferdisplay_obj_t *self) { return self->auto_refresh; } -void common_hal_framebufferio_framebufferdisplay_set_auto_refresh(framebufferio_framebufferdisplay_obj_t* self, - bool auto_refresh) { +void common_hal_framebufferio_framebufferdisplay_set_auto_refresh(framebufferio_framebufferdisplay_obj_t *self, + bool auto_refresh) { self->first_manual_refresh = !auto_refresh; if (auto_refresh != self->auto_refresh) { if (auto_refresh) { @@ -336,12 +336,12 @@ void common_hal_framebufferio_framebufferdisplay_set_auto_refresh(framebufferio_ self->auto_refresh = auto_refresh; } -STATIC void _update_backlight(framebufferio_framebufferdisplay_obj_t* self) { +STATIC void _update_backlight(framebufferio_framebufferdisplay_obj_t *self) { // TODO(tannewt): Fade the backlight based on it's existing value and a target value. The target // should account for ambient light when possible. } -void framebufferio_framebufferdisplay_background(framebufferio_framebufferdisplay_obj_t* self) { +void framebufferio_framebufferdisplay_background(framebufferio_framebufferdisplay_obj_t *self) { _update_backlight(self); if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) { @@ -349,21 +349,21 @@ void framebufferio_framebufferdisplay_background(framebufferio_framebufferdispla } } -void release_framebufferdisplay(framebufferio_framebufferdisplay_obj_t* self) { +void release_framebufferdisplay(framebufferio_framebufferdisplay_obj_t *self) { common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, false); release_display_core(&self->core); self->framebuffer_protocol->deinit(self->framebuffer); self->base.type = &mp_type_NoneType; } -void framebufferio_framebufferdisplay_collect_ptrs(framebufferio_framebufferdisplay_obj_t* self) { +void framebufferio_framebufferdisplay_collect_ptrs(framebufferio_framebufferdisplay_obj_t *self) { gc_collect_ptr(self->framebuffer); displayio_display_core_collect_ptrs(&self->core); } -void framebufferio_framebufferdisplay_reset(framebufferio_framebufferdisplay_obj_t* self) { +void framebufferio_framebufferdisplay_reset(framebufferio_framebufferdisplay_obj_t *self) { mp_obj_type_t *fb_type = mp_obj_get_type(self->framebuffer); - if(fb_type != NULL && fb_type != &mp_type_NoneType) { + if (fb_type != NULL && fb_type != &mp_type_NoneType) { common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, true); common_hal_framebufferio_framebufferdisplay_show(self, NULL); self->core.full_refresh = true; diff --git a/shared-module/framebufferio/FramebufferDisplay.h b/shared-module/framebufferio/FramebufferDisplay.h index d73d4b9a95..b6138e2202 100644 --- a/shared-module/framebufferio/FramebufferDisplay.h +++ b/shared-module/framebufferio/FramebufferDisplay.h @@ -53,13 +53,13 @@ typedef struct { bool first_manual_refresh; } framebufferio_framebufferdisplay_obj_t; -void framebufferio_framebufferdisplay_background(framebufferio_framebufferdisplay_obj_t* self); -void release_framebufferdisplay(framebufferio_framebufferdisplay_obj_t* self); -void framebufferio_framebufferdisplay_reset(framebufferio_framebufferdisplay_obj_t* self); +void framebufferio_framebufferdisplay_background(framebufferio_framebufferdisplay_obj_t *self); +void release_framebufferdisplay(framebufferio_framebufferdisplay_obj_t *self); +void framebufferio_framebufferdisplay_reset(framebufferio_framebufferdisplay_obj_t *self); -void framebufferio_framebufferdisplay_collect_ptrs(framebufferio_framebufferdisplay_obj_t* self); +void framebufferio_framebufferdisplay_collect_ptrs(framebufferio_framebufferdisplay_obj_t *self); -mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t* self); +mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t *self); typedef bool (*framebuffer_get_auto_brightness_fun)(mp_obj_t); typedef bool (*framebuffer_get_reverse_pixels_in_byte_fun)(mp_obj_t); diff --git a/shared-module/gamepad/GamePad.c b/shared-module/gamepad/GamePad.c index 7b4108eb2e..55b447f1eb 100644 --- a/shared-module/gamepad/GamePad.c +++ b/shared-module/gamepad/GamePad.c @@ -30,7 +30,7 @@ #include "supervisor/shared/tick.h" void common_hal_gamepad_gamepad_init(gamepad_obj_t *gamepad, - const mp_obj_t pins[], size_t n_pins) { + const mp_obj_t pins[], size_t n_pins) { for (size_t i = 0; i < 8; ++i) { gamepad->pins[i] = NULL; } diff --git a/shared-module/gamepad/GamePad.h b/shared-module/gamepad/GamePad.h index 048fbcd2b2..7c28e2285b 100644 --- a/shared-module/gamepad/GamePad.h +++ b/shared-module/gamepad/GamePad.h @@ -33,7 +33,7 @@ typedef struct { mp_obj_base_t base; - digitalio_digitalinout_obj_t* pins[8]; + digitalio_digitalinout_obj_t *pins[8]; volatile uint8_t last; volatile uint8_t pressed; uint8_t pulls; diff --git a/shared-module/gamepad/__init__.c b/shared-module/gamepad/__init__.c index 9874b27529..c707886065 100644 --- a/shared-module/gamepad/__init__.c +++ b/shared-module/gamepad/__init__.c @@ -38,14 +38,14 @@ void gamepad_tick(void) { uint8_t current = 0; uint8_t bit = 1; - void* singleton = MP_STATE_VM(gamepad_singleton); + void *singleton = MP_STATE_VM(gamepad_singleton); if (singleton == NULL || !MP_OBJ_IS_TYPE(MP_OBJ_FROM_PTR(singleton), &gamepad_type)) { return; } gamepad_obj_t *self = MP_OBJ_TO_PTR(singleton); for (int i = 0; i < 8; ++i) { - digitalio_digitalinout_obj_t* pin = self->pins[i]; + digitalio_digitalinout_obj_t *pin = self->pins[i]; if (!pin) { break; } diff --git a/shared-module/gamepadshift/GamePadShift.c b/shared-module/gamepadshift/GamePadShift.c index 51da617021..6efa0ea5cf 100644 --- a/shared-module/gamepadshift/GamePadShift.c +++ b/shared-module/gamepadshift/GamePadShift.c @@ -30,16 +30,16 @@ #include "supervisor/shared/tick.h" void common_hal_gamepadshift_gamepadshift_init(gamepadshift_obj_t *gamepadshift, - digitalio_digitalinout_obj_t *clock_pin, - digitalio_digitalinout_obj_t *data_pin, - digitalio_digitalinout_obj_t *latch_pin) { + digitalio_digitalinout_obj_t *clock_pin, + digitalio_digitalinout_obj_t *data_pin, + digitalio_digitalinout_obj_t *latch_pin) { common_hal_digitalio_digitalinout_switch_to_input(data_pin, PULL_NONE); gamepadshift->data_pin = data_pin; common_hal_digitalio_digitalinout_switch_to_output(clock_pin, 0, - DRIVE_MODE_PUSH_PULL); + DRIVE_MODE_PUSH_PULL); gamepadshift->clock_pin = clock_pin; common_hal_digitalio_digitalinout_switch_to_output(latch_pin, 1, - DRIVE_MODE_PUSH_PULL); + DRIVE_MODE_PUSH_PULL); gamepadshift->latch_pin = latch_pin; gamepadshift->last = 0; diff --git a/shared-module/gamepadshift/GamePadShift.h b/shared-module/gamepadshift/GamePadShift.h index b4b26b7a98..53aef50986 100644 --- a/shared-module/gamepadshift/GamePadShift.h +++ b/shared-module/gamepadshift/GamePadShift.h @@ -33,9 +33,9 @@ typedef struct { mp_obj_base_t base; - digitalio_digitalinout_obj_t* data_pin; - digitalio_digitalinout_obj_t* clock_pin; - digitalio_digitalinout_obj_t* latch_pin; + digitalio_digitalinout_obj_t *data_pin; + digitalio_digitalinout_obj_t *clock_pin; + digitalio_digitalinout_obj_t *latch_pin; volatile uint8_t pressed; volatile uint8_t last; } gamepadshift_obj_t; diff --git a/shared-module/gamepadshift/__init__.c b/shared-module/gamepadshift/__init__.c index 47a008c503..44cf3be812 100644 --- a/shared-module/gamepadshift/__init__.c +++ b/shared-module/gamepadshift/__init__.c @@ -30,7 +30,7 @@ #include "shared-bindings/gamepadshift/GamePadShift.h" void gamepadshift_tick(void) { - void* singleton = MP_STATE_VM(gamepad_singleton); + void *singleton = MP_STATE_VM(gamepad_singleton); if (singleton == NULL || !MP_OBJ_IS_TYPE(MP_OBJ_FROM_PTR(singleton), &gamepadshift_type)) { return; } diff --git a/shared-module/ipaddress/IPv4Address.c b/shared-module/ipaddress/IPv4Address.c index f573d9d0a2..6850fcadc0 100644 --- a/shared-module/ipaddress/IPv4Address.c +++ b/shared-module/ipaddress/IPv4Address.c @@ -30,10 +30,10 @@ #include "shared-bindings/ipaddress/IPv4Address.h" -void common_hal_ipaddress_ipv4address_construct(ipaddress_ipv4address_obj_t* self, uint8_t* buf, size_t len) { +void common_hal_ipaddress_ipv4address_construct(ipaddress_ipv4address_obj_t *self, uint8_t *buf, size_t len) { self->ip_bytes = mp_obj_new_bytes(buf, len); } -mp_obj_t common_hal_ipaddress_ipv4address_get_packed(ipaddress_ipv4address_obj_t* self) { +mp_obj_t common_hal_ipaddress_ipv4address_get_packed(ipaddress_ipv4address_obj_t *self) { return self->ip_bytes; } diff --git a/shared-module/ipaddress/__init__.c b/shared-module/ipaddress/__init__.c index a8f8e1caf8..9d98c0eb7c 100644 --- a/shared-module/ipaddress/__init__.c +++ b/shared-module/ipaddress/__init__.c @@ -28,8 +28,8 @@ #include "shared-bindings/ipaddress/IPv4Address.h" mp_obj_t common_hal_ipaddress_new_ipv4address(uint32_t value) { - ipaddress_ipv4address_obj_t* self = m_new_obj(ipaddress_ipv4address_obj_t); + ipaddress_ipv4address_obj_t *self = m_new_obj(ipaddress_ipv4address_obj_t); self->base.type = &ipaddress_ipv4address_type; - common_hal_ipaddress_ipv4address_construct(self, (uint8_t*) &value, 4); + common_hal_ipaddress_ipv4address_construct(self, (uint8_t *)&value, 4); return MP_OBJ_FROM_PTR(self); } diff --git a/shared-module/memorymonitor/AllocationAlarm.c b/shared-module/memorymonitor/AllocationAlarm.c index 35f4e4c636..473a19396a 100644 --- a/shared-module/memorymonitor/AllocationAlarm.c +++ b/shared-module/memorymonitor/AllocationAlarm.c @@ -31,17 +31,17 @@ #include "py/mpstate.h" #include "py/runtime.h" -void common_hal_memorymonitor_allocationalarm_construct(memorymonitor_allocationalarm_obj_t* self, size_t minimum_block_count) { +void common_hal_memorymonitor_allocationalarm_construct(memorymonitor_allocationalarm_obj_t *self, size_t minimum_block_count) { self->minimum_block_count = minimum_block_count; self->next = NULL; self->previous = NULL; } -void common_hal_memorymonitor_allocationalarm_set_ignore(memorymonitor_allocationalarm_obj_t* self, mp_int_t count) { +void common_hal_memorymonitor_allocationalarm_set_ignore(memorymonitor_allocationalarm_obj_t *self, mp_int_t count) { self->count = count; } -void common_hal_memorymonitor_allocationalarm_pause(memorymonitor_allocationalarm_obj_t* self) { +void common_hal_memorymonitor_allocationalarm_pause(memorymonitor_allocationalarm_obj_t *self) { // Check to make sure we aren't already paused. We can be if we're exiting from an exception we // caused. if (self->previous == NULL) { @@ -52,12 +52,12 @@ void common_hal_memorymonitor_allocationalarm_pause(memorymonitor_allocationalar self->previous = NULL; } -void common_hal_memorymonitor_allocationalarm_resume(memorymonitor_allocationalarm_obj_t* self) { +void common_hal_memorymonitor_allocationalarm_resume(memorymonitor_allocationalarm_obj_t *self) { if (self->previous != NULL) { mp_raise_RuntimeError(translate("Already running")); } self->next = MP_STATE_VM(active_allocationalarms); - self->previous = (memorymonitor_allocationalarm_obj_t**) &MP_STATE_VM(active_allocationalarms); + self->previous = (memorymonitor_allocationalarm_obj_t **)&MP_STATE_VM(active_allocationalarms); if (self->next != NULL) { self->next->previous = &self->next; } @@ -65,11 +65,11 @@ void common_hal_memorymonitor_allocationalarm_resume(memorymonitor_allocationala } void memorymonitor_allocationalarms_allocation(size_t block_count) { - memorymonitor_allocationalarm_obj_t* alarm = MP_OBJ_TO_PTR(MP_STATE_VM(active_allocationalarms)); + memorymonitor_allocationalarm_obj_t *alarm = MP_OBJ_TO_PTR(MP_STATE_VM(active_allocationalarms)); size_t alert_count = 0; while (alarm != NULL) { // Hold onto next in case we remove the alarm from the list. - memorymonitor_allocationalarm_obj_t* next = alarm->next; + memorymonitor_allocationalarm_obj_t *next = alarm->next; if (block_count >= alarm->minimum_block_count) { if (alarm->count > 0) { alarm->count--; diff --git a/shared-module/memorymonitor/AllocationAlarm.h b/shared-module/memorymonitor/AllocationAlarm.h index 172c24f6c8..1f6e3d0692 100644 --- a/shared-module/memorymonitor/AllocationAlarm.h +++ b/shared-module/memorymonitor/AllocationAlarm.h @@ -41,8 +41,8 @@ typedef struct _memorymonitor_allocationalarm_obj_t { size_t minimum_block_count; mp_int_t count; // Store the location that points to us so we can remove ourselves. - memorymonitor_allocationalarm_obj_t** previous; - memorymonitor_allocationalarm_obj_t* next; + memorymonitor_allocationalarm_obj_t **previous; + memorymonitor_allocationalarm_obj_t *next; } memorymonitor_allocationalarm_obj_t; void memorymonitor_allocationalarms_allocation(size_t block_count); diff --git a/shared-module/memorymonitor/AllocationSize.c b/shared-module/memorymonitor/AllocationSize.c index c28e65592c..42fae3b065 100644 --- a/shared-module/memorymonitor/AllocationSize.c +++ b/shared-module/memorymonitor/AllocationSize.c @@ -30,50 +30,50 @@ #include "py/mpstate.h" #include "py/runtime.h" -void common_hal_memorymonitor_allocationsize_construct(memorymonitor_allocationsize_obj_t* self) { +void common_hal_memorymonitor_allocationsize_construct(memorymonitor_allocationsize_obj_t *self) { common_hal_memorymonitor_allocationsize_clear(self); self->next = NULL; self->previous = NULL; } -void common_hal_memorymonitor_allocationsize_pause(memorymonitor_allocationsize_obj_t* self) { +void common_hal_memorymonitor_allocationsize_pause(memorymonitor_allocationsize_obj_t *self) { *self->previous = self->next; self->next = NULL; self->previous = NULL; } -void common_hal_memorymonitor_allocationsize_resume(memorymonitor_allocationsize_obj_t* self) { +void common_hal_memorymonitor_allocationsize_resume(memorymonitor_allocationsize_obj_t *self) { if (self->previous != NULL) { mp_raise_RuntimeError(translate("Already running")); } self->next = MP_STATE_VM(active_allocationsizes); - self->previous = (memorymonitor_allocationsize_obj_t**) &MP_STATE_VM(active_allocationsizes); + self->previous = (memorymonitor_allocationsize_obj_t **)&MP_STATE_VM(active_allocationsizes); if (self->next != NULL) { self->next->previous = &self->next; } MP_STATE_VM(active_allocationsizes) = self; } -void common_hal_memorymonitor_allocationsize_clear(memorymonitor_allocationsize_obj_t* self) { +void common_hal_memorymonitor_allocationsize_clear(memorymonitor_allocationsize_obj_t *self) { for (size_t i = 0; i < ALLOCATION_SIZE_BUCKETS; i++) { self->buckets[i] = 0; } } -uint16_t common_hal_memorymonitor_allocationsize_get_len(memorymonitor_allocationsize_obj_t* self) { +uint16_t common_hal_memorymonitor_allocationsize_get_len(memorymonitor_allocationsize_obj_t *self) { return ALLOCATION_SIZE_BUCKETS; } -size_t common_hal_memorymonitor_allocationsize_get_bytes_per_block(memorymonitor_allocationsize_obj_t* self) { +size_t common_hal_memorymonitor_allocationsize_get_bytes_per_block(memorymonitor_allocationsize_obj_t *self) { return BYTES_PER_BLOCK; } -uint16_t common_hal_memorymonitor_allocationsize_get_item(memorymonitor_allocationsize_obj_t* self, int16_t index) { +uint16_t common_hal_memorymonitor_allocationsize_get_item(memorymonitor_allocationsize_obj_t *self, int16_t index) { return self->buckets[index]; } void memorymonitor_allocationsizes_track_allocation(size_t block_count) { - memorymonitor_allocationsize_obj_t* as = MP_OBJ_TO_PTR(MP_STATE_VM(active_allocationsizes)); + memorymonitor_allocationsize_obj_t *as = MP_OBJ_TO_PTR(MP_STATE_VM(active_allocationsizes)); size_t power_of_two = 0; block_count >>= 1; while (block_count != 0) { diff --git a/shared-module/memorymonitor/AllocationSize.h b/shared-module/memorymonitor/AllocationSize.h index 3baab2213e..3af1a1a3a1 100644 --- a/shared-module/memorymonitor/AllocationSize.h +++ b/shared-module/memorymonitor/AllocationSize.h @@ -40,8 +40,8 @@ typedef struct _memorymonitor_allocationsize_obj_t { mp_obj_base_t base; uint16_t buckets[ALLOCATION_SIZE_BUCKETS]; // Store the location that points to us so we can remove ourselves. - memorymonitor_allocationsize_obj_t** previous; - memorymonitor_allocationsize_obj_t* next; + memorymonitor_allocationsize_obj_t **previous; + memorymonitor_allocationsize_obj_t *next; bool paused; } memorymonitor_allocationsize_obj_t; diff --git a/shared-module/msgpack/__init__.c b/shared-module/msgpack/__init__.c index 1030031749..61547fde3a 100644 --- a/shared-module/msgpack/__init__.c +++ b/shared-module/msgpack/__init__.c @@ -59,7 +59,9 @@ STATIC msgpack_stream_t get_stream(mp_obj_t stream_obj, int flags) { // readers STATIC void read(msgpack_stream_t *s, void *buf, mp_uint_t size) { - if (size == 0) return; + if (size == 0) { + return; + } mp_uint_t ret = s->read(s->stream_obj, buf, size, &s->errcode); if (s->errcode != 0) { mp_raise_OSError(s->errcode); @@ -82,7 +84,9 @@ STATIC uint16_t read2(msgpack_stream_t *s) { uint16_t res = 0; read(s, &res, 2); int n = 1; - if (*(char *)&n == 1) res = __builtin_bswap16(res); + if (*(char *)&n == 1) { + res = __builtin_bswap16(res); + } return res; } @@ -90,16 +94,24 @@ STATIC uint32_t read4(msgpack_stream_t *s) { uint32_t res = 0; read(s, &res, 4); int n = 1; - if (*(char *)&n == 1) res = __builtin_bswap32(res); + if (*(char *)&n == 1) { + res = __builtin_bswap32(res); + } return res; } STATIC size_t read_size(msgpack_stream_t *s, uint8_t len_index) { size_t res = 0; switch (len_index) { - case 0: res = (size_t)read1(s); break; - case 1: res = (size_t)read2(s); break; - case 2: res = (size_t)read4(s); break; + case 0: + res = (size_t)read1(s); + break; + case 1: + res = (size_t)read2(s); + break; + case 2: + res = (size_t)read4(s); + break; } return res; } @@ -123,13 +135,17 @@ STATIC void write1(msgpack_stream_t *s, uint8_t obj) { STATIC void write2(msgpack_stream_t *s, uint16_t obj) { int n = 1; - if (*(char *)&n == 1) obj = __builtin_bswap16(obj); + if (*(char *)&n == 1) { + obj = __builtin_bswap16(obj); + } write(s, &obj, 2); } STATIC void write4(msgpack_stream_t *s, uint32_t obj) { int n = 1; - if (*(char *)&n == 1) obj = __builtin_bswap32(obj); + if (*(char *)&n == 1) { + obj = __builtin_bswap32(obj); + } write(s, &obj, 4); } @@ -139,10 +155,10 @@ STATIC void write_size(msgpack_stream_t *s, uint8_t code, size_t size) { write1(s, code); write1(s, size); } else if ((uint16_t)size == size) { - write1(s, code+1); + write1(s, code + 1); write2(s, size); } else { - write1(s, code+2); + write1(s, code + 2); write4(s, size); } } @@ -182,12 +198,14 @@ STATIC void pack_int(msgpack_stream_t *s, int32_t x) { } } -STATIC void pack_bin(msgpack_stream_t *s, const uint8_t* data, size_t len) { +STATIC void pack_bin(msgpack_stream_t *s, const uint8_t *data, size_t len) { write_size(s, 0xc4, len); - if (len > 0) write(s, data, len); + if (len > 0) { + write(s, data, len); + } } -STATIC void pack_ext(msgpack_stream_t *s, int8_t code, const uint8_t* data, size_t len) { +STATIC void pack_ext(msgpack_stream_t *s, int8_t code, const uint8_t *data, size_t len) { if (len == 1) { write1(s, 0xd4); } else if (len == 2) { @@ -202,16 +220,20 @@ STATIC void pack_ext(msgpack_stream_t *s, int8_t code, const uint8_t* data, siz write_size(s, 0xc7, len); } write1(s, code); // type byte - if (len > 0) write(s, data, len); + if (len > 0) { + write(s, data, len); + } } -STATIC void pack_str(msgpack_stream_t *s, const char* str, size_t len) { +STATIC void pack_str(msgpack_stream_t *s, const char *str, size_t len) { if (len < 32) { write1(s, 0b10100000 | (uint8_t)len); } else { write_size(s, 0xd9, len); } - if (len > 0) write(s, str, len); + if (len > 0) { + write(s, str, len); + } } STATIC void pack_array(msgpack_stream_t *s, size_t len) { @@ -259,14 +281,14 @@ STATIC void pack(mp_obj_t obj, msgpack_stream_t *s, mp_obj_t default_handler) { // tuple mp_obj_tuple_t *self = MP_OBJ_TO_PTR(obj); pack_array(s, self->len); - for (size_t i=0; ilen; i++) { + for (size_t i = 0; i < self->len; i++) { pack(self->items[i], s, default_handler); } } else if (MP_OBJ_IS_TYPE(obj, &mp_type_list)) { // list (layout differs from tuple) mp_obj_list_t *self = MP_OBJ_TO_PTR(obj); pack_array(s, self->len); - for (size_t i=0; ilen; i++) { + for (size_t i = 0; i < self->len; i++) { pack(self->items[i], s, default_handler); } } else if (MP_OBJ_IS_TYPE(obj, &mp_type_dict)) { @@ -280,7 +302,9 @@ STATIC void pack(mp_obj_t obj, msgpack_stream_t *s, mp_obj_t default_handler) { pack(next->value, s, default_handler); } } else if (mp_obj_is_float(obj)) { - union Float { mp_float_t f; uint32_t u; }; + union Float { mp_float_t f; + uint32_t u; + }; union Float data; data.f = mp_obj_float_get(obj); write1(s, 0xca); @@ -314,13 +338,13 @@ STATIC mp_obj_t unpack(msgpack_stream_t *s, mp_obj_t ext_hook, bool use_list); STATIC mp_obj_t unpack_array_elements(msgpack_stream_t *s, size_t size, mp_obj_t ext_hook, bool use_list) { if (use_list) { mp_obj_list_t *t = MP_OBJ_TO_PTR(mp_obj_new_list(size, NULL)); - for (size_t i=0; iitems[i] = unpack(s, ext_hook, use_list); } return MP_OBJ_FROM_PTR(t); } else { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(size, NULL)); - for (size_t i=0; iitems[i] = unpack(s, ext_hook, use_list); } return MP_OBJ_FROM_PTR(t); @@ -330,7 +354,7 @@ STATIC mp_obj_t unpack_array_elements(msgpack_stream_t *s, size_t size, mp_obj_t STATIC mp_obj_t unpack_bytes(msgpack_stream_t *s, size_t size) { vstr_t vstr; vstr_init_len(&vstr, size); - byte *p = (byte*)vstr.buf; + byte *p = (byte *)vstr.buf; // read in chunks: (some drivers - e.g. UART) limit the // maximum number of bytes that can be read at once // read(s, p, size); @@ -379,20 +403,23 @@ STATIC mp_obj_t unpack(msgpack_stream_t *s, mp_obj_t ext_hook, bool use_list) { // map (dict) size_t len = code & 0b1111; mp_obj_dict_t *d = MP_OBJ_TO_PTR(mp_obj_new_dict(len)); - for (size_t i=0; ideinit != NULL) nic_type->deinit(nic); + mod_network_nic_type_t *nic_type = (mod_network_nic_type_t *)mp_obj_get_type(nic); + if (nic_type->deinit != NULL) { + nic_type->deinit(nic); + } } mp_obj_list_set_len(&MP_STATE_PORT(mod_network_nic_list), 0); } @@ -56,13 +58,17 @@ void network_module_deinit(void) { void network_module_background(void) { static uint32_t next_tick = 0; uint32_t this_tick = supervisor_ticks_ms32(); - if (this_tick < next_tick) return; + if (this_tick < next_tick) { + return; + } next_tick = this_tick + 1000; for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) { mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i]; - mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic); - if (nic_type->timer_tick != NULL) nic_type->timer_tick(nic); + mod_network_nic_type_t *nic_type = (mod_network_nic_type_t *)mp_obj_get_type(nic); + if (nic_type->timer_tick != NULL) { + nic_type->timer_tick(nic); + } } } @@ -82,7 +88,7 @@ mp_obj_t network_module_find_nic(const uint8_t *ip) { for (mp_uint_t i = 0; i < MP_STATE_PORT(mod_network_nic_list).len; i++) { mp_obj_t nic = MP_STATE_PORT(mod_network_nic_list).items[i]; // TODO check IP suitability here - //mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic); + // mod_network_nic_type_t *nic_type = (mod_network_nic_type_t*)mp_obj_get_type(nic); return nic; } diff --git a/shared-module/os/__init__.c b/shared-module/os/__init__.c index 159b54e315..89c7952671 100644 --- a/shared-module/os/__init__.c +++ b/shared-module/os/__init__.c @@ -40,19 +40,19 @@ // as needed. It does not provide uname. // Version of mp_vfs_lookup_path that takes and returns uPy string objects. -STATIC mp_vfs_mount_t *lookup_path(const char* path, mp_obj_t *path_out) { +STATIC mp_vfs_mount_t *lookup_path(const char *path, mp_obj_t *path_out) { const char *p_out; *path_out = mp_const_none; mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &p_out); if (vfs != MP_VFS_NONE && vfs != MP_VFS_ROOT) { *path_out = mp_obj_new_str_of_type(&mp_type_str, - (const byte*)p_out, strlen(p_out)); + (const byte *)p_out, strlen(p_out)); } return vfs; } // Strip off trailing slashes to please underlying libraries -STATIC mp_vfs_mount_t *lookup_dir_path(const char* path, mp_obj_t *path_out) { +STATIC mp_vfs_mount_t *lookup_dir_path(const char *path, mp_obj_t *path_out) { const char *p_out; *path_out = mp_const_none; mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &p_out); @@ -61,7 +61,7 @@ STATIC mp_vfs_mount_t *lookup_dir_path(const char* path, mp_obj_t *path_out) { while (len > 1 && p_out[len - 1] == '/') { len--; } - *path_out = mp_obj_new_str_of_type(&mp_type_str, (const byte*)p_out, len); + *path_out = mp_obj_new_str_of_type(&mp_type_str, (const byte *)p_out, len); } return vfs; } @@ -83,7 +83,7 @@ STATIC mp_obj_t mp_vfs_proxy_call(mp_vfs_mount_t *vfs, qstr meth_name, size_t n_ return mp_call_method_n_kw(n_args, 0, meth); } -void common_hal_os_chdir(const char* path) { +void common_hal_os_chdir(const char *path) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_dir_path(path, &path_out); MP_STATE_VM(vfs_cur) = vfs; @@ -107,7 +107,7 @@ mp_obj_t common_hal_os_getcwd(void) { return mp_vfs_getcwd(); } -mp_obj_t common_hal_os_listdir(const char* path) { +mp_obj_t common_hal_os_listdir(const char *path) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_dir_path(path, &path_out); @@ -135,7 +135,7 @@ mp_obj_t common_hal_os_listdir(const char* path) { return dir_list; } -void common_hal_os_mkdir(const char* path) { +void common_hal_os_mkdir(const char *path) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_dir_path(path, &path_out); if (vfs == MP_VFS_ROOT || (vfs != MP_VFS_NONE && !strcmp(mp_obj_str_get_str(path_out), "/"))) { @@ -144,13 +144,13 @@ void common_hal_os_mkdir(const char* path) { mp_vfs_proxy_call(vfs, MP_QSTR_mkdir, 1, &path_out); } -void common_hal_os_remove(const char* path) { +void common_hal_os_remove(const char *path) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path, &path_out); mp_vfs_proxy_call(vfs, MP_QSTR_remove, 1, &path_out); } -void common_hal_os_rename(const char* old_path, const char* new_path) { +void common_hal_os_rename(const char *old_path, const char *new_path) { mp_obj_t args[2]; mp_vfs_mount_t *old_vfs = lookup_path(old_path, &args[0]); mp_vfs_mount_t *new_vfs = lookup_path(new_path, &args[1]); @@ -161,13 +161,13 @@ void common_hal_os_rename(const char* old_path, const char* new_path) { mp_vfs_proxy_call(old_vfs, MP_QSTR_rename, 2, args); } -void common_hal_os_rmdir(const char* path) { +void common_hal_os_rmdir(const char *path) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_dir_path(path, &path_out); mp_vfs_proxy_call(vfs, MP_QSTR_rmdir, 1, &path_out); } -mp_obj_t common_hal_os_stat(const char* path) { +mp_obj_t common_hal_os_stat(const char *path) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path, &path_out); if (vfs == MP_VFS_ROOT) { @@ -181,7 +181,7 @@ mp_obj_t common_hal_os_stat(const char* path) { return mp_vfs_proxy_call(vfs, MP_QSTR_stat, 1, &path_out); } -mp_obj_t common_hal_os_statvfs(const char* path) { +mp_obj_t common_hal_os_statvfs(const char *path) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path, &path_out); if (vfs == MP_VFS_ROOT) { diff --git a/shared-module/random/__init__.c b/shared-module/random/__init__.c index 42499bc0a1..95ac3bc659 100644 --- a/shared-module/random/__init__.c +++ b/shared-module/random/__init__.c @@ -40,20 +40,19 @@ STATIC uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233; STATIC uint8_t yasmarang_dat = 0; -STATIC uint32_t yasmarang(void) -{ +STATIC uint32_t yasmarang(void) { if (yasmarang_pad == 0xeda4baba) { if (!common_hal_os_urandom((uint8_t *)&yasmarang_pad, sizeof(uint32_t))) { yasmarang_pad = common_hal_time_monotonic_ms() & 0xffffffff; } } - yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n; - yasmarang_pad = (yasmarang_pad<<3) + (yasmarang_pad>>29); - yasmarang_n = yasmarang_pad | 2; - yasmarang_d ^= (yasmarang_pad<<31) + (yasmarang_pad>>1); - yasmarang_dat ^= (char) yasmarang_pad ^ (yasmarang_d>>8) ^ 1; + yasmarang_pad += yasmarang_dat + yasmarang_d * yasmarang_n; + yasmarang_pad = (yasmarang_pad << 3) + (yasmarang_pad >> 29); + yasmarang_n = yasmarang_pad | 2; + yasmarang_d ^= (yasmarang_pad << 31) + (yasmarang_pad >> 1); + yasmarang_dat ^= (char)yasmarang_pad ^ (yasmarang_d >> 8) ^ 1; - return (yasmarang_pad^(yasmarang_d<<5)^(yasmarang_pad>>18)^(yasmarang_dat<<1)); + return yasmarang_pad ^ (yasmarang_d << 5) ^ (yasmarang_pad >> 18) ^ (yasmarang_dat << 1); } /* yasmarang */ // End of Yasmarang @@ -106,9 +105,11 @@ STATIC mp_float_t yasmarang_float(void) { union { mp_float_t f; #if MP_ENDIANNESS_LITTLE - struct { mp_float_int_t frc:MP_FLOAT_FRAC_BITS, exp:MP_FLOAT_EXP_BITS, sgn:1; } p; + struct { mp_float_int_t frc : MP_FLOAT_FRAC_BITS, exp : MP_FLOAT_EXP_BITS, sgn : 1; + } p; #else - struct { mp_float_int_t sgn:1, exp:MP_FLOAT_EXP_BITS, frc:MP_FLOAT_FRAC_BITS; } p; + struct { mp_float_int_t sgn : 1, exp : MP_FLOAT_EXP_BITS, frc : MP_FLOAT_FRAC_BITS; + } p; #endif } u; u.p.sgn = 0; diff --git a/shared-module/rgbmatrix/RGBMatrix.c b/shared-module/rgbmatrix/RGBMatrix.c index a688d7fd6f..a0dc783b55 100644 --- a/shared-module/rgbmatrix/RGBMatrix.c +++ b/shared-module/rgbmatrix/RGBMatrix.c @@ -67,7 +67,7 @@ void common_hal_rgbmatrix_rgbmatrix_construct(rgbmatrix_rgbmatrix_obj_t *self, i common_hal_rgbmatrix_rgbmatrix_reconstruct(self, framebuffer); } -void common_hal_rgbmatrix_rgbmatrix_reconstruct(rgbmatrix_rgbmatrix_obj_t* self, mp_obj_t framebuffer) { +void common_hal_rgbmatrix_rgbmatrix_reconstruct(rgbmatrix_rgbmatrix_obj_t *self, mp_obj_t framebuffer) { self->paused = 1; common_hal_rgbmatrix_timer_disable(self->timer); @@ -80,7 +80,7 @@ void common_hal_rgbmatrix_rgbmatrix_reconstruct(rgbmatrix_rgbmatrix_obj_t* self, self->bufinfo.typecode = 'H'; } // verify that the matrix is big enough - mp_get_index(mp_obj_get_type(self->framebuffer), self->bufinfo.len, MP_OBJ_NEW_SMALL_INT(self->bufsize-1), false); + mp_get_index(mp_obj_get_type(self->framebuffer), self->bufinfo.len, MP_OBJ_NEW_SMALL_INT(self->bufsize - 1), false); } else { common_hal_rgbmatrix_free_impl(self->bufinfo.buf); common_hal_rgbmatrix_free_impl(self->protomatter.rgbPins); @@ -96,7 +96,7 @@ void common_hal_rgbmatrix_rgbmatrix_reconstruct(rgbmatrix_rgbmatrix_obj_t* self, memset(&self->protomatter, 0, sizeof(self->protomatter)); ProtomatterStatus stat = _PM_init(&self->protomatter, self->width, self->bit_depth, - self->rgb_count/6, self->rgb_pins, + self->rgb_count / 6, self->rgb_pins, self->addr_count, self->addr_pins, self->clock_pin, self->latch_pin, self->oe_pin, self->doublebuffer, self->serpentine ? -self->tile : self->tile, @@ -120,19 +120,19 @@ void common_hal_rgbmatrix_rgbmatrix_reconstruct(rgbmatrix_rgbmatrix_obj_t* self, if (stat != PROTOMATTER_OK) { common_hal_rgbmatrix_rgbmatrix_deinit(self); switch (stat) { - case PROTOMATTER_ERR_PINS: - mp_raise_ValueError(translate("Invalid pin")); - break; - case PROTOMATTER_ERR_ARG: - mp_raise_ValueError(translate("Invalid argument")); - break; - case PROTOMATTER_ERR_MALLOC: - mp_raise_msg(&mp_type_MemoryError, NULL); - break; - default: - mp_raise_msg_varg(&mp_type_RuntimeError, - translate("Internal error #%d"), (int)stat); - break; + case PROTOMATTER_ERR_PINS: + mp_raise_ValueError(translate("Invalid pin")); + break; + case PROTOMATTER_ERR_ARG: + mp_raise_ValueError(translate("Invalid argument")); + break; + case PROTOMATTER_ERR_MALLOC: + mp_raise_msg(&mp_type_MemoryError, NULL); + break; + default: + mp_raise_msg_varg(&mp_type_RuntimeError, + translate("Internal error #%d"), (int)stat); + break; } } @@ -147,12 +147,12 @@ STATIC void free_pin(uint8_t *pin) { } STATIC void free_pin_seq(uint8_t *seq, int count) { - for (int i=0; itimer) { common_hal_rgbmatrix_timer_free(self->timer); self->timer = 0; @@ -183,11 +183,11 @@ void common_hal_rgbmatrix_rgbmatrix_deinit(rgbmatrix_rgbmatrix_obj_t* self) { self->framebuffer = NULL; } -void rgbmatrix_rgbmatrix_collect_ptrs(rgbmatrix_rgbmatrix_obj_t* self) { +void rgbmatrix_rgbmatrix_collect_ptrs(rgbmatrix_rgbmatrix_obj_t *self) { gc_collect_ptr(self->framebuffer); } -void common_hal_rgbmatrix_rgbmatrix_set_paused(rgbmatrix_rgbmatrix_obj_t* self, bool paused) { +void common_hal_rgbmatrix_rgbmatrix_set_paused(rgbmatrix_rgbmatrix_obj_t *self, bool paused) { if (paused && !self->paused) { _PM_stop(&self->protomatter); } else if (!paused && self->paused) { @@ -198,22 +198,22 @@ void common_hal_rgbmatrix_rgbmatrix_set_paused(rgbmatrix_rgbmatrix_obj_t* self, self->paused = paused; } -bool common_hal_rgbmatrix_rgbmatrix_get_paused(rgbmatrix_rgbmatrix_obj_t* self) { +bool common_hal_rgbmatrix_rgbmatrix_get_paused(rgbmatrix_rgbmatrix_obj_t *self) { return self->paused; } -void common_hal_rgbmatrix_rgbmatrix_refresh(rgbmatrix_rgbmatrix_obj_t* self) { +void common_hal_rgbmatrix_rgbmatrix_refresh(rgbmatrix_rgbmatrix_obj_t *self) { if (!self->paused) { _PM_convert_565(&self->protomatter, self->bufinfo.buf, self->width); _PM_swapbuffer_maybe(&self->protomatter); } } -int common_hal_rgbmatrix_rgbmatrix_get_width(rgbmatrix_rgbmatrix_obj_t* self) { +int common_hal_rgbmatrix_rgbmatrix_get_width(rgbmatrix_rgbmatrix_obj_t *self) { return self->width; } -int common_hal_rgbmatrix_rgbmatrix_get_height(rgbmatrix_rgbmatrix_obj_t* self) { +int common_hal_rgbmatrix_rgbmatrix_get_height(rgbmatrix_rgbmatrix_obj_t *self) { int computed_height = (self->rgb_count / 3) * (1 << (self->addr_count)) * self->tile; return computed_height; } diff --git a/shared-module/rgbmatrix/allocator.h b/shared-module/rgbmatrix/allocator.h index 3431046d5b..5c11ad52a7 100644 --- a/shared-module/rgbmatrix/allocator.h +++ b/shared-module/rgbmatrix/allocator.h @@ -32,6 +32,6 @@ #include "supervisor/memory.h" #define _PM_allocate common_hal_rgbmatrix_allocator_impl -#define _PM_free(x) (common_hal_rgbmatrix_free_impl((x)), (x)=NULL, (void)0) +#define _PM_free(x) (common_hal_rgbmatrix_free_impl((x)), (x) = NULL, (void)0) extern void *common_hal_rgbmatrix_allocator_impl(size_t sz); extern void common_hal_rgbmatrix_free_impl(void *); diff --git a/shared-module/sdcardio/SDCard.c b/shared-module/sdcardio/SDCard.c index 1712f58ee4..c3263fa0dc 100644 --- a/shared-module/sdcardio/SDCard.c +++ b/shared-module/sdcardio/SDCard.c @@ -35,15 +35,15 @@ #include "py/mperrno.h" #if 0 -#define DEBUG_PRINT(...) ((void)mp_printf(&mp_plat_print, ## __VA_ARGS__)) +#define DEBUG_PRINT(...) ((void)mp_printf(&mp_plat_print,##__VA_ARGS__)) #else #define DEBUG_PRINT(...) ((void)0) #endif #define CMD_TIMEOUT (200) -#define R1_IDLE_STATE (1<<0) -#define R1_ILLEGAL_COMMAND (1<<2) +#define R1_IDLE_STATE (1 << 0) +#define R1_ILLEGAL_COMMAND (1 << 2) #define TOKEN_CMD25 (0xFC) #define TOKEN_STOP_TRAN (0xFD) @@ -67,7 +67,7 @@ STATIC void lock_bus_or_throw(sdcardio_sdcard_obj_t *self) { STATIC void clock_card(sdcardio_sdcard_obj_t *self, int bytes) { uint8_t buf[] = {0xff}; common_hal_digitalio_digitalinout_set_value(&self->cs, true); - for (int i=0; ibus, buf, 1); } } @@ -77,7 +77,7 @@ STATIC void extraclock_and_unlock_bus(sdcardio_sdcard_obj_t *self) { common_hal_busio_spi_unlock(self->bus); } -static uint8_t CRC7(const uint8_t* data, uint8_t n) { +static uint8_t CRC7(const uint8_t *data, uint8_t n) { uint8_t crc = 0; for (uint8_t i = 0; i < n; i++) { uint8_t d = data[i]; @@ -123,7 +123,7 @@ STATIC int cmd(sdcardio_sdcard_obj_t *self, int cmd, int arg, void *response_buf // Wait for the response (response[7] == 0) bool response_received = false; - for (int i=0; ibus, cmdbuf, 1, 0xff); if ((cmdbuf[0] & 0x80) == 0) { response_received = true; @@ -141,7 +141,7 @@ STATIC int cmd(sdcardio_sdcard_obj_t *self, int cmd, int arg, void *response_buf cmdbuf[1] = 0xff; do { // Wait for the start block byte - common_hal_busio_spi_read(self->bus, cmdbuf+1, 1, 0xff); + common_hal_busio_spi_read(self->bus, cmdbuf + 1, 1, 0xff); } while (cmdbuf[1] != 0xfe); } @@ -149,7 +149,7 @@ STATIC int cmd(sdcardio_sdcard_obj_t *self, int cmd, int arg, void *response_buf if (data_block) { // Read and discard the CRC-CCITT checksum - common_hal_busio_spi_read(self->bus, cmdbuf+1, 2, 0xff); + common_hal_busio_spi_read(self->bus, cmdbuf + 1, 2, 0xff); } } @@ -161,13 +161,13 @@ STATIC int block_cmd(sdcardio_sdcard_obj_t *self, int cmd_, int block, void *res return cmd(self, cmd_, block * self->cdv, response_buf, response_len, true, true); } -STATIC bool cmd_nodata(sdcardio_sdcard_obj_t* self, int cmd, int response) { +STATIC bool cmd_nodata(sdcardio_sdcard_obj_t *self, int cmd, int response) { uint8_t cmdbuf[2] = {cmd, 0xff}; common_hal_busio_spi_write(self->bus, cmdbuf, sizeof(cmdbuf)); // Wait for the response (response[7] == response) - for (int i=0; ibus, cmdbuf, 1, 0xff); if (cmdbuf[0] == response) { return 0; @@ -177,7 +177,7 @@ STATIC bool cmd_nodata(sdcardio_sdcard_obj_t* self, int cmd, int response) { } STATIC const compressed_string_t *init_card_v1(sdcardio_sdcard_obj_t *self) { - for (int i=0; ibus, cmd, 1, 0xff); DEBUG_PRINT("i=%02d cmd[0] = 0x%02x\n", i, cmd[0]); if ((cmd[0] & 0b00010001) == 0b00000001) { diff --git a/shared-module/sharpdisplay/SharpMemoryFramebuffer.c b/shared-module/sharpdisplay/SharpMemoryFramebuffer.c index 4b92bd637a..14f4908222 100644 --- a/shared-module/sharpdisplay/SharpMemoryFramebuffer.c +++ b/shared-module/sharpdisplay/SharpMemoryFramebuffer.c @@ -40,7 +40,8 @@ STATIC uint8_t bitrev(uint8_t n) { uint8_t r = 0; - for(int i=0;i<8;i++) r |= ((n>>i) & 1)<<(7-i); + for (int i = 0; i < 8; i++) {r |= ((n >> i) & 1) << (7 - i); + } return r; } @@ -70,10 +71,10 @@ bool common_hal_sharpdisplay_framebuffer_get_pixels_in_byte_share_row(sharpdispl void common_hal_sharpdisplay_framebuffer_reset(sharpdisplay_framebuffer_obj_t *self) { if (self->bus != &self->inline_bus -#if BOARD_SPI + #if BOARD_SPI && self->bus != common_hal_board_get_spi() -#endif - ) { + #endif + ) { memcpy(&self->inline_bus, self->bus, sizeof(busio_spi_obj_t)); self->bus = &self->inline_bus; } @@ -81,7 +82,7 @@ void common_hal_sharpdisplay_framebuffer_reset(sharpdisplay_framebuffer_obj_t *s void common_hal_sharpdisplay_framebuffer_reconstruct(sharpdisplay_framebuffer_obj_t *self) { // Look up the allocation by the old pointer and get the new pointer from it. - supervisor_allocation* alloc = allocation_from_ptr(self->bufinfo.buf); + supervisor_allocation *alloc = allocation_from_ptr(self->bufinfo.buf); self->bufinfo.buf = alloc ? alloc->ptr : NULL; } @@ -90,7 +91,7 @@ void common_hal_sharpdisplay_framebuffer_get_bufinfo(sharpdisplay_framebuffer_ob int row_stride = common_hal_sharpdisplay_framebuffer_get_row_stride(self); int height = common_hal_sharpdisplay_framebuffer_get_height(self); self->bufinfo.len = row_stride * height + 2; - supervisor_allocation* alloc = allocate_memory(align32_size(self->bufinfo.len), false, true); + supervisor_allocation *alloc = allocate_memory(align32_size(self->bufinfo.len), false, true); if (alloc == NULL) { m_malloc_fail(self->bufinfo.len); } @@ -100,8 +101,8 @@ void common_hal_sharpdisplay_framebuffer_get_bufinfo(sharpdisplay_framebuffer_ob uint8_t *data = self->bufinfo.buf; *data++ = SHARPMEM_BIT_WRITECMD_LSB; - for(int y=0; yfull_refresh = true; @@ -160,8 +161,8 @@ void common_hal_sharpdisplay_framebuffer_swapbuffers(sharpdisplay_framebuffer_ob // output each changed row size_t row_stride = common_hal_sharpdisplay_framebuffer_get_row_stride(self); - for(int y=0; yheight; y++) { - if(self->full_refresh || (dirty_row_bitmask[y/8] & (1 << (y & 7)))) { + for (int y = 0; y < self->height; y++) { + if (self->full_refresh || (dirty_row_bitmask[y / 8] & (1 << (y & 7)))) { common_hal_busio_spi_write(self->bus, data, row_stride); } data += row_stride; diff --git a/shared-module/sharpdisplay/SharpMemoryFramebuffer.h b/shared-module/sharpdisplay/SharpMemoryFramebuffer.h index 08966a89c1..47e1a373fd 100644 --- a/shared-module/sharpdisplay/SharpMemoryFramebuffer.h +++ b/shared-module/sharpdisplay/SharpMemoryFramebuffer.h @@ -33,7 +33,7 @@ typedef struct { mp_obj_base_t base; - busio_spi_obj_t* bus; + busio_spi_obj_t *bus; busio_spi_obj_t inline_bus; digitalio_digitalinout_obj_t chip_select; mp_buffer_info_t bufinfo; @@ -41,7 +41,7 @@ typedef struct { uint16_t width, height; uint32_t baudrate; - bool full_refresh:1; + bool full_refresh : 1; } sharpdisplay_framebuffer_obj_t; void common_hal_sharpdisplay_framebuffer_construct(sharpdisplay_framebuffer_obj_t *self, busio_spi_obj_t *spi, mcu_pin_obj_t *chip_select, int baudrate, int width, int height); @@ -56,4 +56,4 @@ void common_hal_sharpdisplay_framebuffer_reconstruct(sharpdisplay_framebuffer_ob extern const framebuffer_p_t sharpdisplay_framebuffer_proto; -void common_hal_sharpdisplay_framebuffer_collect_ptrs(sharpdisplay_framebuffer_obj_t*); +void common_hal_sharpdisplay_framebuffer_collect_ptrs(sharpdisplay_framebuffer_obj_t *); diff --git a/shared-module/storage/__init__.c b/shared-module/storage/__init__.c index 5864307fd5..db994158d6 100644 --- a/shared-module/storage/__init__.c +++ b/shared-module/storage/__init__.c @@ -57,7 +57,7 @@ STATIC mp_obj_t mp_vfs_proxy_call(mp_vfs_mount_t *vfs, qstr meth_name, size_t n_ return mp_call_method_n_kw(n_args, 0, meth); } -void common_hal_storage_mount(mp_obj_t vfs_obj, const char* mount_path, bool readonly) { +void common_hal_storage_mount(mp_obj_t vfs_obj, const char *mount_path, bool readonly) { // create new object mp_vfs_mount_t *vfs = m_new_obj(mp_vfs_mount_t); vfs->str = mount_path; @@ -94,7 +94,7 @@ void common_hal_storage_mount(mp_obj_t vfs_obj, const char* mount_path, bool rea } // call the underlying object to do any mounting operation - mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t*)&args); + mp_vfs_proxy_call(vfs, MP_QSTR_mount, 2, (mp_obj_t *)&args); // Insert the vfs into the mount table by pushing it onto the front of the // mount table. @@ -127,7 +127,7 @@ void common_hal_storage_umount_object(mp_obj_t vfs_obj) { mp_vfs_proxy_call(vfs, MP_QSTR_umount, 0, NULL); } -STATIC mp_obj_t storage_object_from_path(const char* mount_path) { +STATIC mp_obj_t storage_object_from_path(const char *mount_path) { for (mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table); *vfsp != NULL; vfsp = &(*vfsp)->next) { if (strcmp(mount_path, (*vfsp)->str) == 0) { return (*vfsp)->obj; @@ -136,7 +136,7 @@ STATIC mp_obj_t storage_object_from_path(const char* mount_path) { mp_raise_OSError(MP_EINVAL); } -void common_hal_storage_umount_path(const char* mount_path) { +void common_hal_storage_umount_path(const char *mount_path) { common_hal_storage_umount_object(storage_object_from_path(mount_path)); } diff --git a/shared-module/struct/__init__.c b/shared-module/struct/__init__.c index 245dbbda97..7a7ea845e7 100644 --- a/shared-module/struct/__init__.c +++ b/shared-module/struct/__init__.c @@ -34,11 +34,11 @@ #include "supervisor/shared/translate.h" void struct_validate_format(char fmt) { -#if MICROPY_NONSTANDARD_TYPECODES - if( fmt == 'S' || fmt == 'O') { + #if MICROPY_NONSTANDARD_TYPECODES + if (fmt == 'S' || fmt == 'O') { mp_raise_RuntimeError(translate("'S' and 'O' are not supported format types")); } -#endif + #endif } char get_fmt_type(const char **fmt) { @@ -119,7 +119,7 @@ mp_uint_t shared_modules_struct_calcsize(mp_obj_t fmt_in) { return size; } -void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte* end_p, size_t n_args, const mp_obj_t *args) { +void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte *end_p, size_t n_args, const mp_obj_t *args) { const char *fmt = mp_obj_str_get_str(fmt_in); char fmt_type = get_fmt_type(&fmt); const mp_uint_t total_sz = shared_modules_struct_calcsize(fmt_in); @@ -164,50 +164,50 @@ void shared_modules_struct_pack_into(mp_obj_t fmt_in, byte *p, byte* end_p, size } } -mp_obj_tuple_t * shared_modules_struct_unpack_from(mp_obj_t fmt_in, byte *p, byte *end_p, bool exact_size) { +mp_obj_tuple_t *shared_modules_struct_unpack_from(mp_obj_t fmt_in, byte *p, byte *end_p, bool exact_size) { - const char *fmt = mp_obj_str_get_str(fmt_in); - char fmt_type = get_fmt_type(&fmt); - const mp_uint_t num_items = calcsize_items(fmt); - const mp_uint_t total_sz = shared_modules_struct_calcsize(fmt_in); - mp_obj_tuple_t *res = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_items, NULL)); + const char *fmt = mp_obj_str_get_str(fmt_in); + char fmt_type = get_fmt_type(&fmt); + const mp_uint_t num_items = calcsize_items(fmt); + const mp_uint_t total_sz = shared_modules_struct_calcsize(fmt_in); + mp_obj_tuple_t *res = MP_OBJ_TO_PTR(mp_obj_new_tuple(num_items, NULL)); - // If exact_size, make sure the buffer is exactly the right size. - // Otherwise just make sure it's big enough. - if (exact_size) { - if (p + total_sz != end_p) { - mp_raise_RuntimeError(translate("buffer size must match format")); - } - } else { - if (p + total_sz > end_p) { - mp_raise_RuntimeError(translate("buffer too small")); - } - } + // If exact_size, make sure the buffer is exactly the right size. + // Otherwise just make sure it's big enough. + if (exact_size) { + if (p + total_sz != end_p) { + mp_raise_RuntimeError(translate("buffer size must match format")); + } + } else { + if (p + total_sz > end_p) { + mp_raise_RuntimeError(translate("buffer too small")); + } + } - for (uint i = 0; i < num_items;) { - mp_uint_t sz = 1; + for (uint i = 0; i < num_items;) { + mp_uint_t sz = 1; - struct_validate_format(*fmt); + struct_validate_format(*fmt); - if (unichar_isdigit(*fmt)) { - sz = get_fmt_num(&fmt); - } - mp_obj_t item; - if (*fmt == 's') { - item = mp_obj_new_bytes(p, sz); - p += sz; - res->items[i++] = item; - } else { - while (sz--) { - item = mp_binary_get_val(fmt_type, *fmt, &p); - // Pad bytes are not stored. - if (*fmt != 'x') { - res->items[i++] = item; - } - } - } - fmt++; - } - return res; + if (unichar_isdigit(*fmt)) { + sz = get_fmt_num(&fmt); + } + mp_obj_t item; + if (*fmt == 's') { + item = mp_obj_new_bytes(p, sz); + p += sz; + res->items[i++] = item; + } else { + while (sz--) { + item = mp_binary_get_val(fmt_type, *fmt, &p); + // Pad bytes are not stored. + if (*fmt != 'x') { + res->items[i++] = item; + } + } + } + fmt++; + } + return res; } diff --git a/shared-module/terminalio/Terminal.c b/shared-module/terminalio/Terminal.c index df92a5dc48..4589c91498 100644 --- a/shared-module/terminalio/Terminal.c +++ b/shared-module/terminalio/Terminal.c @@ -29,7 +29,7 @@ #include "shared-module/fontio/BuiltinFont.h" #include "shared-bindings/displayio/TileGrid.h" -void common_hal_terminalio_terminal_construct(terminalio_terminal_obj_t *self, displayio_tilegrid_t* tilegrid, const fontio_builtinfont_t* font) { +void common_hal_terminalio_terminal_construct(terminalio_terminal_obj_t *self, displayio_tilegrid_t *tilegrid, const fontio_builtinfont_t *font) { self->cursor_x = 0; self->cursor_y = 0; self->font = font; @@ -46,7 +46,7 @@ void common_hal_terminalio_terminal_construct(terminalio_terminal_obj_t *self, d } size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, const byte *data, size_t len, int *errcode) { - const byte* i = data; + const byte *i = data; uint16_t start_y = self->cursor_y; while (i < data + len) { unichar c = utf8_get_char(i); @@ -61,7 +61,7 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con self->cursor_x = 0; } else if (c == '\n') { self->cursor_y++; - // Commands below are used by MicroPython in the REPL + // Commands below are used by MicroPython in the REPL } else if (c == '\b') { if (self->cursor_x > 0) { self->cursor_x--; diff --git a/shared-module/terminalio/Terminal.h b/shared-module/terminalio/Terminal.h index c31392cc4f..2ba7e21f72 100644 --- a/shared-module/terminalio/Terminal.h +++ b/shared-module/terminalio/Terminal.h @@ -36,10 +36,10 @@ typedef struct { mp_obj_base_t base; - const fontio_builtinfont_t* font; + const fontio_builtinfont_t *font; uint16_t cursor_x; uint16_t cursor_y; - displayio_tilegrid_t* tilegrid; + displayio_tilegrid_t *tilegrid; uint16_t first_row; } terminalio_terminal_obj_t; diff --git a/shared-module/touchio/TouchIn.c b/shared-module/touchio/TouchIn.c index 3fdf3e0ca1..840c14571d 100644 --- a/shared-module/touchio/TouchIn.c +++ b/shared-module/touchio/TouchIn.c @@ -59,15 +59,17 @@ static uint16_t get_raw_reading(touchio_touchin_obj_t *self) { common_hal_digitalio_digitalinout_switch_to_input(self->digitalinout, PULL_NONE); - while(common_hal_digitalio_digitalinout_get_value(self->digitalinout)) { - if (ticks >= TIMEOUT_TICKS) return TIMEOUT_TICKS; + while (common_hal_digitalio_digitalinout_get_value(self->digitalinout)) { + if (ticks >= TIMEOUT_TICKS) { + return TIMEOUT_TICKS; + } ticks++; } } return ticks; } -void common_hal_touchio_touchin_construct(touchio_touchin_obj_t* self, const mcu_pin_obj_t *pin) { +void common_hal_touchio_touchin_construct(touchio_touchin_obj_t *self, const mcu_pin_obj_t *pin) { common_hal_mcu_pin_claim(pin); self->digitalinout = m_new_obj(digitalio_digitalinout_obj_t); self->digitalinout->base.type = &digitalio_digitalinout_type; @@ -81,11 +83,11 @@ void common_hal_touchio_touchin_construct(touchio_touchin_obj_t* self, const mcu self->threshold = raw_reading * 1.05 + 100; } -bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t* self) { +bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t *self) { return self->digitalinout == MP_OBJ_NULL; } -void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t* self) { +void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t *self) { if (common_hal_touchio_touchin_deinited(self)) { return; } @@ -111,6 +113,6 @@ uint16_t common_hal_touchio_touchin_get_threshold(touchio_touchin_obj_t *self) { } void common_hal_touchio_touchin_set_threshold(touchio_touchin_obj_t *self, - uint16_t new_threshold) { + uint16_t new_threshold) { self->threshold = new_threshold; } diff --git a/shared-module/uheap/__init__.c b/shared-module/uheap/__init__.c index 5ef15dce42..fd8e31ec0d 100644 --- a/shared-module/uheap/__init__.c +++ b/shared-module/uheap/__init__.c @@ -40,8 +40,8 @@ #include "shared-bindings/uheap/__init__.h" #define VERIFY_PTR(ptr) ( \ - (void *) ptr >= (void*)MP_STATE_MEM(gc_pool_start) /* must be above start of pool */ \ - && (void *) ptr < (void*)MP_STATE_MEM(gc_pool_end) /* must be below end of pool */ \ + (void *)ptr >= (void *)MP_STATE_MEM(gc_pool_start) /* must be above start of pool */ \ + && (void *)ptr < (void *)MP_STATE_MEM(gc_pool_end) /* must be below end of pool */ \ ) static void indent(uint8_t levels) { @@ -60,17 +60,17 @@ static uint32_t int_size(uint8_t indent_level, mp_obj_t obj) { return 0; } #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_MPZ - mp_obj_int_t* i = MP_OBJ_TO_PTR(obj); - return gc_nbytes(obj) + gc_nbytes(i->mpz.dig); + mp_obj_int_t *i = MP_OBJ_TO_PTR(obj); + return gc_nbytes(obj) + gc_nbytes(i->mpz.dig); #else - return gc_nbytes(obj); + return gc_nbytes(obj); #endif } static uint32_t string_size(uint8_t indent_level, mp_obj_t obj) { if (MP_OBJ_IS_QSTR(obj)) { qstr qs = MP_OBJ_QSTR_VALUE(obj); - const char* s = qstr_str(qs); + const char *s = qstr_str(qs); if (!VERIFY_PTR(s)) { return 0; } @@ -78,7 +78,7 @@ static uint32_t string_size(uint8_t indent_level, mp_obj_t obj) { mp_printf(&mp_plat_print, "%s\n", s); return 0; } else { // MP_OBJ_IS_TYPE(o, &mp_type_str) - mp_obj_str_t* s = MP_OBJ_TO_PTR(obj); + mp_obj_str_t *s = MP_OBJ_TO_PTR(obj); return gc_nbytes(s) + gc_nbytes(s->data); } } @@ -118,8 +118,8 @@ static uint32_t dict_size(uint8_t indent_level, mp_obj_dict_t *dict) { } static uint32_t function_size(uint8_t indent_level, mp_obj_t obj) { - //indent(indent_level); - //mp_print_str(&mp_plat_print, "function\n"); + // indent(indent_level); + // mp_print_str(&mp_plat_print, "function\n"); if (MP_OBJ_IS_TYPE(obj, &mp_type_fun_builtin_0)) { return 0; } else if (MP_OBJ_IS_TYPE(obj, &mp_type_fun_builtin_1)) { @@ -131,7 +131,7 @@ static uint32_t function_size(uint8_t indent_level, mp_obj_t obj) { } else if (MP_OBJ_IS_TYPE(obj, &mp_type_fun_builtin_var)) { return 0; } else if (MP_OBJ_IS_TYPE(obj, &mp_type_fun_bc)) { - mp_obj_fun_bc_t* fn = MP_OBJ_TO_PTR(obj); + mp_obj_fun_bc_t *fn = MP_OBJ_TO_PTR(obj); uint32_t total_size = gc_nbytes(fn) + gc_nbytes(fn->bytecode) + gc_nbytes(fn->const_table); #if MICROPY_DEBUG_PRINTERS mp_printf(&mp_plat_print, "BYTECODE START\n"); @@ -180,7 +180,7 @@ static uint32_t type_size(uint8_t indent_level, mp_obj_type_t *type) { // mp_obj_base_t base; // qstr name; - //total_size += string_size(indent_level, MP_OBJ_TO_PTR(type->name)); + // total_size += string_size(indent_level, MP_OBJ_TO_PTR(type->name)); // mp_print_fun_t print; // mp_make_new_fun_t make_new; // to make an instance of the type // @@ -258,8 +258,8 @@ static uint32_t object_size(uint8_t indent_level, mp_obj_t obj) { return function_size(indent_level, MP_OBJ_TO_PTR(obj)); } if (!VERIFY_PTR(obj)) { - //indent(indent_level); - //mp_printf(&mp_plat_print, "In ROM\n"); + // indent(indent_level); + // mp_printf(&mp_plat_print, "In ROM\n"); return 0; } mp_obj_t type = MP_OBJ_FROM_PTR(mp_obj_get_type(obj)); @@ -274,7 +274,7 @@ static uint32_t object_size(uint8_t indent_level, mp_obj_t obj) { return array_size(indent_level, MP_OBJ_TO_PTR(obj)); } else if (type == &mp_type_memoryview) { return memoryview_size(indent_level, MP_OBJ_TO_PTR(obj)); - } else if (MP_OBJ_IS_OBJ(obj) && VERIFY_PTR(type)) { + } else if (MP_OBJ_IS_OBJ(obj) && VERIFY_PTR(type)) { return instance_size(indent_level, MP_OBJ_TO_PTR(obj)); } diff --git a/shared-module/usb_cdc/__init__.c b/shared-module/usb_cdc/__init__.c index fe05cb1075..3cf80a8b5c 100644 --- a/shared-module/usb_cdc/__init__.c +++ b/shared-module/usb_cdc/__init__.c @@ -42,8 +42,7 @@ static usb_cdc_serial_obj_t serial_objs[CFG_TUD_CDC] = { { .base.type = &usb_cdc_serial_type, .timeout = -1.0f, .write_timeout = -1.0f, - .idx = 0, - }, { + .idx = 0,}, { .base.type = &usb_cdc_serial_type, .timeout = -1.0f, .write_timeout = -1.0f, diff --git a/shared-module/usb_hid/Device.c b/shared-module/usb_hid/Device.c index 2b560c328b..4f392847ff 100644 --- a/shared-module/usb_hid/Device.c +++ b/shared-module/usb_hid/Device.c @@ -41,29 +41,29 @@ uint8_t common_hal_usb_hid_device_get_usage(usb_hid_device_obj_t *self) { return self->usage; } -void common_hal_usb_hid_device_send_report(usb_hid_device_obj_t *self, uint8_t* report, uint8_t len) { +void common_hal_usb_hid_device_send_report(usb_hid_device_obj_t *self, uint8_t *report, uint8_t len) { if (len != self->report_length) { mp_raise_ValueError_varg(translate("Buffer incorrect size. Should be %d bytes."), self->report_length); } // Wait until interface is ready, timeout = 2 seconds uint64_t end_ticks = supervisor_ticks_ms64() + 2000; - while ( (supervisor_ticks_ms64() < end_ticks) && !tud_hid_ready() ) { + while ((supervisor_ticks_ms64() < end_ticks) && !tud_hid_ready()) { RUN_BACKGROUND_TASKS; } - if ( !tud_hid_ready() ) { + if (!tud_hid_ready()) { mp_raise_msg(&mp_type_OSError, translate("USB Busy")); } memcpy(self->report_buffer, report, len); - if ( !tud_hid_report(self->report_id, self->report_buffer, len) ) { + if (!tud_hid_report(self->report_id, self->report_buffer, len)) { mp_raise_msg(&mp_type_OSError, translate("USB Error")); } } -static usb_hid_device_obj_t* get_hid_device(uint8_t report_id) { +static usb_hid_device_obj_t *get_hid_device(uint8_t report_id) { for (uint8_t i = 0; i < USB_HID_NUM_DEVICES; i++) { if (usb_hid_devices[i].report_id == report_id) { return &usb_hid_devices[i]; @@ -73,10 +73,12 @@ static usb_hid_device_obj_t* get_hid_device(uint8_t report_id) { } // Callbacks invoked when receive Get_Report request through control endpoint -uint16_t tud_hid_get_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t report_type, uint8_t* buffer, uint16_t reqlen) { - (void) itf; +uint16_t tud_hid_get_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t report_type, uint8_t *buffer, uint16_t reqlen) { + (void)itf; // only support Input Report - if ( report_type != HID_REPORT_TYPE_INPUT ) return 0; + if (report_type != HID_REPORT_TYPE_INPUT) { + return 0; + } // fill buffer with current report memcpy(buffer, get_hid_device(report_id)->report_buffer, reqlen); @@ -84,8 +86,8 @@ uint16_t tud_hid_get_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t } // Callbacks invoked when receive Set_Report request through control endpoint -void tud_hid_set_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t report_type, uint8_t const* buffer, uint16_t bufsize) { - (void) itf; +void tud_hid_set_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t report_type, uint8_t const *buffer, uint16_t bufsize) { + (void)itf; if (report_type == HID_REPORT_TYPE_INVALID) { report_id = buffer[0]; buffer++; @@ -94,7 +96,7 @@ void tud_hid_set_report_cb(uint8_t itf, uint8_t report_id, hid_report_type_t rep return; } - usb_hid_device_obj_t* hid_device = get_hid_device(report_id); + usb_hid_device_obj_t *hid_device = get_hid_device(report_id); if (hid_device && hid_device->out_report_length >= bufsize) { memcpy(hid_device->out_report_buffer, buffer, bufsize); diff --git a/shared-module/usb_hid/Device.h b/shared-module/usb_hid/Device.h index 93c3518b43..bf4e9d9adb 100644 --- a/shared-module/usb_hid/Device.h +++ b/shared-module/usb_hid/Device.h @@ -33,17 +33,17 @@ #include "py/obj.h" #ifdef __cplusplus - extern "C" { +extern "C" { #endif typedef struct { mp_obj_base_t base; - uint8_t* report_buffer; + uint8_t *report_buffer; uint8_t report_id; uint8_t report_length; uint8_t usage_page; uint8_t usage; - uint8_t* out_report_buffer; + uint8_t *out_report_buffer; uint8_t out_report_length; } usb_hid_device_obj_t; @@ -51,7 +51,7 @@ typedef struct { extern usb_hid_device_obj_t usb_hid_devices[]; #ifdef __cplusplus - } +} #endif #endif /* SHARED_MODULE_USB_HID_DEVICE_H */ diff --git a/shared-module/usb_midi/__init__.c b/shared-module/usb_midi/__init__.c index 3fb3f836cd..0684112b72 100644 --- a/shared-module/usb_midi/__init__.c +++ b/shared-module/usb_midi/__init__.c @@ -36,26 +36,26 @@ #include "supervisor/memory.h" #include "tusb.h" -supervisor_allocation* usb_midi_allocation; +supervisor_allocation *usb_midi_allocation; void usb_midi_init(void) { // TODO(tannewt): Make this dynamic. - size_t tuple_size = align32_size(sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t*) * 2); + size_t tuple_size = align32_size(sizeof(mp_obj_tuple_t) + sizeof(mp_obj_t *) * 2); size_t portin_size = align32_size(sizeof(usb_midi_portin_obj_t)); size_t portout_size = align32_size(sizeof(usb_midi_portout_obj_t)); // For each embedded MIDI Jack in the descriptor we create a Port usb_midi_allocation = allocate_memory(tuple_size + portin_size + portout_size, false, false); - mp_obj_tuple_t *ports = (mp_obj_tuple_t *) usb_midi_allocation->ptr; + mp_obj_tuple_t *ports = (mp_obj_tuple_t *)usb_midi_allocation->ptr; ports->base.type = &mp_type_tuple; ports->len = 2; - usb_midi_portin_obj_t* in = (usb_midi_portin_obj_t *) (usb_midi_allocation->ptr + tuple_size / 4); + usb_midi_portin_obj_t *in = (usb_midi_portin_obj_t *)(usb_midi_allocation->ptr + tuple_size / 4); in->base.type = &usb_midi_portin_type; ports->items[0] = MP_OBJ_FROM_PTR(in); - usb_midi_portout_obj_t* out = (usb_midi_portout_obj_t *) (usb_midi_allocation->ptr + tuple_size / 4 + portin_size / 4); + usb_midi_portout_obj_t *out = (usb_midi_portout_obj_t *)(usb_midi_allocation->ptr + tuple_size / 4 + portin_size / 4); out->base.type = &usb_midi_portout_type; ports->items[1] = MP_OBJ_FROM_PTR(out); diff --git a/shared-module/ustack/__init__.c b/shared-module/ustack/__init__.c index 1e168ad6a0..55e5fa2d1a 100644 --- a/shared-module/ustack/__init__.c +++ b/shared-module/ustack/__init__.c @@ -36,8 +36,9 @@ uint32_t shared_module_ustack_max_stack_usage(void) { // Start at stack limit and move up. // Untouched stack was filled with a sentinel value. // Stop at first non-sentinel byte. - char* p = MP_STATE_THREAD(stack_bottom); - while (*p++ == MP_MAX_STACK_USAGE_SENTINEL_BYTE) { } + char *p = MP_STATE_THREAD(stack_bottom); + while (*p++ == MP_MAX_STACK_USAGE_SENTINEL_BYTE) { + } return MP_STATE_THREAD(stack_top) - p; } #endif @@ -47,5 +48,5 @@ uint32_t shared_module_ustack_stack_size() { } uint32_t shared_module_ustack_stack_usage() { - return mp_stack_usage(); + return mp_stack_usage(); } diff --git a/shared-module/vectorio/Circle.c b/shared-module/vectorio/Circle.c index 73629b8cee..9c74580650 100644 --- a/shared-module/vectorio/Circle.c +++ b/shared-module/vectorio/Circle.c @@ -25,10 +25,16 @@ uint32_t common_hal_vectorio_circle_get_pixel(void *obj, int16_t x, int16_t y) { int16_t radius = abs(self->radius); x = abs(x); y = abs(y); - if (x+y <= radius) return 1; - if (x > radius) return 0; - if (y > radius) return 0; - const bool pythagorasSmallerThanRadius = (int32_t)x*x + (int32_t)y*y <= (int32_t)radius*radius; + if (x + y <= radius) { + return 1; + } + if (x > radius) { + return 0; + } + if (y > radius) { + return 0; + } + const bool pythagorasSmallerThanRadius = (int32_t)x * x + (int32_t)y * y <= (int32_t)radius * radius; return pythagorasSmallerThanRadius ? 1 : 0; } diff --git a/shared-module/vectorio/Polygon.c b/shared-module/vectorio/Polygon.c index e00a4696b2..00af1e0d7e 100644 --- a/shared-module/vectorio/Polygon.c +++ b/shared-module/vectorio/Polygon.c @@ -22,21 +22,21 @@ static void _clobber_points_list(vectorio_polygon_t *self, mp_obj_t points_tuple mp_obj_list_get(points_tuple_list, &len, &items); VECTORIO_POLYGON_DEBUG(" self.len: %d, len: %d, ", self->len, len); - if ( len < 3 ) { + if (len < 3) { mp_raise_TypeError_varg(translate("Polygon needs at least 3 points")); } - if ( self->len < 2*len ) { - if ( self->points_list != NULL ) { + if (self->len < 2 * len) { + if (self->points_list != NULL) { VECTORIO_POLYGON_DEBUG("free(%d), ", sizeof(self->points_list)); - gc_free( self->points_list ); + gc_free(self->points_list); } - self->points_list = gc_alloc( 2 * len * sizeof(int), false, false ); + self->points_list = gc_alloc(2 * len * sizeof(int), false, false); VECTORIO_POLYGON_DEBUG("alloc(%p, %d)", self->points_list, 2 * len * sizeof(int)); } - self->len = 2*len; + self->len = 2 * len; - for ( size_t i = 0; i < len; ++i) { + for (size_t i = 0; i < len; ++i) { size_t tuple_len = 0; mp_obj_t *tuple_items; mp_obj_tuple_get(items[i], &tuple_len, &tuple_items); @@ -44,11 +44,11 @@ static void _clobber_points_list(vectorio_polygon_t *self, mp_obj_t points_tuple if (tuple_len != 2) { mp_raise_ValueError_varg(translate("%q must be a tuple of length 2"), MP_QSTR_point); } - if ( !mp_obj_get_int_maybe(tuple_items[ 0 ], &self->points_list[2*i ]) - || !mp_obj_get_int_maybe(tuple_items[ 1 ], &self->points_list[2*i + 1]) - ) { + if (!mp_obj_get_int_maybe(tuple_items[ 0 ], &self->points_list[2 * i ]) + || !mp_obj_get_int_maybe(tuple_items[ 1 ], &self->points_list[2 * i + 1]) + ) { self->len = 0; - gc_free( self->points_list ); + gc_free(self->points_list); self->points_list = NULL; mp_raise_ValueError_varg(translate("unsupported %q type"), MP_QSTR_point); } @@ -62,27 +62,27 @@ void common_hal_vectorio_polygon_construct(vectorio_polygon_t *self, mp_obj_t po self->points_list = NULL; self->len = 0; self->on_dirty.obj = NULL; - _clobber_points_list( self, points_list ); + _clobber_points_list(self, points_list); VECTORIO_POLYGON_DEBUG("\n"); } mp_obj_t common_hal_vectorio_polygon_get_points(vectorio_polygon_t *self) { VECTORIO_POLYGON_DEBUG("%p common_hal_vectorio_polygon_get_points {len: %d, points_list: %p}\n", self, self->len, self->points_list); - mp_obj_t list = mp_obj_new_list(self->len/2, NULL); + mp_obj_t list = mp_obj_new_list(self->len / 2, NULL); for (size_t i = 0; i < self->len; i += 2) { - mp_obj_t tuple[] = { mp_obj_new_int(self->points_list[i]), mp_obj_new_int(self->points_list[i+1]) }; + mp_obj_t tuple[] = { mp_obj_new_int(self->points_list[i]), mp_obj_new_int(self->points_list[i + 1]) }; mp_obj_list_append( list, mp_obj_new_tuple(2, tuple) - ); + ); } return list; } void common_hal_vectorio_polygon_set_points(vectorio_polygon_t *self, mp_obj_t points_list) { VECTORIO_POLYGON_DEBUG("%p common_hal_vectorio_polygon_set_points: ", self); - _clobber_points_list( self, points_list ); + _clobber_points_list(self, points_list); if (self->on_dirty.obj != NULL) { self->on_dirty.event(self->on_dirty.obj); } @@ -90,7 +90,7 @@ void common_hal_vectorio_polygon_set_points(vectorio_polygon_t *self, mp_obj_t p } void common_hal_vectorio_polygon_set_on_dirty(vectorio_polygon_t *self, vectorio_event_t notification) { - if ( self->on_dirty.obj != NULL ) { + if (self->on_dirty.obj != NULL) { mp_raise_TypeError(translate("polygon can only be registered in one parent")); } self->on_dirty = notification; @@ -104,14 +104,22 @@ void common_hal_vectorio_polygon_get_area(void *polygon, displayio_area_t *area) area->y1 = SHRT_MAX; area->x2 = SHRT_MIN; area->y2 = SHRT_MIN; - for (size_t i=0; i < self->len; ++i) { + for (size_t i = 0; i < self->len; ++i) { int x = self->points_list[i]; ++i; int y = self->points_list[i]; - if (x <= area->x1) area->x1 = x-1; - if (y <= area->y1) area->y1 = y-1; - if (x >= area->x2) area->x2 = x+1; - if (y >= area->y2) area->y2 = y+1; + if (x <= area->x1) { + area->x1 = x - 1; + } + if (y <= area->y1) { + area->y1 = y - 1; + } + if (x >= area->x2) { + area->x2 = x + 1; + } + if (y >= area->y2) { + area->y2 = y + 1; + } } } @@ -119,9 +127,9 @@ void common_hal_vectorio_polygon_get_area(void *polygon, displayio_area_t *area) // <0 if the point is to the left of the line vector // 0 if the point is on the line // >0 if the point is to the right of the line vector -__attribute__((always_inline)) static inline int line_side( mp_int_t x1, mp_int_t y1, mp_int_t x2, mp_int_t y2, int16_t px, int16_t py ) { +__attribute__((always_inline)) static inline int line_side(mp_int_t x1, mp_int_t y1, mp_int_t x2, mp_int_t y2, int16_t px, int16_t py) { return (px - x1) * (y2 - y1) - - (py - y1) * (x2 - x1); + - (py - y1) * (x2 - x1); } @@ -136,19 +144,19 @@ uint32_t common_hal_vectorio_polygon_get_pixel(void *obj, int16_t x, int16_t y) int winding_number = 0; int x1 = self->points_list[0]; int y1 = self->points_list[1]; - for (size_t i=2; i <= self->len + 1; ++i) { + for (size_t i = 2; i <= self->len + 1; ++i) { VECTORIO_POLYGON_DEBUG(" {(%3d, %3d),", x1, y1); int x2 = self->points_list[i % self->len]; ++i; int y2 = self->points_list[i % self->len]; VECTORIO_POLYGON_DEBUG(" (%3d, %3d)}\n", x2, y2); - if ( y1 <= y ) { - if ( y2 > y && line_side(x1, y1, x2, y2, x, y) < 0 ) { + if (y1 <= y) { + if (y2 > y && line_side(x1, y1, x2, y2, x, y) < 0) { // Wind up, point is to the left of the edge vector ++winding_number; VECTORIO_POLYGON_DEBUG(" wind:%2d winding_number:%2d\n", 1, winding_number); } - } else if ( y2 <= y && line_side(x1, y1, x2, y2, x, y) > 0 ) { + } else if (y2 <= y && line_side(x1, y1, x2, y2, x, y) > 0) { // Wind down, point is to the right of the edge vector --winding_number; VECTORIO_POLYGON_DEBUG(" wind:%2d winding_number:%2d\n", -1, winding_number); diff --git a/shared-module/vectorio/VectorShape.c b/shared-module/vectorio/VectorShape.c index b5d36339ed..c6524af9d3 100644 --- a/shared-module/vectorio/VectorShape.c +++ b/shared-module/vectorio/VectorShape.c @@ -38,16 +38,16 @@ static void _get_screen_area(vectorio_vector_shape_t *self, displayio_area_t *ou VECTORIO_SHAPE_DEBUG("%p get_screen_area tform:{x:%d y:%d dx:%d dy:%d scl:%d w:%d h:%d mx:%d my:%d tr:%d}", self, self->absolute_transform->x, self->absolute_transform->y, self->absolute_transform->dx, self->absolute_transform->dy, self->absolute_transform->scale, self->absolute_transform->width, self->absolute_transform->height, self->absolute_transform->mirror_x, self->absolute_transform->mirror_y, self->absolute_transform->transpose_xy - ); + ); self->ishape.get_area(self->ishape.shape, out_area); VECTORIO_SHAPE_DEBUG(" in:{(%5d,%5d), (%5d,%5d)}", out_area->x1, out_area->y1, out_area->x2, out_area->y2); if (self->absolute_transform->transpose_xy) { int16_t swap = out_area->x1; out_area->x1 = (out_area->y1 + self->y) * self->absolute_transform->dx + self->absolute_transform->x; - out_area->y1 = (swap + self->x) * self->absolute_transform->dy + self->absolute_transform->y; + out_area->y1 = (swap + self->x) * self->absolute_transform->dy + self->absolute_transform->y; swap = out_area->x2; out_area->x2 = (out_area->y2 + self->y) * self->absolute_transform->dx + self->absolute_transform->x; - out_area->y2 = (swap + self->x) * self->absolute_transform->dy + self->absolute_transform->y; + out_area->y2 = (swap + self->x) * self->absolute_transform->dy + self->absolute_transform->y; } else { out_area->x1 = (out_area->x1 + self->x) * self->absolute_transform->dx + self->absolute_transform->x; out_area->y1 = (out_area->y1 + self->y) * self->absolute_transform->dy + self->absolute_transform->y; @@ -94,8 +94,8 @@ void common_hal_vectorio_vector_shape_set_dirty(void *vector_shape) { void common_hal_vectorio_vector_shape_construct(vectorio_vector_shape_t *self, - vectorio_ishape_t ishape, - mp_obj_t pixel_shader, uint16_t x, uint16_t y) { + vectorio_ishape_t ishape, + mp_obj_t pixel_shader, uint16_t x, uint16_t y) { VECTORIO_SHAPE_DEBUG("%p vector_shape_construct x:%3d, y:%3d\n", self, x, y); self->x = x; self->y = y; @@ -152,22 +152,22 @@ void common_hal_vectorio_vector_shape_set_pixel_shader(vectorio_vector_shape_t * } -bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displayio_colorspace_t* colorspace, const displayio_area_t* area, uint32_t* mask, uint32_t *buffer) { +bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displayio_colorspace_t *colorspace, const displayio_area_t *area, uint32_t *mask, uint32_t *buffer) { // Shape areas are relative to 0,0. This will allow rotation about a known axis. // The consequence is that the area reported by the shape itself is _relative_ to 0,0. // To make it relative to the VectorShape position, we must shift it. // Pixels are drawn on the screen_area (shifted) coordinate space, while pixels are _determined_ from // the shape_area (unshifted) space. -#ifdef VECTORIO_PERF + #ifdef VECTORIO_PERF uint64_t start = common_hal_time_monotonic_ns(); uint64_t pixel_time = 0; -#endif + #endif displayio_area_t overlap; VECTORIO_SHAPE_DEBUG("%p fill_area dirty:%d fill: {(%5d,%5d), (%5d,%5d)} dirty: {(%5d,%5d), (%5d,%5d)}", self, self->dirty, area->x1, area->y1, area->x2, area->y2, self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2 - ); + ); if (!displayio_area_compute_overlap(area, &self->ephemeral_dirty_area, &overlap)) { VECTORIO_SHAPE_DEBUG(" no overlap\n"); return false; @@ -194,7 +194,7 @@ bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displ // Check the mask first to see if the pixel has already been set. uint32_t pixel_index = mask_start_px + (input_pixel.x - overlap.x1); uint32_t *mask_doubleword = &(mask[pixel_index / 32]); - uint8_t mask_bit = pixel_index % 32; + uint8_t mask_bit = pixel_index % 32; VECTORIO_SHAPE_PIXEL_DEBUG("%p pixel_index: %5u mask_bit: %2u", self, pixel_index, mask_bit); if ((*mask_doubleword & (1u << mask_bit)) != 0) { VECTORIO_SHAPE_PIXEL_DEBUG(" masked\n"); @@ -213,14 +213,14 @@ bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displ pixel_to_get_y = (input_pixel.y - self->absolute_transform->dy * self->y - self->absolute_transform->y) / self->absolute_transform->dy; } VECTORIO_SHAPE_PIXEL_DEBUG(" get_pixel %p (%3d, %3d) -> ( %3d, %3d )", self->ishape.shape, input_pixel.x, input_pixel.y, pixel_to_get_x, pixel_to_get_y); -#ifdef VECTORIO_PERF + #ifdef VECTORIO_PERF uint64_t pre_pixel = common_hal_time_monotonic_ns(); -#endif + #endif input_pixel.pixel = self->ishape.get_pixel(self->ishape.shape, pixel_to_get_x, pixel_to_get_y); -#ifdef VECTORIO_PERF + #ifdef VECTORIO_PERF uint64_t post_pixel = common_hal_time_monotonic_ns(); pixel_time += post_pixel - pre_pixel; -#endif + #endif VECTORIO_SHAPE_PIXEL_DEBUG(" -> %d", input_pixel.pixel); output_pixel.opaque = true; @@ -238,10 +238,10 @@ bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displ *mask_doubleword |= 1u << mask_bit; if (colorspace->depth == 16) { VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %04x 16\n", output_pixel.pixel); - *(((uint16_t*) buffer) + pixel_index) = output_pixel.pixel; + *(((uint16_t *)buffer) + pixel_index) = output_pixel.pixel; } else if (colorspace->depth == 8) { VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %02x 8\n", output_pixel.pixel); - *(((uint8_t*) buffer) + pixel_index) = output_pixel.pixel; + *(((uint8_t *)buffer) + pixel_index) = output_pixel.pixel; } else if (colorspace->depth < 8) { // Reorder the offsets to pack multiple rows into a byte (meaning they share a column). if (!colorspace->pixels_in_byte_share_row) { @@ -256,13 +256,13 @@ bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displ shift = (pixels_per_byte - 1) * colorspace->depth - shift; } VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %2d %d\n", output_pixel.pixel, colorspace->depth); - ((uint8_t*)buffer)[pixel_index / pixels_per_byte] |= output_pixel.pixel << shift; + ((uint8_t *)buffer)[pixel_index / pixels_per_byte] |= output_pixel.pixel << shift; } } } mask_start_px += linestride_px - column_dirty_offset_px; } -#ifdef VECTORIO_PERF + #ifdef VECTORIO_PERF uint64_t end = common_hal_time_monotonic_ns(); uint32_t pixels = (overlap.x2 - overlap.x1) * (overlap.y2 - overlap.y1); VECTORIO_PERF("draw %16s -> shape:{%4dpx, %4.1fms,%9.1fpps fill} shape_pixels:{%6.1fus total, %4.1fus/px}\n", @@ -272,15 +272,15 @@ bool vectorio_vector_shape_fill_area(vectorio_vector_shape_t *self, const _displ (double)(max(1, pixels * (1000000000.0 / (end - start)))), (double)(pixel_time / 1000.0), (double)(pixel_time / 1000.0 / pixels) - ); -#endif + ); + #endif VECTORIO_SHAPE_DEBUG(" -> pixels:%4d\n"); return full_coverage; } void vectorio_vector_shape_finish_refresh(vectorio_vector_shape_t *self) { - if ( !self->dirty ) { + if (!self->dirty) { return; } VECTORIO_SHAPE_DEBUG("%p finish_refresh was:{(%3d,%3d), (%3d,%3d)}\n", self, self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2); @@ -299,7 +299,7 @@ void vectorio_vector_shape_finish_refresh(vectorio_vector_shape_t *self) { // Assembles a singly linked list of dirty areas from all components on the display. -displayio_area_t* vectorio_vector_shape_get_refresh_areas(vectorio_vector_shape_t *self, displayio_area_t* tail) { +displayio_area_t *vectorio_vector_shape_get_refresh_areas(vectorio_vector_shape_t *self, displayio_area_t *tail) { if (self->dirty || (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_palette_type) && displayio_palette_needs_refresh(self->pixel_shader)) || (MP_OBJ_IS_TYPE(self->pixel_shader, &displayio_colorconverter_type) && displayio_colorconverter_needs_refresh(self->pixel_shader)) diff --git a/shared-module/vectorio/VectorShape.h b/shared-module/vectorio/VectorShape.h index 56eb3d8a53..1896c72d6e 100644 --- a/shared-module/vectorio/VectorShape.h +++ b/shared-module/vectorio/VectorShape.h @@ -38,7 +38,7 @@ typedef struct { displayio_area_t ephemeral_dirty_area; } vectorio_vector_shape_t; -displayio_area_t* vectorio_vector_shape_get_refresh_areas(vectorio_vector_shape_t *self, displayio_area_t *tail); +displayio_area_t *vectorio_vector_shape_get_refresh_areas(vectorio_vector_shape_t *self, displayio_area_t *tail); bool vectorio_vector_shape_get_dirty_area(vectorio_vector_shape_t *self, displayio_area_t *current_dirty_area); diff --git a/shared-module/wiznet/wiznet5k.c b/shared-module/wiznet/wiznet5k.c index 8ccb4ff8d2..708d2166e6 100644 --- a/shared-module/wiznet/wiznet5k.c +++ b/shared-module/wiznet/wiznet5k.c @@ -82,7 +82,7 @@ int wiznet5k_gethostbyname(mp_obj_t nic, const char *name, mp_uint_t len, uint8_ uint8_t dns_ip[MOD_NETWORK_IPADDR_BUF_SIZE] = {8, 8, 8, 8}; uint8_t *buf = m_new(uint8_t, MAX_DNS_BUF_SIZE); DNS_init(0, buf); - mp_int_t ret = DNS_run(dns_ip, (uint8_t*)name, out_ip); + mp_int_t ret = DNS_run(dns_ip, (uint8_t *)name, out_ip); m_del(uint8_t, buf, MAX_DNS_BUF_SIZE); if (ret == 1) { // success @@ -110,9 +110,15 @@ int wiznet5k_socket_socket(mod_network_socket_obj_t *socket, int *_errno) { } switch (socket->u_param.type) { - case MOD_NETWORK_SOCK_STREAM: socket->u_param.type = Sn_MR_TCP; break; - case MOD_NETWORK_SOCK_DGRAM: socket->u_param.type = Sn_MR_UDP; break; - default: *_errno = MP_EINVAL; return -1; + case MOD_NETWORK_SOCK_STREAM: + socket->u_param.type = Sn_MR_TCP; + break; + case MOD_NETWORK_SOCK_DGRAM: + socket->u_param.type = Sn_MR_UDP; + break; + default: + *_errno = MP_EINVAL; + return -1; } if (socket->u_param.fileno == -1) { @@ -184,11 +190,11 @@ int wiznet5k_socket_accept(mod_network_socket_obj_t *socket, mod_network_socket_ socket->u_param.fileno = -1; int _errno2; if (wiznet5k_socket_socket(socket, &_errno2) != 0) { - //printf("(bad resocket %d)\n", _errno2); + // printf("(bad resocket %d)\n", _errno2); } else if (wiznet5k_socket_bind(socket, NULL, *port, &_errno2) != 0) { - //printf("(bad rebind %d)\n", _errno2); + // printf("(bad rebind %d)\n", _errno2); } else if (wiznet5k_socket_listen(socket, 0, &_errno2) != 0) { - //printf("(bad relisten %d)\n", _errno2); + // printf("(bad relisten %d)\n", _errno2); } return 0; @@ -229,7 +235,7 @@ int wiznet5k_socket_connect(mod_network_socket_obj_t *socket, byte *ip, mp_uint_ mp_uint_t wiznet5k_socket_send(mod_network_socket_obj_t *socket, const byte *buf, mp_uint_t len, int *_errno) { MP_THREAD_GIL_EXIT(); - mp_int_t ret = WIZCHIP_EXPORT(send)(socket->u_param.fileno, (byte*)buf, len); + mp_int_t ret = WIZCHIP_EXPORT(send)(socket->u_param.fileno, (byte *)buf, len); MP_THREAD_GIL_ENTER(); // TODO convert Wiz errno's to POSIX ones @@ -264,7 +270,7 @@ mp_uint_t wiznet5k_socket_sendto(mod_network_socket_obj_t *socket, const byte *b } MP_THREAD_GIL_EXIT(); - mp_int_t ret = WIZCHIP_EXPORT(sendto)(socket->u_param.fileno, (byte*)buf, len, ip, port); + mp_int_t ret = WIZCHIP_EXPORT(sendto)(socket->u_param.fileno, (byte *)buf, len, ip, port); MP_THREAD_GIL_ENTER(); if (ret < 0) { @@ -339,7 +345,9 @@ int wiznet5k_start_dhcp(void) { if (wiznet5k_obj.dhcp_socket < 0) { // Set up the socket to listen on UDP 68 before calling DHCP_init wiznet5k_obj.dhcp_socket = get_available_socket(&wiznet5k_obj); - if (wiznet5k_obj.dhcp_socket < 0) return MP_EMFILE; + if (wiznet5k_obj.dhcp_socket < 0) { + return MP_EMFILE; + } WIZCHIP_EXPORT(socket)(wiznet5k_obj.dhcp_socket, MOD_NETWORK_SOCK_DGRAM, DHCP_CLIENT_PORT, 0); DHCP_init(wiznet5k_obj.dhcp_socket, dhcp_buf); @@ -382,7 +390,7 @@ void wiznet5k_socket_deinit(mod_network_socket_obj_t *socket) { mp_obj_t wiznet5k_create(busio_spi_obj_t *spi_in, const mcu_pin_obj_t *cs_in, const mcu_pin_obj_t *rst_in) { // init the wiznet5k object - wiznet5k_obj.base.type = (mp_obj_type_t*)&mod_network_nic_type_wiznet5k; + wiznet5k_obj.base.type = (mp_obj_type_t *)&mod_network_nic_type_wiznet5k; wiznet5k_obj.cris_state = 0; wiznet5k_obj.spi = spi_in; wiznet5k_obj.socket_used = 0; @@ -397,12 +405,14 @@ mp_obj_t wiznet5k_create(busio_spi_obj_t *spi_in, const mcu_pin_obj_t *cs_in, co 1, // HIGH POLARITY 1, // SECOND PHASE TRANSITION 8 // 8 BITS - ); + ); common_hal_digitalio_digitalinout_construct(&wiznet5k_obj.cs, cs_in); common_hal_digitalio_digitalinout_switch_to_output(&wiznet5k_obj.cs, 1, DRIVE_MODE_PUSH_PULL); - if (rst_in) common_hal_digitalio_digitalinout_construct(&wiznet5k_obj.rst, rst_in); + if (rst_in) { + common_hal_digitalio_digitalinout_construct(&wiznet5k_obj.rst, rst_in); + } wiznet5k_reset(); reg_wizchip_cris_cbfunc(wiz_cris_enter, wiz_cris_exit); @@ -417,7 +427,7 @@ mp_obj_t wiznet5k_create(busio_spi_obj_t *spi_in, const mcu_pin_obj_t *cs_in, co .dhcp = NETINFO_DHCP, }; network_module_create_random_mac_address(netinfo.mac); - ctlnetwork(CN_SET_NETINFO, (void*)&netinfo); + ctlnetwork(CN_SET_NETINFO, (void *)&netinfo); // seems we need a small delay after init mp_hal_delay_ms(250); diff --git a/supervisor/linker.h b/supervisor/linker.h old mode 100755 new mode 100644 index 74b2dd5a6d..43050b907a --- a/supervisor/linker.h +++ b/supervisor/linker.h @@ -30,9 +30,9 @@ #define MICROPY_INCLUDED_SUPERVISOR_LINKER_H #if defined(IMXRT10XX) || defined(FOMU) || defined(STM32H7) -#define PLACE_IN_DTCM_DATA(name) name __attribute__((section(".dtcm_data." #name ))) -#define PLACE_IN_DTCM_BSS(name) name __attribute__((section(".dtcm_bss." #name ))) -#define PLACE_IN_ITCM(name) __attribute__((section(".itcm." #name ))) name +#define PLACE_IN_DTCM_DATA(name) name __attribute__((section(".dtcm_data." #name))) +#define PLACE_IN_DTCM_BSS(name) name __attribute__((section(".dtcm_bss." #name))) +#define PLACE_IN_ITCM(name) __attribute__((section(".itcm." #name))) name #else #define PLACE_IN_DTCM_DATA(name) name #define PLACE_IN_DTCM_BSS(name) name diff --git a/supervisor/memory.h b/supervisor/memory.h old mode 100755 new mode 100644 index 0f820eac1c..0aa38eec37 --- a/supervisor/memory.h +++ b/supervisor/memory.h @@ -36,12 +36,12 @@ #include typedef struct { - uint32_t* ptr; + uint32_t *ptr; } supervisor_allocation; -void free_memory(supervisor_allocation* allocation); +void free_memory(supervisor_allocation *allocation); // Find the allocation with the given ptr, NULL if not found. When called from the context of a // supervisor_move_memory() callback, finds the allocation that had that ptr *before* the move, but @@ -49,9 +49,9 @@ void free_memory(supervisor_allocation* allocation); // When called with NULL, may return either NULL or an unused allocation whose ptr is NULL (this is // a feature used internally in allocate_memory to save code size). Passing the return value to // free_memory() is a permissible no-op in either case. -supervisor_allocation* allocation_from_ptr(void *ptr); +supervisor_allocation *allocation_from_ptr(void *ptr); -supervisor_allocation* allocate_remaining_memory(void); +supervisor_allocation *allocate_remaining_memory(void); // Allocate a piece of a given length in bytes. If high_address is true then it should be allocated // at a lower address from the top of the stack. Otherwise, addresses will increase starting after @@ -62,13 +62,13 @@ supervisor_allocation* allocate_remaining_memory(void); // The ptr of the returned supervisor_allocation will change at that point. If you need to be // notified of that, add your own callback function at the designated place near the end of // supervisor_move_memory(). -supervisor_allocation* allocate_memory(uint32_t length, bool high_address, bool movable); +supervisor_allocation *allocate_memory(uint32_t length, bool high_address, bool movable); static inline size_t align32_size(size_t size) { return (size + 3) & ~3; } -size_t get_allocation_length(supervisor_allocation* allocation); +size_t get_allocation_length(supervisor_allocation *allocation); // Called after the GC heap is freed, transfers movable allocations from the GC heap to the // supervisor heap and compacts the supervisor heap. diff --git a/supervisor/port.h b/supervisor/port.h index 812cf715b1..0a8cdfd342 100644 --- a/supervisor/port.h +++ b/supervisor/port.h @@ -74,7 +74,7 @@ uint32_t port_get_saved_word(void); // Get the raw tick count since start up. A tick is 1/1024 of a second, a common low frequency // clock rate. If subticks is not NULL then the port will fill in the number of subticks where each // tick is 32 subticks (for a resolution of 1/32768 or 30.5ish microseconds.) -uint64_t port_get_raw_ticks(uint8_t* subticks); +uint64_t port_get_raw_ticks(uint8_t *subticks); // Enable 1/1024 second tick. void port_enable_tick(void); diff --git a/supervisor/serial.h b/supervisor/serial.h index 066886303e..e85231c6c7 100644 --- a/supervisor/serial.h +++ b/supervisor/serial.h @@ -35,14 +35,14 @@ #ifdef CIRCUITPY_BOOT_OUTPUT_FILE #include "lib/oofatfs/ff.h" -extern FIL* boot_output_file; +extern FIL *boot_output_file; #endif void serial_early_init(void); void serial_init(void); -void serial_write(const char* text); +void serial_write(const char *text); // Only writes up to given length. Does not check for null termination at all. -void serial_write_substring(const char* text, uint32_t length); +void serial_write_substring(const char *text, uint32_t length); char serial_read(void); bool serial_bytes_available(void); bool serial_connected(void); diff --git a/supervisor/shared/background_callback.c b/supervisor/shared/background_callback.c index 68a0a9667d..0dafb5398d 100644 --- a/supervisor/shared/background_callback.c +++ b/supervisor/shared/background_callback.c @@ -33,12 +33,13 @@ #include "supervisor/shared/tick.h" #include "shared-bindings/microcontroller/__init__.h" -STATIC volatile background_callback_t * volatile callback_head, * volatile callback_tail; +STATIC volatile background_callback_t *volatile callback_head, *volatile callback_tail; #define CALLBACK_CRITICAL_BEGIN (common_hal_mcu_disable_interrupts()) #define CALLBACK_CRITICAL_END (common_hal_mcu_enable_interrupts()) -MP_WEAK void port_wake_main_task(void) {} +MP_WEAK void port_wake_main_task(void) { +} void background_callback_add_core(background_callback_t *cb) { CALLBACK_CRITICAL_BEGIN; @@ -47,7 +48,7 @@ void background_callback_add_core(background_callback_t *cb) { return; } cb->next = 0; - cb->prev = (background_callback_t*)callback_tail; + cb->prev = (background_callback_t *)callback_tail; if (callback_tail) { callback_tail->next = cb; } @@ -77,7 +78,7 @@ void PLACE_IN_ITCM(background_callback_run_all)() { return; } in_background_callback = true; - background_callback_t *cb = (background_callback_t*)callback_head; + background_callback_t *cb = (background_callback_t *)callback_head; callback_head = NULL; callback_tail = NULL; while (cb) { @@ -107,8 +108,8 @@ void background_callback_end_critical_section() { void background_callback_reset() { CALLBACK_CRITICAL_BEGIN; - background_callback_t *cb = (background_callback_t*)callback_head; - while(cb) { + background_callback_t *cb = (background_callback_t *)callback_head; + while (cb) { background_callback_t *next = cb->next; memset(cb, 0, sizeof(*cb)); cb = next; @@ -134,8 +135,8 @@ void background_callback_gc_collect(void) { // It's necessary to traverse the whole list here, as the callbacks // themselves can be in non-gc memory, and some of the cb->data // objects themselves might be in non-gc memory. - background_callback_t *cb = (background_callback_t*)callback_head; - while(cb) { + background_callback_t *cb = (background_callback_t *)callback_head; + while (cb) { gc_collect_ptr(cb->data); cb = cb->next; } diff --git a/supervisor/shared/bluetooth.c b/supervisor/shared/bluetooth.c index 56bf321173..00095c4f6b 100644 --- a/supervisor/shared/bluetooth.c +++ b/supervisor/shared/bluetooth.c @@ -81,13 +81,13 @@ STATIC void supervisor_bluetooth_start_advertising(void) { } // TODO: switch to Adafruit short UUID for the advertisement and add manufacturing data to distinguish ourselves from arduino. _common_hal_bleio_adapter_start_advertising(&common_hal_bleio_adapter_obj, - true, - false, 0, - 1.0, - circuitpython_advertising_data, - sizeof(circuitpython_advertising_data), - circuitpython_scan_response_data, - sizeof(circuitpython_scan_response_data)); + true, + false, 0, + 1.0, + circuitpython_advertising_data, + sizeof(circuitpython_advertising_data), + circuitpython_scan_response_data, + sizeof(circuitpython_scan_response_data)); } void supervisor_start_bluetooth(void) { @@ -109,15 +109,15 @@ void supervisor_start_bluetooth(void) { supervisor_ble_version_uuid.base.type = &bleio_uuid_type; common_hal_bleio_uuid_construct(&supervisor_ble_version_uuid, 0x0203, circuitpython_base_uuid); common_hal_bleio_characteristic_construct(&supervisor_ble_version_characteristic, - &supervisor_ble_service, - 0, // handle (for remote only) - &supervisor_ble_version_uuid, - CHAR_PROP_READ, - SECURITY_MODE_OPEN, - SECURITY_MODE_NO_ACCESS, - 4, // max length - true, // fixed length - NULL); // no initial value + &supervisor_ble_service, + 0, // handle (for remote only) + &supervisor_ble_version_uuid, + CHAR_PROP_READ, + SECURITY_MODE_OPEN, + SECURITY_MODE_NO_ACCESS, + 4, // max length + true, // fixed length + NULL); // no initial value uint32_t version = 1; mp_buffer_info_t bufinfo; @@ -129,15 +129,15 @@ void supervisor_start_bluetooth(void) { supervisor_ble_filename_uuid.base.type = &bleio_uuid_type; common_hal_bleio_uuid_construct(&supervisor_ble_filename_uuid, 0x0200, circuitpython_base_uuid); common_hal_bleio_characteristic_construct(&supervisor_ble_filename_characteristic, - &supervisor_ble_service, - 0, // handle (for remote only) - &supervisor_ble_filename_uuid, - CHAR_PROP_READ | CHAR_PROP_WRITE, - SECURITY_MODE_OPEN, - SECURITY_MODE_OPEN, - 500, // max length - false, // fixed length - NULL); // no initial value + &supervisor_ble_service, + 0, // handle (for remote only) + &supervisor_ble_filename_uuid, + CHAR_PROP_READ | CHAR_PROP_WRITE, + SECURITY_MODE_OPEN, + SECURITY_MODE_OPEN, + 500, // max length + false, // fixed length + NULL); // no initial value char code_py[] = "/code.py"; bufinfo.buf = code_py; @@ -148,29 +148,29 @@ void supervisor_start_bluetooth(void) { supervisor_ble_length_uuid.base.type = &bleio_uuid_type; common_hal_bleio_uuid_construct(&supervisor_ble_length_uuid, 0x0202, circuitpython_base_uuid); common_hal_bleio_characteristic_construct(&supervisor_ble_length_characteristic, - &supervisor_ble_service, - 0, // handle (for remote only) - &supervisor_ble_length_uuid, - CHAR_PROP_NOTIFY | CHAR_PROP_READ, - SECURITY_MODE_OPEN, - SECURITY_MODE_NO_ACCESS, - 4, // max length - true, // fixed length - NULL); // no initial value + &supervisor_ble_service, + 0, // handle (for remote only) + &supervisor_ble_length_uuid, + CHAR_PROP_NOTIFY | CHAR_PROP_READ, + SECURITY_MODE_OPEN, + SECURITY_MODE_NO_ACCESS, + 4, // max length + true, // fixed length + NULL); // no initial value // File actions supervisor_ble_contents_uuid.base.type = &bleio_uuid_type; common_hal_bleio_uuid_construct(&supervisor_ble_contents_uuid, 0x0201, circuitpython_base_uuid); common_hal_bleio_characteristic_construct(&supervisor_ble_contents_characteristic, - &supervisor_ble_service, - 0, // handle (for remote only) - &supervisor_ble_contents_uuid, - CHAR_PROP_NOTIFY | CHAR_PROP_WRITE_NO_RESPONSE | CHAR_PROP_WRITE, - SECURITY_MODE_OPEN, - SECURITY_MODE_OPEN, - 500, // max length - false, // fixed length - NULL); // no initial value + &supervisor_ble_service, + 0, // handle (for remote only) + &supervisor_ble_contents_uuid, + CHAR_PROP_NOTIFY | CHAR_PROP_WRITE_NO_RESPONSE | CHAR_PROP_WRITE, + SECURITY_MODE_OPEN, + SECURITY_MODE_OPEN, + 500, // max length + false, // fixed length + NULL); // no initial value supervisor_bluetooth_start_advertising(); vm_used_ble = false; @@ -187,7 +187,7 @@ STATIC void update_file_length(void) { bufinfo.buf = &file_length; bufinfo.len = sizeof(file_length); if (active_file.obj.fs != 0) { - file_length = (int32_t) f_size(&active_file); + file_length = (int32_t)f_size(&active_file); } common_hal_bleio_characteristic_set_value(&supervisor_ble_length_characteristic, &bufinfo); } @@ -201,8 +201,8 @@ STATIC void open_current_file(void) { size_t length = common_hal_bleio_characteristic_get_value(&supervisor_ble_filename_characteristic, path, max_len - 1); path[length] = '\0'; - FATFS *fs = &((fs_user_mount_t *) MP_STATE_VM(vfs_mount_table)->obj)->fatfs; - f_open(fs, &active_file, (char*) path, FA_READ | FA_WRITE); + FATFS *fs = &((fs_user_mount_t *)MP_STATE_VM(vfs_mount_table)->obj)->fatfs; + f_open(fs, &active_file, (char *)path, FA_READ | FA_WRITE); update_file_length(); } @@ -238,12 +238,12 @@ void supervisor_bluetooth_background(void) { new_filename = false; // get length and set the characteristic for it } - uint16_t current_length = ((uint16_t*) current_command)[0]; + uint16_t current_length = ((uint16_t *)current_command)[0]; if (current_length > 0 && current_length == current_offset) { - uint16_t command = ((uint16_t *) current_command)[1]; + uint16_t command = ((uint16_t *)current_command)[1]; if (command == 1) { - uint16_t max_len = 20; //supervisor_ble_contents_characteristic.max_length; + uint16_t max_len = 20; // supervisor_ble_contents_characteristic.max_length; uint8_t buf[max_len]; mp_buffer_info_t bufinfo; bufinfo.buf = buf; @@ -258,8 +258,8 @@ void supervisor_bluetooth_background(void) { uint32_t offset = current_command[1]; uint32_t remove_length = current_command[2]; uint32_t insert_length = current_command[3]; - uint32_t file_length = (int32_t) f_size(&active_file); - //uint32_t data_shift_length = fileLength - offset - remove_length; + uint32_t file_length = (int32_t)f_size(&active_file); + // uint32_t data_shift_length = fileLength - offset - remove_length; int32_t data_shift = insert_length - remove_length; uint32_t new_length = file_length + data_shift; @@ -278,11 +278,11 @@ void supervisor_bluetooth_background(void) { f_lseek(&active_file, file_length); // Fill end with 0xff so we don't need to erase. uint8_t data = 0xff; - for (size_t i = 0; i < (size_t) data_shift; i++) { + for (size_t i = 0; i < (size_t)data_shift; i++) { UINT actual; f_write(&active_file, &data, 1, &actual); } - for (uint32_t shift_offset = new_length - 1; shift_offset >= offset + insert_length ; shift_offset--) { + for (uint32_t shift_offset = new_length - 1; shift_offset >= offset + insert_length; shift_offset--) { UINT actual; f_lseek(&active_file, shift_offset - data_shift); f_read(&active_file, &data, 1, &actual); @@ -292,7 +292,7 @@ void supervisor_bluetooth_background(void) { } f_lseek(&active_file, offset); - uint8_t* data = (uint8_t *) (current_command + 4); + uint8_t *data = (uint8_t *)(current_command + 4); UINT written; f_write(&active_file, data, insert_length, &written); f_sync(&active_file); diff --git a/supervisor/shared/board.c b/supervisor/shared/board.c index 6d648510e7..427c179242 100644 --- a/supervisor/shared/board.c +++ b/supervisor/shared/board.c @@ -33,7 +33,7 @@ #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/neopixel_write/__init__.h" -void board_reset_user_neopixels(const mcu_pin_obj_t* pin, size_t count) { +void board_reset_user_neopixels(const mcu_pin_obj_t *pin, size_t count) { // Turn off on-board NeoPixel string uint8_t empty[count * 3]; memset(empty, 0, count * 3); diff --git a/supervisor/shared/board.h b/supervisor/shared/board.h index fe887a9335..def5f48655 100644 --- a/supervisor/shared/board.h +++ b/supervisor/shared/board.h @@ -31,6 +31,6 @@ #include "shared-bindings/microcontroller/Pin.h" -void board_reset_user_neopixels(const mcu_pin_obj_t* pin, size_t count); +void board_reset_user_neopixels(const mcu_pin_obj_t *pin, size_t count); #endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_BOARD_H diff --git a/supervisor/shared/display.c b/supervisor/shared/display.c index 1919cf4a47..6ee6c7386a 100644 --- a/supervisor/shared/display.c +++ b/supervisor/shared/display.c @@ -50,7 +50,7 @@ extern displayio_bitmap_t blinka_bitmap; extern displayio_group_t circuitpython_splash; #if CIRCUITPY_TERMINALIO -static supervisor_allocation* tilegrid_tiles = NULL; +static supervisor_allocation *tilegrid_tiles = NULL; #endif void supervisor_start_terminal(uint16_t width_px, uint16_t height_px) { @@ -59,10 +59,10 @@ void supervisor_start_terminal(uint16_t width_px, uint16_t height_px) { uint8_t scale = 2; #if CIRCUITPY_TERMINALIO - displayio_tilegrid_t* grid = &supervisor_terminal_text_grid; + displayio_tilegrid_t *grid = &supervisor_terminal_text_grid; bool tall = height_px > width_px; uint16_t terminal_width_px = tall ? width_px : width_px - blinka_bitmap.width; - uint16_t terminal_height_px = tall ? height_px - blinka_bitmap.height : height_px ; + uint16_t terminal_height_px = tall ? height_px - blinka_bitmap.height : height_px; uint16_t width_in_tiles = terminal_width_px / grid->tile_width; // determine scale based on h if (width_in_tiles < 80) { @@ -94,7 +94,7 @@ void supervisor_start_terminal(uint16_t width_px, uint16_t height_px) { return; } } - uint8_t* tiles = (uint8_t*) tilegrid_tiles->ptr; + uint8_t *tiles = (uint8_t *)tilegrid_tiles->ptr; grid->y = tall ? blinka_bitmap.height : 0; grid->x = tall ? 0 : blinka_bitmap.width; @@ -130,7 +130,7 @@ void supervisor_stop_terminal(void) { void supervisor_display_move_memory(void) { #if CIRCUITPY_TERMINALIO if (tilegrid_tiles != NULL) { - supervisor_terminal_text_grid.tiles = (uint8_t*) tilegrid_tiles->ptr; + supervisor_terminal_text_grid.tiles = (uint8_t *)tilegrid_tiles->ptr; } else { supervisor_terminal_text_grid.tiles = NULL; } @@ -139,16 +139,16 @@ void supervisor_display_move_memory(void) { #if CIRCUITPY_DISPLAYIO for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { #if CIRCUITPY_RGBMATRIX - if (displays[i].rgbmatrix.base.type == &rgbmatrix_RGBMatrix_type) { - rgbmatrix_rgbmatrix_obj_t * pm = &displays[i].rgbmatrix; - common_hal_rgbmatrix_rgbmatrix_reconstruct(pm, NULL); - } + if (displays[i].rgbmatrix.base.type == &rgbmatrix_RGBMatrix_type) { + rgbmatrix_rgbmatrix_obj_t *pm = &displays[i].rgbmatrix; + common_hal_rgbmatrix_rgbmatrix_reconstruct(pm, NULL); + } #endif #if CIRCUITPY_SHARPDISPLAY - if (displays[i].bus_base.type == &sharpdisplay_framebuffer_type) { - sharpdisplay_framebuffer_obj_t * sharp = &displays[i].sharpdisplay; - common_hal_sharpdisplay_framebuffer_reconstruct(sharp); - } + if (displays[i].bus_base.type == &sharpdisplay_framebuffer_type) { + sharpdisplay_framebuffer_obj_t *sharp = &displays[i].sharpdisplay; + common_hal_sharpdisplay_framebuffer_reconstruct(sharp); + } #endif } #endif diff --git a/supervisor/shared/external_flash/devices.h b/supervisor/shared/external_flash/devices.h index c8c941adf8..edc6419ef9 100644 --- a/supervisor/shared/external_flash/devices.h +++ b/supervisor/shared/external_flash/devices.h @@ -55,662 +55,662 @@ typedef struct { // Supports the quad input page program command 0x32. This is known as 1-1-4 because it only // uses all four lines for data. - bool supports_qspi_writes: 1; + bool supports_qspi_writes : 1; // Requires a separate command 0x31 to write to the second byte of the status register. // Otherwise two byte are written via 0x01. - bool write_status_register_split: 1; + bool write_status_register_split : 1; // True when the status register is a single byte. This implies the Quad Enable bit is in the // first byte and the Read Status Register 2 command (0x35) is unsupported. - bool single_status_byte: 1; + bool single_status_byte : 1; // Does not support using a ready bit within the status register - bool no_ready_bit: 1; + bool no_ready_bit : 1; // Does not support the erase command (0x20) - bool no_erase_cmd: 1; + bool no_erase_cmd : 1; // Device does not have a reset command - bool no_reset_cmd: 1; + bool no_reset_cmd : 1; } external_flash_device; // Settings for the Adesto Tech AT25DF081A 1MiB SPI flash. It's on the SAMD21 // Xplained board. // Datasheet: https://www.adestotech.com/wp-content/uploads/doc8715.pdf -#define AT25DF081A {\ - .total_size = (1 << 20), /* 1 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0x1f, \ - .memory_type = 0x45, \ - .capacity = 0x01, \ - .max_clock_speed_mhz = 85, \ - .quad_enable_bit_mask = 0x00, \ - .has_sector_protection = true, \ - .supports_fast_read = true, \ - .supports_qspi = false, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define AT25DF081A { \ + .total_size = (1 << 20), /* 1 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0x1f, \ + .memory_type = 0x45, \ + .capacity = 0x01, \ + .max_clock_speed_mhz = 85, \ + .quad_enable_bit_mask = 0x00, \ + .has_sector_protection = true, \ + .supports_fast_read = true, \ + .supports_qspi = false, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Adesto Tech AT25DF641-SSHD-T 8MiB SPI flash // for the Oak Dev Tech Icy Tree M0 (SAMD21) feather board. // Source: https://www.digikey.com/product-detail/en/adesto-technologies/AT25SF641-SDHD-T/1265-1180-1-ND/ // Datasheet: https://www.adestotech.com/wp-content/uploads/doc8693.pdf -#define AT25DF641A {\ - .total_size = (1 << 23), /* 8 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0x1f, \ - .memory_type = 0x48, \ - .capacity = 0x00, \ - .max_clock_speed_mhz = 85, \ - .quad_enable_bit_mask = 0x00, \ - .has_sector_protection = true, \ - .supports_fast_read = true, \ - .supports_qspi = false, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define AT25DF641A { \ + .total_size = (1 << 23), /* 8 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0x1f, \ + .memory_type = 0x48, \ + .capacity = 0x00, \ + .max_clock_speed_mhz = 85, \ + .quad_enable_bit_mask = 0x00, \ + .has_sector_protection = true, \ + .supports_fast_read = true, \ + .supports_qspi = false, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Adesto Tech AT25SF161-SSHD-T 2MiB SPI flash // for the StringCar M0 (SAMD21) Express board. // Source: https://www.digikey.com/product-detail/en/adesto-technologies/AT25SF161-SDHD-T/1265-1230-1-ND/ // Datasheet: https://www.adestotech.com/wpo-content/uploads/jDS-AT25SF161_046.pdf -#define AT25SF161 {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0x1f, \ - .memory_type = 0x86, \ - .capacity = 0x01, \ - .max_clock_speed_mhz = 85, \ - .quad_enable_bit_mask = 0x00, \ - .has_sector_protection = true, \ - .supports_fast_read = true, \ - .supports_qspi = false, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define AT25SF161 { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0x1f, \ + .memory_type = 0x86, \ + .capacity = 0x01, \ + .max_clock_speed_mhz = 85, \ + .quad_enable_bit_mask = 0x00, \ + .has_sector_protection = true, \ + .supports_fast_read = true, \ + .supports_qspi = false, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Adesto Tech AT25SF041 1MiB SPI flash. It's on the SparkFun // SAMD51 Thing Plus board // Datasheet: https://www.adestotech.com/wp-content/uploads/DS-AT25SF041_044.pdf -#define AT25SF041A {\ - .total_size = (1 << 19), /* 512 KiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0x1f, \ - .memory_type = 0x84, \ - .capacity = 0x01, \ - .max_clock_speed_mhz = 85, \ - .quad_enable_bit_mask = 0x00, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = false, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define AT25SF041A { \ + .total_size = (1 << 19), /* 512 KiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0x1f, \ + .memory_type = 0x84, \ + .capacity = 0x01, \ + .max_clock_speed_mhz = 85, \ + .quad_enable_bit_mask = 0x00, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = false, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Gigadevice GD25Q16C 2MiB SPI flash. // Datasheet: http://www.gigadevice.com/datasheet/gd25q16c/ -#define GD25Q16C {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc8, \ - .memory_type = 0x40, \ - .capacity = 0x15, \ - .max_clock_speed_mhz = 104, /* if we need 120 then we can turn on high performance mode */ \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define GD25Q16C { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc8, \ + .memory_type = 0x40, \ + .capacity = 0x15, \ + .max_clock_speed_mhz = 104, /* if we need 120 then we can turn on high performance mode */ \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Gigadevice GD25Q32C 4MiB SPI flash. // Datasheet: http://www.elm-tech.com/en/products/spi-flash-memory/gd25q32/gd25q32.pdf -#define GD25Q32C {\ - .total_size = (1 << 22), /* 4 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc8, \ - .memory_type = 0x40, \ - .capacity = 0x16, \ - .max_clock_speed_mhz = 104, /* if we need 120 then we can turn on high performance mode */ \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = true, \ - .single_status_byte = false, \ +#define GD25Q32C { \ + .total_size = (1 << 22), /* 4 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc8, \ + .memory_type = 0x40, \ + .capacity = 0x16, \ + .max_clock_speed_mhz = 104, /* if we need 120 then we can turn on high performance mode */ \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = true, \ + .single_status_byte = false, \ } // Settings for the Gigadevice GD25Q64C 8MiB SPI flash. // Datasheet: http://www.elm-tech.com/en/products/spi-flash-memory/gd25q64/gd25q64.pdf -#define GD25Q64C {\ - .total_size = (1 << 23), /* 8 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc8, \ - .memory_type = 0x40, \ - .capacity = 0x17, \ - .max_clock_speed_mhz = 104, /* if we need 120 then we can turn on high performance mode */ \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = true, \ - .single_status_byte = false, \ +#define GD25Q64C { \ + .total_size = (1 << 23), /* 8 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc8, \ + .memory_type = 0x40, \ + .capacity = 0x17, \ + .max_clock_speed_mhz = 104, /* if we need 120 then we can turn on high performance mode */ \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = true, \ + .single_status_byte = false, \ } // Settings for the Gigadevice GD25S512MD 64MiB SPI flash. // Datasheet: http://www.gigadevice.com/datasheet/gd25s512md/ -#define GD25S512MD {\ - .total_size = (1 << 26), /* 64 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc8, \ - .memory_type = 0x40, \ - .capacity = 0x19, \ - .max_clock_speed_mhz = 104, /* if we need 120 then we can turn on high performance mode */ \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = true, \ - .single_status_byte = false, \ +#define GD25S512MD { \ + .total_size = (1 << 26), /* 64 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc8, \ + .memory_type = 0x40, \ + .capacity = 0x19, \ + .max_clock_speed_mhz = 104, /* if we need 120 then we can turn on high performance mode */ \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = true, \ + .single_status_byte = false, \ } // Settings for the Cypress (was Spansion) S25FL064L 8MiB SPI flash. // Datasheet: http://www.cypress.com/file/316661/download -#define S25FL064L {\ - .total_size = (1 << 23), /* 8 MiB */ \ - .start_up_time_us = 300, \ - .manufacturer_id = 0x01, \ - .memory_type = 0x60, \ - .capacity = 0x17, \ - .max_clock_speed_mhz = 108, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define S25FL064L { \ + .total_size = (1 << 23), /* 8 MiB */ \ + .start_up_time_us = 300, \ + .manufacturer_id = 0x01, \ + .memory_type = 0x60, \ + .capacity = 0x17, \ + .max_clock_speed_mhz = 108, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Cypress (was Spansion) S25FL116K 2MiB SPI flash. // Datasheet: http://www.cypress.com/file/196886/download -#define S25FL116K {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0x01, \ - .memory_type = 0x40, \ - .capacity = 0x15, \ - .max_clock_speed_mhz = 108, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define S25FL116K { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0x01, \ + .memory_type = 0x40, \ + .capacity = 0x15, \ + .max_clock_speed_mhz = 108, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Cypress (was Spansion) S25FL216K 2MiB SPI flash. // Datasheet: http://www.cypress.com/file/197346/download -#define S25FL216K {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0x01, \ - .memory_type = 0x40, \ - .capacity = 0x15, \ - .max_clock_speed_mhz = 65, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = false, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define S25FL216K { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0x01, \ + .memory_type = 0x40, \ + .capacity = 0x15, \ + .max_clock_speed_mhz = 65, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = false, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q16FW 2MiB SPI flash. // Datasheet: https://www.winbond.com/resource-files/w25q16fw%20revj%2005182017%20sfdp.pdf -#define W25Q16FW {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x60, \ - .capacity = 0x15, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q16FW { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x60, \ + .capacity = 0x15, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q16JV-IQ 2MiB SPI flash. Note that JV-IM has a different .memory_type (0x70) // Datasheet: https://www.winbond.com/resource-files/w25q16jv%20spi%20revf%2005092017.pdf -#define W25Q16JV_IQ {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x40, \ - .capacity = 0x15, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q16JV_IQ { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x40, \ + .capacity = 0x15, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q16JV-IM 2MiB SPI flash. Note that JV-IQ has a different .memory_type (0x40) // Datasheet: https://www.winbond.com/resource-files/w25q16jv%20spi%20revf%2005092017.pdf -#define W25Q16JV_IM {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x70, \ - .capacity = 0x15, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ +#define W25Q16JV_IM { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x70, \ + .capacity = 0x15, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ } // Settings for the Winbond W25Q32BV 4MiB SPI flash. // Datasheet: https://www.winbond.com/resource-files/w25q32bv_revi_100413_wo_automotive.pdf -#define W25Q32BV {\ - .total_size = (1 << 22), /* 4 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x60, \ - .capacity = 0x16, \ - .max_clock_speed_mhz = 104, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q32BV { \ + .total_size = (1 << 22), /* 4 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x60, \ + .capacity = 0x16, \ + .max_clock_speed_mhz = 104, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q32JV-IM 4MiB SPI flash. // Datasheet: https://www.winbond.com/resource-files/w25q32jv%20revg%2003272018%20plus.pdf -#define W25Q32JV_IM {\ - .total_size = (1 << 22), /* 4 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x70, \ - .capacity = 0x16, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ +#define W25Q32JV_IM { \ + .total_size = (1 << 22), /* 4 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x70, \ + .capacity = 0x16, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ } // Settings for the Winbond W25Q32JV-IQ 4MiB SPI flash. // Datasheet: https://www.mouser.com/datasheet/2/949/w25q32jv_revg_03272018_plus-1489806.pdf -#define W25Q32JV_IQ {\ - .total_size = (1 << 22), /* 4 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x40, \ - .capacity = 0x16, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ +#define W25Q32JV_IQ { \ + .total_size = (1 << 22), /* 4 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x40, \ + .capacity = 0x16, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ } // Settings for the Winbond W25Q64FV 8MiB SPI flash. // Datasheet: https://www.winbond.com/resource-files/w25q64fv%20revs%2007182017.pdf -#define W25Q64FV {\ - .total_size = (1 << 23), /* 8 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x40, \ - .capacity = 0x17, \ - .max_clock_speed_mhz = 104, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q64FV { \ + .total_size = (1 << 23), /* 8 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x40, \ + .capacity = 0x17, \ + .max_clock_speed_mhz = 104, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q64JV-IM 8MiB SPI flash. Note that JV-IQ has a different .memory_type (0x40) // Datasheet: http://www.winbond.com/resource-files/w25q64jv%20revj%2003272018%20plus.pdf -#define W25Q64JV_IM {\ - .total_size = (1 << 23), /* 8 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x70, \ - .capacity = 0x17, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q64JV_IM { \ + .total_size = (1 << 23), /* 8 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x70, \ + .capacity = 0x17, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q64JV-IQ 8MiB SPI flash. Note that JV-IM has a different .memory_type (0x70) // Datasheet: http://www.winbond.com/resource-files/w25q64jv%20revj%2003272018%20plus.pdf -#define W25Q64JV_IQ {\ - .total_size = (1 << 23), /* 8 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x40, \ - .capacity = 0x17, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q64JV_IQ { \ + .total_size = (1 << 23), /* 8 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x40, \ + .capacity = 0x17, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q80DL 1MiB SPI flash. // Datasheet: https://www.winbond.com/resource-files/w25q80dv%20dl_revh_10022015.pdf -#define W25Q80DL {\ - .total_size = (1 << 20), /* 1 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x60, \ - .capacity = 0x14, \ - .max_clock_speed_mhz = 104, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q80DL { \ + .total_size = (1 << 20), /* 1 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x60, \ + .capacity = 0x14, \ + .max_clock_speed_mhz = 104, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q80DV 1MiB SPI flash.. Note that W25Q80DL has a different memory type (0x60) // Datasheet: https://www.winbond.com/resource-files/w25q80dv%20dl_revh_10022015.pdf -#define W25Q80DV {\ - .total_size = (1 << 20), /* 1 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x40, \ - .capacity = 0x14, \ - .max_clock_speed_mhz = 104, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q80DV { \ + .total_size = (1 << 20), /* 1 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x40, \ + .capacity = 0x14, \ + .max_clock_speed_mhz = 104, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Winbond W25Q128JV-SQ 16MiB SPI flash. Note that JV-IM has a different .memory_type (0x70) // Datasheet: https://www.winbond.com/resource-files/w25q128jv%20revf%2003272018%20plus.pdf -#define W25Q128JV_SQ {\ - .total_size = (1 << 24), /* 16 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x40, \ - .capacity = 0x18, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q128JV_SQ { \ + .total_size = (1 << 24), /* 16 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x40, \ + .capacity = 0x18, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the Everspin MR20H40 / MR25H40 magnetic non-volatile RAM // Datasheet: https://www.everspin.com/supportdocs/MR25H40CDFR -#define MR2xH40 {\ - .total_size = (1 << 22), /* 4 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0xef, /*no JDEC*/ \ - .memory_type = 0x40, /*no JDEC*/ \ - .capacity = 0x14, /*no JDEC*/ \ - .max_clock_speed_mhz = 10, \ - .quad_enable_bit_mask = 0x00, \ - .has_sector_protection = false, \ - .supports_fast_read = false, \ - .supports_qspi = false, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ - .no_ready_bit = true, \ - .no_erase_cmd = true, \ - .no_reset_cmd = true, \ +#define MR2xH40 { \ + .total_size = (1 << 22), /* 4 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0xef, /*no JDEC*/ \ + .memory_type = 0x40, /*no JDEC*/ \ + .capacity = 0x14, /*no JDEC*/ \ + .max_clock_speed_mhz = 10, \ + .quad_enable_bit_mask = 0x00, \ + .has_sector_protection = false, \ + .supports_fast_read = false, \ + .supports_qspi = false, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ + .no_ready_bit = true, \ + .no_erase_cmd = true, \ + .no_reset_cmd = true, \ } // Settings for the Macronix MX25L1606 2MiB SPI flash. // Datasheet: -#define MX25L1606 {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc2, \ - .memory_type = 0x20, \ - .capacity = 0x15, \ - .max_clock_speed_mhz = 8, \ - .quad_enable_bit_mask = 0x40, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ +#define MX25L1606 { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc2, \ + .memory_type = 0x20, \ + .capacity = 0x15, \ + .max_clock_speed_mhz = 8, \ + .quad_enable_bit_mask = 0x40, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ } // Settings for the Macronix MX25L3233F 4MiB SPI flash. // Datasheet: http://www.macronix.com/Lists/Datasheet/Attachments/7426/MX25L3233F,%203V,%2032Mb,%20v1.6.pdf -#define MX25L3233F {\ - .total_size = (1 << 22), /* 4 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc2, \ - .memory_type = 0x20, \ - .capacity = 0x16, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x40, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ +#define MX25L3233F { \ + .total_size = (1 << 22), /* 4 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc2, \ + .memory_type = 0x20, \ + .capacity = 0x16, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x40, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ } // Settings for the Macronix MX25R6435F 8MiB SPI flash. // Datasheet: http://www.macronix.com/Lists/Datasheet/Attachments/7428/MX25R6435F,%20Wide%20Range,%2064Mb,%20v1.4.pdf // By default its in lower power mode which can only do 8mhz. In high power mode it can do 80mhz. -#define MX25R6435F {\ - .total_size = (1 << 23), /* 8 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc2, \ - .memory_type = 0x28, \ - .capacity = 0x17, \ - .max_clock_speed_mhz = 8, \ - .quad_enable_bit_mask = 0x40, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ +#define MX25R6435F { \ + .total_size = (1 << 23), /* 8 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc2, \ + .memory_type = 0x28, \ + .capacity = 0x17, \ + .max_clock_speed_mhz = 8, \ + .quad_enable_bit_mask = 0x40, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ } // Settings for the Macronix MX25R1635F 8MiB SPI flash. // Datasheet: https://www.macronix.com/Lists/Datasheet/Attachments/7595/MX25R1635F,%20Wide%20Range,%2016Mb,%20v1.6.pdf // In low power mode, quad operations can only run at 8 MHz. -#define MX25R1635F {\ - .total_size = (1 << 21), /* 2 MiB */ \ - .start_up_time_us = 800, \ - .manufacturer_id = 0xc2, \ - .memory_type = 0x28, \ - .capacity = 0x15, \ - .max_clock_speed_mhz = 33, /* 8 mhz for dual/quad */ \ - .quad_enable_bit_mask = 0x80, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ +#define MX25R1635F { \ + .total_size = (1 << 21), /* 2 MiB */ \ + .start_up_time_us = 800, \ + .manufacturer_id = 0xc2, \ + .memory_type = 0x28, \ + .capacity = 0x15, \ + .max_clock_speed_mhz = 33, /* 8 mhz for dual/quad */ \ + .quad_enable_bit_mask = 0x80, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ } // Settings for the Macronix MX25L51245G 64MiB SPI flash. // Datasheet: https://www.macronix.com/Lists/Datasheet/Attachments/7437/MX25L51245G,%203V,%20512Mb,%20v1.6.pdf -#define MX25L51245G {\ - .total_size = (1 << 26), /* 64 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc2, \ - .memory_type = 0x20, \ - .capacity = 0x1a, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x40, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ +#define MX25L51245G { \ + .total_size = (1 << 26), /* 64 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc2, \ + .memory_type = 0x20, \ + .capacity = 0x1a, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x40, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ } // Settings for the Macronix MX25L51245G 64MiB SPI flash. // Datasheet: https://www.macronix.com/Lists/Datasheet/Attachments/7437/MX25L51245G,%203V,%20512Mb,%20v1.6.pdf -#define MX25L25645G {\ - .total_size = (1 << 25), /* 32 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0x9f, \ - .memory_type = 0xab, \ - .capacity = 0x90, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0xaf, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ +#define MX25L25645G { \ + .total_size = (1 << 25), /* 32 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0x9f, \ + .memory_type = 0xab, \ + .capacity = 0x90, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0xaf, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ } // Settings for the Macronix MX25L12833F 16MiB SPI flash // Datasheet: https://www.macronix.com/Lists/Datasheet/Attachments/7447/MX25L12833F,%203V,%20128Mb,%20v1.0.pdf -#define MX25L12833F {\ - .total_size = (1UL << 24), /* 16 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xc2, \ - .memory_type = 0x20, \ - .capacity = 0x18, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x40, \ - .has_sector_protection = true, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ - } +#define MX25L12833F { \ + .total_size = (1UL << 24), /* 16 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xc2, \ + .memory_type = 0x20, \ + .capacity = 0x18, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x40, \ + .has_sector_protection = true, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ +} // Settings for the Winbond W25Q128JV-PM 16MiB SPI flash. Note that JV-IM has a different .memory_type (0x70) // Datasheet: https://www.winbond.com/resource-files/w25q128jv%20revf%2003272018%20plus.pdf -#define W25Q128JV_PM {\ - .total_size = (1 << 24), /* 16 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x70, \ - .capacity = 0x18, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ +#define W25Q128JV_PM { \ + .total_size = (1 << 24), /* 16 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x70, \ + .capacity = 0x18, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ } // Settings for the Winbond W25Q32FV 4MiB SPI flash. // Datasheet:http://www.winbond.com/resource-files/w25q32fv%20revj%2006032016.pdf?__locale=en -#define W25Q32FV {\ - .total_size = (1 << 22), /* 4 MiB */ \ - .start_up_time_us = 5000, \ - .manufacturer_id = 0xef, \ - .memory_type = 0x40, \ - .capacity = 0x16, \ - .max_clock_speed_mhz = 104, \ - .quad_enable_bit_mask = 0x00, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = false, \ - .supports_qspi_writes = false, \ - .write_status_register_split = false, \ - .single_status_byte = false, \ +#define W25Q32FV { \ + .total_size = (1 << 22), /* 4 MiB */ \ + .start_up_time_us = 5000, \ + .manufacturer_id = 0xef, \ + .memory_type = 0x40, \ + .capacity = 0x16, \ + .max_clock_speed_mhz = 104, \ + .quad_enable_bit_mask = 0x00, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = false, \ + .supports_qspi_writes = false, \ + .write_status_register_split = false, \ + .single_status_byte = false, \ } // Settings for the ISSI IS25LP128F 16MiB SPI flash. // Datasheet: http://www.issi.com/WW/pdf/25LP-WP128F.pdf -#define IS25LP128F {\ - .total_size = (1 << 24), /* 16 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0x9d, \ - .memory_type = 0x60, \ - .capacity = 0x18, \ - .max_clock_speed_mhz = 133, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = true, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ +#define IS25LP128F { \ + .total_size = (1 << 24), /* 16 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0x9d, \ + .memory_type = 0x60, \ + .capacity = 0x18, \ + .max_clock_speed_mhz = 133, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = true, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ } // Settings for the Micron N25Q256A 256Mb (32MiB) QSPI flash. // Datasheet: https://www.micron.com/-/media/client/global/documents/products/data-sheet/nor-flash/serial-nor/n25q/n25q_256mb_3v.pdf -#define N25Q256A {\ - /* .total_size = (1 << 25), 32 MiB does not work at this time, as assumptions about 3-byte addresses abound */ \ - .total_size = (1 << 24), /* 16 MiB */ \ - .start_up_time_us = 10000, \ - .manufacturer_id = 0x20, \ - .memory_type = 0xBA, \ - .capacity = 0x19, \ - .max_clock_speed_mhz = 108, \ - .quad_enable_bit_mask = 0x02, \ - .has_sector_protection = false, \ - .supports_fast_read = true, \ - .supports_qspi = true, \ - .supports_qspi_writes = true, \ - .write_status_register_split = false, \ - .single_status_byte = true, \ +#define N25Q256A { \ + /* .total_size = (1 << 25), 32 MiB does not work at this time, as assumptions about 3-byte addresses abound */ \ + .total_size = (1 << 24), /* 16 MiB */ \ + .start_up_time_us = 10000, \ + .manufacturer_id = 0x20, \ + .memory_type = 0xBA, \ + .capacity = 0x19, \ + .max_clock_speed_mhz = 108, \ + .quad_enable_bit_mask = 0x02, \ + .has_sector_protection = false, \ + .supports_fast_read = true, \ + .supports_qspi = true, \ + .supports_qspi_writes = true, \ + .write_status_register_split = false, \ + .single_status_byte = true, \ } #endif // MICROPY_INCLUDED_ATMEL_SAMD_EXTERNAL_FLASH_DEVICES_H diff --git a/supervisor/shared/external_flash/external_flash.c b/supervisor/shared/external_flash/external_flash.c index 23727e7e70..f8054a9fe0 100644 --- a/supervisor/shared/external_flash/external_flash.c +++ b/supervisor/shared/external_flash/external_flash.c @@ -48,19 +48,19 @@ static uint32_t current_sector; STATIC const external_flash_device possible_devices[] = {EXTERNAL_FLASH_DEVICES}; #define EXTERNAL_FLASH_DEVICE_COUNT MP_ARRAY_SIZE(possible_devices) -static const external_flash_device* flash_device = NULL; +static const external_flash_device *flash_device = NULL; // Track which blocks (up to 32) in the current sector currently live in the // cache. static uint32_t dirty_mask; -static supervisor_allocation* supervisor_cache = NULL; +static supervisor_allocation *supervisor_cache = NULL; // Wait until both the write enable and write in progress bits have cleared. static bool wait_for_flash_ready(void) { bool ok = true; // Both the write enable and write in progress bits should be low. - if (flash_device->no_ready_bit){ + if (flash_device->no_ready_bit) { // For NVM without a ready bit in status register return ok; } @@ -77,7 +77,7 @@ static bool write_enable(void) { } // Read data_length's worth of bytes starting at address into data. -static bool read_flash(uint32_t address, uint8_t* data, uint32_t data_length) { +static bool read_flash(uint32_t address, uint8_t *data, uint32_t data_length) { if (flash_device == NULL) { return false; } @@ -90,13 +90,13 @@ static bool read_flash(uint32_t address, uint8_t* data, uint32_t data_length) { // Writes data_length's worth of bytes starting at address from data. Assumes // that the sector that address resides in has already been erased. So make sure // to run erase_sector. -static bool write_flash(uint32_t address, const uint8_t* data, uint32_t data_length) { +static bool write_flash(uint32_t address, const uint8_t *data, uint32_t data_length) { if (flash_device == NULL) { return false; } // Don't bother writing if the data is all 1s. Thats equivalent to the flash // state after an erase. - if (!flash_device->no_erase_cmd){ + if (!flash_device->no_erase_cmd) { // Only do this if the device has an erase command bool all_ones = true; for (uint16_t i = 0; i < data_length; i++) { @@ -111,14 +111,14 @@ static bool write_flash(uint32_t address, const uint8_t* data, uint32_t data_len } for (uint32_t bytes_written = 0; - bytes_written < data_length; - bytes_written += SPI_FLASH_PAGE_SIZE) { + bytes_written < data_length; + bytes_written += SPI_FLASH_PAGE_SIZE) { if (!wait_for_flash_ready() || !write_enable()) { return false; } - if (!spi_flash_write_data(address + bytes_written, (uint8_t*) data + bytes_written, - SPI_FLASH_PAGE_SIZE)) { + if (!spi_flash_write_data(address + bytes_written, (uint8_t *)data + bytes_written, + SPI_FLASH_PAGE_SIZE)) { return false; } } @@ -128,7 +128,7 @@ static bool write_flash(uint32_t address, const uint8_t* data, uint32_t data_len static bool page_erased(uint32_t sector_address) { // Check the first few bytes to catch the common case where there is data // without using a bunch of memory. - if (flash_device->no_erase_cmd){ + if (flash_device->no_erase_cmd) { // skip this if device doesn't have an erase command. return true; } @@ -162,7 +162,7 @@ static bool page_erased(uint32_t sector_address) { static bool erase_sector(uint32_t sector_address) { // Before we erase the sector we need to wait for any writes to finish and // and then enable the write again. - if (flash_device->no_erase_cmd){ + if (flash_device->no_erase_cmd) { // skip this if device doesn't have an erase command. return true; } @@ -209,33 +209,33 @@ void supervisor_flash_init(void) { spi_flash_init(); -#ifdef EXTERNAL_FLASH_NO_JEDEC + #ifdef EXTERNAL_FLASH_NO_JEDEC // For NVM that don't have JEDEC response spi_flash_command(CMD_WAKE); for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) { - const external_flash_device* possible_device = &possible_devices[i]; + const external_flash_device *possible_device = &possible_devices[i]; flash_device = possible_device; break; } -#else + #else // The response will be 0xff if the flash needs more time to start up. uint8_t jedec_id_response[3] = {0xff, 0xff, 0xff}; while (jedec_id_response[0] == 0xff) { spi_flash_read_command(CMD_READ_JEDEC_ID, jedec_id_response, 3); } - for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) { - const external_flash_device* possible_device = &possible_devices[i]; - if (jedec_id_response[0] == possible_device->manufacturer_id && - jedec_id_response[1] == possible_device->memory_type && - jedec_id_response[2] == possible_device->capacity) { - flash_device = possible_device; - break; - } - } -#endif - if (flash_device == NULL) { - return; + for (uint8_t i = 0; i < EXTERNAL_FLASH_DEVICE_COUNT; i++) { + const external_flash_device *possible_device = &possible_devices[i]; + if (jedec_id_response[0] == possible_device->manufacturer_id && + jedec_id_response[1] == possible_device->memory_type && + jedec_id_response[2] == possible_device->capacity) { + flash_device = possible_device; + break; } + } + #endif + if (flash_device == NULL) { + return; + } // We don't know what state the flash is in so wait for any remaining writes and then reset. uint8_t read_status_response[1] = {0x00}; @@ -250,7 +250,7 @@ void supervisor_flash_init(void) { } while ((read_status_response[0] & 0x80) != 0); } - if (!(flash_device->no_reset_cmd)){ + if (!(flash_device->no_reset_cmd)) { spi_flash_command(CMD_ENABLE_RESET); spi_flash_command(CMD_RESET); } @@ -261,14 +261,14 @@ void supervisor_flash_init(void) { spi_flash_init_device(flash_device); // Activity LED for flash writes. -#ifdef MICROPY_HW_LED_MSC + #ifdef MICROPY_HW_LED_MSC gpio_set_pin_function(SPI_FLASH_CS_PIN, GPIO_PIN_FUNCTION_OFF); gpio_set_pin_direction(MICROPY_HW_LED_MSC, GPIO_DIRECTION_OUT); // There's already a pull-up on the board. gpio_set_pin_level(MICROPY_HW_LED_MSC, false); -#endif + #endif - if (flash_device->has_sector_protection) { + if (flash_device->has_sector_protection) { write_enable(); // Turn off sector protection @@ -312,7 +312,7 @@ static bool flush_scratch_flash(void) { if ((dirty_mask & (1 << i)) == 0) { copy_to_scratch_ok = copy_to_scratch_ok && copy_block(current_sector + i * FILESYSTEM_BLOCK_SIZE, - scratch_sector + i * FILESYSTEM_BLOCK_SIZE); + scratch_sector + i * FILESYSTEM_BLOCK_SIZE); } } if (!copy_to_scratch_ok) { @@ -325,7 +325,7 @@ static bool flush_scratch_flash(void) { // Finally, copy the new version into it. for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) { copy_block(scratch_sector + i * FILESYSTEM_BLOCK_SIZE, - current_sector + i * FILESYSTEM_BLOCK_SIZE); + current_sector + i * FILESYSTEM_BLOCK_SIZE); } return true; } @@ -341,8 +341,8 @@ static bool allocate_ram_cache(void) { // Attempt to allocate outside the heap first. supervisor_cache = allocate_memory(table_size + SPI_FLASH_ERASE_SIZE, false, false); if (supervisor_cache != NULL) { - MP_STATE_VM(flash_ram_cache) = (uint8_t **) supervisor_cache->ptr; - uint8_t* page_start = (uint8_t *) supervisor_cache->ptr + table_size; + MP_STATE_VM(flash_ram_cache) = (uint8_t **)supervisor_cache->ptr; + uint8_t *page_start = (uint8_t *)supervisor_cache->ptr + table_size; for (uint8_t i = 0; i < blocks_per_sector; i++) { for (uint8_t j = 0; j < pages_per_block; j++) { @@ -446,8 +446,8 @@ static bool flush_ram_cache(bool keep_cache) { for (uint8_t i = 0; i < SPI_FLASH_ERASE_SIZE / FILESYSTEM_BLOCK_SIZE; i++) { for (uint8_t j = 0; j < pages_per_block; j++) { write_flash(current_sector + (i * pages_per_block + j) * SPI_FLASH_PAGE_SIZE, - MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j], - SPI_FLASH_PAGE_SIZE); + MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j], + SPI_FLASH_PAGE_SIZE); if (!keep_cache && supervisor_cache == NULL && MP_STATE_MEM(gc_pool_start)) { m_free(MP_STATE_VM(flash_ram_cache)[i * pages_per_block + j]); } @@ -464,7 +464,7 @@ static bool flush_ram_cache(bool keep_cache) { // TODO Don't blink the status indicator if we don't actually do any writing (hard to tell right now). static void spi_flash_flush_keep_cache(bool keep_cache) { #ifdef MICROPY_HW_LED_MSC - port_pin_set_output_level(MICROPY_HW_LED_MSC, true); + port_pin_set_output_level(MICROPY_HW_LED_MSC, true); #endif temp_status_color(ACTIVE_WRITE); // If we've cached to the flash itself flush from there. @@ -476,7 +476,7 @@ static void spi_flash_flush_keep_cache(bool keep_cache) { current_sector = NO_SECTOR_LOADED; clear_temp_status(); #ifdef MICROPY_HW_LED_MSC - port_pin_set_output_level(MICROPY_HW_LED_MSC, false); + port_pin_set_output_level(MICROPY_HW_LED_MSC, false); #endif } @@ -514,8 +514,8 @@ bool external_flash_read_block(uint8_t *dest, uint32_t block) { uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE; for (int i = 0; i < pages_per_block; i++) { memcpy(dest + i * SPI_FLASH_PAGE_SIZE, - MP_STATE_VM(flash_ram_cache)[block_index * pages_per_block + i], - SPI_FLASH_PAGE_SIZE); + MP_STATE_VM(flash_ram_cache)[block_index * pages_per_block + i], + SPI_FLASH_PAGE_SIZE); } return true; } else { @@ -563,8 +563,8 @@ bool external_flash_write_block(const uint8_t *data, uint32_t block) { uint8_t pages_per_block = FILESYSTEM_BLOCK_SIZE / SPI_FLASH_PAGE_SIZE; for (int i = 0; i < pages_per_block; i++) { memcpy(MP_STATE_VM(flash_ram_cache)[block_index * pages_per_block + i], - data + i * SPI_FLASH_PAGE_SIZE, - SPI_FLASH_PAGE_SIZE); + data + i * SPI_FLASH_PAGE_SIZE, + SPI_FLASH_PAGE_SIZE); } return true; } else { diff --git a/supervisor/shared/external_flash/external_flash_root_pointers.h b/supervisor/shared/external_flash/external_flash_root_pointers.h index cb1b86d193..0613c9a57d 100644 --- a/supervisor/shared/external_flash/external_flash_root_pointers.h +++ b/supervisor/shared/external_flash/external_flash_root_pointers.h @@ -30,6 +30,6 @@ // We use this when we can allocate the whole cache in RAM. #define FLASH_ROOT_POINTERS \ - uint8_t** flash_ram_cache; \ + uint8_t **flash_ram_cache; \ #endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_EXTERNAL_FLASH_ROOT_POINTERS_H diff --git a/supervisor/shared/external_flash/qspi_flash.c b/supervisor/shared/external_flash/qspi_flash.c index 48266540c4..dc16f3465b 100644 --- a/supervisor/shared/external_flash/qspi_flash.c +++ b/supervisor/shared/external_flash/qspi_flash.c @@ -28,7 +28,7 @@ #include "supervisor/shared/external_flash/common_commands.h" -void check_quad_enable(const external_flash_device* device) { +void check_quad_enable(const external_flash_device *device) { if (device->quad_enable_bit_mask == 0x00) { return; } diff --git a/supervisor/shared/external_flash/qspi_flash.h b/supervisor/shared/external_flash/qspi_flash.h index b72e37b268..c0c089ee0f 100644 --- a/supervisor/shared/external_flash/qspi_flash.h +++ b/supervisor/shared/external_flash/qspi_flash.h @@ -26,6 +26,6 @@ #ifndef MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_QSPI_FLASH_H #define MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_QSPI_FLASH_H -void check_quad_enable(const external_flash_device* device); +void check_quad_enable(const external_flash_device *device); #endif // MICROPY_INCLUDED_SUPERVISOR_SHARED_EXTERNAL_FLASH_QSPI_FLASH_H diff --git a/supervisor/shared/external_flash/spi_flash.c b/supervisor/shared/external_flash/spi_flash.c index 67e64c970e..3ddd92b5ed 100644 --- a/supervisor/shared/external_flash/spi_flash.c +++ b/supervisor/shared/external_flash/spi_flash.c @@ -38,12 +38,13 @@ digitalio_digitalinout_obj_t cs_pin; busio_spi_obj_t supervisor_flash_spi_bus; -const external_flash_device* flash_device; +const external_flash_device *flash_device; uint32_t spi_flash_baudrate; // Enable the flash over SPI. static void flash_enable(void) { - while (!common_hal_busio_spi_try_lock(&supervisor_flash_spi_bus)) {} + while (!common_hal_busio_spi_try_lock(&supervisor_flash_spi_bus)) { + } common_hal_digitalio_digitalinout_set_value(&cs_pin, false); } @@ -53,7 +54,7 @@ static void flash_disable(void) { common_hal_busio_spi_unlock(&supervisor_flash_spi_bus); } -static bool transfer(uint8_t* command, uint32_t command_length, uint8_t* data_in, uint8_t* data_out, uint32_t data_length) { +static bool transfer(uint8_t *command, uint32_t command_length, uint8_t *data_in, uint8_t *data_out, uint32_t data_length) { flash_enable(); bool status = common_hal_busio_spi_write(&supervisor_flash_spi_bus, command, command_length); if (status) { @@ -69,7 +70,7 @@ static bool transfer(uint8_t* command, uint32_t command_length, uint8_t* data_in return status; } -static bool transfer_command(uint8_t command, uint8_t* data_in, uint8_t* data_out, uint32_t data_length) { +static bool transfer_command(uint8_t command, uint8_t *data_in, uint8_t *data_out, uint32_t data_length) { return transfer(&command, 1, data_in, data_out, data_length); } @@ -77,16 +78,16 @@ bool spi_flash_command(uint8_t command) { return transfer_command(command, NULL, NULL, 0); } -bool spi_flash_read_command(uint8_t command, uint8_t* data, uint32_t data_length) { +bool spi_flash_read_command(uint8_t command, uint8_t *data, uint32_t data_length) { return transfer_command(command, NULL, data, data_length); } -bool spi_flash_write_command(uint8_t command, uint8_t* data, uint32_t data_length) { +bool spi_flash_write_command(uint8_t command, uint8_t *data, uint32_t data_length) { return transfer_command(command, data, NULL, data_length); } // Pack the low 24 bits of the address into a uint8_t array. -static void address_to_bytes(uint32_t address, uint8_t* bytes) { +static void address_to_bytes(uint32_t address, uint8_t *bytes) { bytes[0] = (address >> 16) & 0xff; bytes[1] = (address >> 8) & 0xff; bytes[2] = address & 0xff; @@ -98,7 +99,7 @@ bool spi_flash_sector_command(uint8_t command, uint32_t address) { return transfer(request, 4, NULL, NULL, 0); } -bool spi_flash_write_data(uint32_t address, uint8_t* data, uint32_t data_length) { +bool spi_flash_write_data(uint32_t address, uint8_t *data, uint32_t data_length) { uint8_t request[4] = {CMD_PAGE_PROGRAM, 0x00, 0x00, 0x00}; // Write the SPI flash write address into the bytes following the command byte. address_to_bytes(address, request + 1); @@ -112,7 +113,7 @@ bool spi_flash_write_data(uint32_t address, uint8_t* data, uint32_t data_length) return status; } -bool spi_flash_read_data(uint32_t address, uint8_t* data, uint32_t data_length) { +bool spi_flash_read_data(uint32_t address, uint8_t *data, uint32_t data_length) { uint8_t request[5] = {CMD_READ_DATA, 0x00, 0x00, 0x00}; uint8_t command_length = 4; if (flash_device->supports_fast_read) { @@ -145,7 +146,7 @@ void spi_flash_init(void) { common_hal_busio_spi_never_reset(&supervisor_flash_spi_bus); } -void spi_flash_init_device(const external_flash_device* device) { +void spi_flash_init_device(const external_flash_device *device) { flash_device = device; spi_flash_baudrate = device->max_clock_speed_mhz * 1000000; if (spi_flash_baudrate > SPI_FLASH_MAX_BAUDRATE) { diff --git a/supervisor/shared/filesystem.c b/supervisor/shared/filesystem.c index 09b30b6bad..874f258217 100644 --- a/supervisor/shared/filesystem.c +++ b/supervisor/shared/filesystem.c @@ -75,7 +75,7 @@ static void make_sample_code_file(FATFS *fatfs) { FIL fs; UINT char_written = 0; const byte buffer[] = "print(\"Hello World!\")\n"; - //Create or modify existing code.py file + // Create or modify existing code.py file f_open(fatfs, &fs, "/code.py", FA_WRITE | FA_CREATE_ALWAYS); f_write(&fs, buffer, sizeof(buffer) - 1, &char_written); f_close(&fs); @@ -106,11 +106,11 @@ void filesystem_init(bool create_allowed, bool force_create) { } // set label -#ifdef CIRCUITPY_DRIVE_LABEL + #ifdef CIRCUITPY_DRIVE_LABEL res = f_setlabel(&vfs_fat->fatfs, CIRCUITPY_DRIVE_LABEL); -#else + #else res = f_setlabel(&vfs_fat->fatfs, "CIRCUITPY"); -#endif + #endif if (res != FR_OK) { return; } diff --git a/supervisor/shared/flash.c b/supervisor/shared/flash.c index 1e09fe14b3..33314adf1a 100644 --- a/supervisor/shared/flash.c +++ b/supervisor/shared/flash.c @@ -160,7 +160,7 @@ STATIC mp_obj_t supervisor_flash_obj_writeblocks(mp_obj_t self, mp_obj_t block_n } STATIC MP_DEFINE_CONST_FUN_OBJ_3(supervisor_flash_obj_writeblocks_obj, supervisor_flash_obj_writeblocks); -bool flash_ioctl(size_t cmd, mp_int_t* out_value) { +bool flash_ioctl(size_t cmd, mp_int_t *out_value) { *out_value = 0; switch (cmd) { case BP_IOCTL_INIT: diff --git a/supervisor/shared/memory.c b/supervisor/shared/memory.c old mode 100755 new mode 100644 index 480c322b01..83c9d63236 --- a/supervisor/shared/memory.c +++ b/supervisor/shared/memory.c @@ -34,32 +34,32 @@ enum { CIRCUITPY_SUPERVISOR_IMMOVABLE_ALLOC_COUNT = - // stack + heap - 2 -#ifdef EXTERNAL_FLASH_DEVICES - + 1 -#endif -#if CIRCUITPY_USB_MIDI - + 1 -#endif + // stack + heap + 2 + #ifdef EXTERNAL_FLASH_DEVICES + + 1 + #endif + #if CIRCUITPY_USB_MIDI + + 1 + #endif , CIRCUITPY_SUPERVISOR_MOVABLE_ALLOC_COUNT = - 0 -#if CIRCUITPY_DISPLAYIO - #if CIRCUITPY_TERMINALIO + 0 + #if CIRCUITPY_DISPLAYIO + #if CIRCUITPY_TERMINALIO + 1 - #endif - + CIRCUITPY_DISPLAY_LIMIT * ( - // Maximum needs of one display: max(4 if RGBMATRIX, 1 if SHARPDISPLAY, 0) - #if CIRCUITPY_RGBMATRIX - 4 - #elif CIRCUITPY_SHARPDISPLAY - 1 - #else - 0 #endif - ) -#endif + + CIRCUITPY_DISPLAY_LIMIT * ( + // Maximum needs of one display: max(4 if RGBMATRIX, 1 if SHARPDISPLAY, 0) + #if CIRCUITPY_RGBMATRIX + 4 + #elif CIRCUITPY_SHARPDISPLAY + 1 + #else + 0 + #endif + ) + #endif , CIRCUITPY_SUPERVISOR_ALLOC_COUNT = CIRCUITPY_SUPERVISOR_IMMOVABLE_ALLOC_COUNT + CIRCUITPY_SUPERVISOR_MOVABLE_ALLOC_COUNT }; @@ -71,40 +71,38 @@ enum { #define MOVABLE 2 static supervisor_allocation allocations[CIRCUITPY_SUPERVISOR_ALLOC_COUNT]; -supervisor_allocation* old_allocations; +supervisor_allocation *old_allocations; typedef struct _supervisor_allocation_node { - struct _supervisor_allocation_node* next; + struct _supervisor_allocation_node *next; size_t length; // We use uint32_t to ensure word (4 byte) alignment. uint32_t data[]; } supervisor_allocation_node; -supervisor_allocation_node* low_head; -supervisor_allocation_node* high_head; +supervisor_allocation_node *low_head; +supervisor_allocation_node *high_head; // Intermediate (void*) is to suppress -Wcast-align warning. Alignment will always be correct // because this only reverses how (alloc)->ptr was obtained as &(node->data[0]). -#define ALLOCATION_NODE(alloc) ((supervisor_allocation_node*)(void*)((char*)((alloc)->ptr) - sizeof(supervisor_allocation_node))) +#define ALLOCATION_NODE(alloc) ((supervisor_allocation_node *)(void *)((char *)((alloc)->ptr) - sizeof(supervisor_allocation_node))) -void free_memory(supervisor_allocation* allocation) { +void free_memory(supervisor_allocation *allocation) { if (allocation == NULL || allocation->ptr == NULL) { return; } - supervisor_allocation_node* node = ALLOCATION_NODE(allocation); + supervisor_allocation_node *node = ALLOCATION_NODE(allocation); if (node == low_head) { do { low_head = low_head->next; } while (low_head != NULL && (low_head->length & HOLE)); - } - else if (node == high_head) { + } else if (node == high_head) { do { high_head = high_head->next; } while (high_head != NULL && (high_head->length & HOLE)); - } - else { + } else { // Check if it's in the list of embedded allocations. - supervisor_allocation_node** emb = &MP_STATE_VM(first_embedded_allocation); + supervisor_allocation_node **emb = &MP_STATE_VM(first_embedded_allocation); while (*emb != NULL && *emb != node) { emb = &((*emb)->next); } @@ -112,12 +110,11 @@ void free_memory(supervisor_allocation* allocation) { // Found, remove it from the list. *emb = node->next; m_free(node -#if MICROPY_MALLOC_USES_ALLOCATED_SIZE + #if MICROPY_MALLOC_USES_ALLOCATED_SIZE , sizeof(supervisor_allocation_node) + (node->length & ~FLAGS) -#endif - ); - } - else { + #endif + ); + } else { // Else it must be within the low or high ranges and becomes a hole. node->length = ((node->length & ~FLAGS) | HOLE); } @@ -125,11 +122,11 @@ void free_memory(supervisor_allocation* allocation) { allocation->ptr = NULL; } -supervisor_allocation* allocation_from_ptr(void *ptr) { +supervisor_allocation *allocation_from_ptr(void *ptr) { // When called from the context of supervisor_move_memory() (old_allocations != NULL), search // by old pointer to give clients a way of mapping from old to new pointer. But not if // ptr == NULL, then the caller wants an allocation whose current ptr is NULL. - supervisor_allocation* list = (old_allocations && ptr) ? old_allocations : &allocations[0]; + supervisor_allocation *list = (old_allocations && ptr) ? old_allocations : &allocations[0]; for (size_t index = 0; index < CIRCUITPY_SUPERVISOR_ALLOC_COUNT; index++) { if (list[index].ptr == ptr) { return &allocations[index]; @@ -138,11 +135,11 @@ supervisor_allocation* allocation_from_ptr(void *ptr) { return NULL; } -supervisor_allocation* allocate_remaining_memory(void) { +supervisor_allocation *allocate_remaining_memory(void) { return allocate_memory((uint32_t)-1, false, false); } -static supervisor_allocation_node* find_hole(supervisor_allocation_node* node, size_t length) { +static supervisor_allocation_node *find_hole(supervisor_allocation_node *node, size_t length) { for (; node != NULL; node = node->next) { if (node->length == (length | HOLE)) { break; @@ -151,15 +148,15 @@ static supervisor_allocation_node* find_hole(supervisor_allocation_node* node, s return node; } -static supervisor_allocation_node* allocate_memory_node(uint32_t length, bool high, bool movable) { +static supervisor_allocation_node *allocate_memory_node(uint32_t length, bool high, bool movable) { if (CIRCUITPY_SUPERVISOR_MOVABLE_ALLOC_COUNT == 0) { assert(!movable); } // supervisor_move_memory() currently does not support movable allocations on the high side, it // must be extended first if this is ever needed. assert(!(high && movable)); - uint32_t* low_address = low_head ? low_head->data + low_head->length / 4 : port_heap_get_bottom(); - uint32_t* high_address = high_head ? (uint32_t*)high_head : port_heap_get_top(); + uint32_t *low_address = low_head ? low_head->data + low_head->length / 4 : port_heap_get_bottom(); + uint32_t *high_address = high_head ? (uint32_t *)high_head : port_heap_get_top(); // Special case for allocate_remaining_memory(), avoids computing low/high_address twice. if (length == (uint32_t)-1) { length = (high_address - low_address) * 4 - sizeof(supervisor_allocation_node); @@ -168,23 +165,21 @@ static supervisor_allocation_node* allocate_memory_node(uint32_t length, bool hi return NULL; } // 1. Matching hole on the requested side? - supervisor_allocation_node* node = find_hole(high ? high_head : low_head, length); + supervisor_allocation_node *node = find_hole(high ? high_head : low_head, length); if (!node) { // 2. Enough free space in the middle? if ((high_address - low_address) * 4 >= (int32_t)(sizeof(supervisor_allocation_node) + length)) { if (high) { high_address -= (sizeof(supervisor_allocation_node) + length) / 4; - node = (supervisor_allocation_node*)high_address; + node = (supervisor_allocation_node *)high_address; node->next = high_head; high_head = node; - } - else { - node = (supervisor_allocation_node*)low_address; + } else { + node = (supervisor_allocation_node *)low_address; node->next = low_head; low_head = node; } - } - else { + } else { // 3. Matching hole on the other side? node = find_hole(high ? low_head : high_head, length); if (!node) { @@ -210,13 +205,13 @@ static supervisor_allocation_node* allocate_memory_node(uint32_t length, bool hi return node; } -supervisor_allocation* allocate_memory(uint32_t length, bool high, bool movable) { - supervisor_allocation_node* node = allocate_memory_node(length, high, movable); +supervisor_allocation *allocate_memory(uint32_t length, bool high, bool movable) { + supervisor_allocation_node *node = allocate_memory_node(length, high, movable); if (!node) { return NULL; } // Find the first free allocation. - supervisor_allocation* alloc = allocation_from_ptr(NULL); + supervisor_allocation *alloc = allocation_from_ptr(NULL); if (!alloc) { // We should free node again to avoid leaking, but something is wrong anyway if clients try // to make more allocations than available, so don't bother. @@ -226,7 +221,7 @@ supervisor_allocation* allocate_memory(uint32_t length, bool high, bool movable) return alloc; } -size_t get_allocation_length(supervisor_allocation* allocation) { +size_t get_allocation_length(supervisor_allocation *allocation) { return ALLOCATION_NODE(allocation)->length & ~FLAGS; } @@ -250,19 +245,19 @@ void supervisor_move_memory(void) { bool acted; do { acted = false; - supervisor_allocation_node** nodep = &low_head; + supervisor_allocation_node **nodep = &low_head; while (*nodep != NULL && (*nodep)->next != NULL) { if (((*nodep)->length & MOVABLE) && ((*nodep)->next->length & HOLE)) { - supervisor_allocation_node* oldnode = *nodep; - supervisor_allocation_node* start = oldnode->next; - supervisor_allocation* alloc = allocation_from_ptr(&(oldnode->data[0])); + supervisor_allocation_node *oldnode = *nodep; + supervisor_allocation_node *start = oldnode->next; + supervisor_allocation *alloc = allocation_from_ptr(&(oldnode->data[0])); assert(alloc != NULL); alloc->ptr = &(start->data[0]); oldnode->next = start->next; size_t holelength = start->length; size_t size = sizeof(supervisor_allocation_node) + (oldnode->length & ~FLAGS); memmove(start, oldnode, size); - supervisor_allocation_node* newhole = (supervisor_allocation_node*)(void*)((char*)start + size); + supervisor_allocation_node *newhole = (supervisor_allocation_node *)(void *)((char *)start + size); newhole->next = start; newhole->length = holelength; *nodep = newhole; @@ -274,7 +269,8 @@ void supervisor_move_memory(void) { // Any holes bubbled to the top can be absorbed into the free middle. while (low_head != NULL && (low_head->length & HOLE)) { low_head = low_head->next; - }; + } + ; // Don't bother compacting the high side, there are no movable allocations and no holes there in // current usage. @@ -287,23 +283,23 @@ void supervisor_move_memory(void) { // code than using the qsort() function from the C library. while (MP_STATE_VM(first_embedded_allocation)) { // First element is first candidate. - supervisor_allocation_node** pminnode = &MP_STATE_VM(first_embedded_allocation); + supervisor_allocation_node **pminnode = &MP_STATE_VM(first_embedded_allocation); // Iterate from second element (if any) on. - for (supervisor_allocation_node** pnode = &(MP_STATE_VM(first_embedded_allocation)->next); *pnode != NULL; pnode = &(*pnode)->next) { + for (supervisor_allocation_node **pnode = &(MP_STATE_VM(first_embedded_allocation)->next); *pnode != NULL; pnode = &(*pnode)->next) { if (*pnode < *pminnode) { pminnode = pnode; } } // Remove from list. - supervisor_allocation_node* node = *pminnode; + supervisor_allocation_node *node = *pminnode; *pminnode = node->next; // Process. size_t length = (node->length & ~FLAGS); - supervisor_allocation* alloc = allocation_from_ptr(&(node->data[0])); + supervisor_allocation *alloc = allocation_from_ptr(&(node->data[0])); assert(alloc != NULL); // This may overwrite the header of node if it happened to be there already, but not the // data. - supervisor_allocation_node* new_node = allocate_memory_node(length, false, true); + supervisor_allocation_node *new_node = allocate_memory_node(length, false, true); // There must be enough free space. assert(new_node != NULL); memmove(&(new_node->data[0]), &(node->data[0]), length); diff --git a/supervisor/shared/micropython.c b/supervisor/shared/micropython.c index bbc4807f97..c68c4bf7e9 100644 --- a/supervisor/shared/micropython.c +++ b/supervisor/shared/micropython.c @@ -44,7 +44,7 @@ int mp_hal_stdin_rx_chr(void) { for (;;) { #ifdef MICROPY_VM_HOOK_LOOP - MICROPY_VM_HOOK_LOOP + MICROPY_VM_HOOK_LOOP #endif mp_handle_pending(); if (serial_bytes_available()) { diff --git a/supervisor/shared/rgb_led_colors.h b/supervisor/shared/rgb_led_colors.h index c723fbab36..581c177442 100644 --- a/supervisor/shared/rgb_led_colors.h +++ b/supervisor/shared/rgb_led_colors.h @@ -9,7 +9,7 @@ #define BLUE COLOR(0, 0, INTENSITY) #define CYAN COLOR(0, INTENSITY, INTENSITY) #define RED COLOR(INTENSITY, 0, 0) -#define ORANGE COLOR(INTENSITY, INTENSITY*2/3, 0) +#define ORANGE COLOR(INTENSITY, INTENSITY * 2 / 3, 0) #define YELLOW COLOR(INTENSITY, INTENSITY, 0) #define PURPLE COLOR(INTENSITY, 0, INTENSITY) #define WHITE COLOR(INTENSITY, INTENSITY, INTENSITY) diff --git a/supervisor/shared/rgb_led_status.c b/supervisor/shared/rgb_led_status.c index 60470e057e..d6e11c2aef 100644 --- a/supervisor/shared/rgb_led_status.c +++ b/supervisor/shared/rgb_led_status.c @@ -104,43 +104,43 @@ void rgb_led_status_init() { rgb_led_status_init_in_progress = true; #ifdef MICROPY_HW_NEOPIXEL - common_hal_digitalio_digitalinout_construct(&status_neopixel, MICROPY_HW_NEOPIXEL); - // Pretend we aren't using the pins. digitalio.DigitalInOut - // will mark them as used. - neopixel_in_use = false; - common_hal_digitalio_digitalinout_switch_to_output(&status_neopixel, false, DRIVE_MODE_PUSH_PULL); + common_hal_digitalio_digitalinout_construct(&status_neopixel, MICROPY_HW_NEOPIXEL); + // Pretend we aren't using the pins. digitalio.DigitalInOut + // will mark them as used. + neopixel_in_use = false; + common_hal_digitalio_digitalinout_switch_to_output(&status_neopixel, false, DRIVE_MODE_PUSH_PULL); #endif #if defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) - #if CIRCUITPY_BITBANG_APA102 - shared_module_bitbangio_spi_construct(&status_apa102, - MICROPY_HW_APA102_SCK, - MICROPY_HW_APA102_MOSI, - NULL); - #else - if (!common_hal_busio_spi_deinited(&status_apa102)) { - // This may call us recursively if common_hal_reset_pin() is called, - // The rgb_led_status_init_in_progress guard will prevent further recursion. - common_hal_busio_spi_deinit(&status_apa102); - } - common_hal_busio_spi_construct(&status_apa102, - MICROPY_HW_APA102_SCK, - MICROPY_HW_APA102_MOSI, - NULL); - common_hal_busio_spi_never_reset(&status_apa102); - #endif - // Pretend we aren't using the pins. bitbangio.SPI will - // mark them as used. - apa102_mosi_in_use = false; - apa102_sck_in_use = false; - #if CIRCUITPY_BITBANG_APA102 - shared_module_bitbangio_spi_try_lock(&status_apa102); - // Use 1MHz for clock rate. Some APA102's are spec'd 800kHz-1200kHz, - // though many can run much faster. bitbang will probably run slower. - shared_module_bitbangio_spi_configure(&status_apa102, 1000000, 0, 0, 8); - #else - common_hal_busio_spi_try_lock(&status_apa102); - common_hal_busio_spi_configure(&status_apa102, 1000000, 0, 0, 8); - #endif + #if CIRCUITPY_BITBANG_APA102 + shared_module_bitbangio_spi_construct(&status_apa102, + MICROPY_HW_APA102_SCK, + MICROPY_HW_APA102_MOSI, + NULL); + #else + if (!common_hal_busio_spi_deinited(&status_apa102)) { + // This may call us recursively if common_hal_reset_pin() is called, + // The rgb_led_status_init_in_progress guard will prevent further recursion. + common_hal_busio_spi_deinit(&status_apa102); + } + common_hal_busio_spi_construct(&status_apa102, + MICROPY_HW_APA102_SCK, + MICROPY_HW_APA102_MOSI, + NULL); + common_hal_busio_spi_never_reset(&status_apa102); + #endif + // Pretend we aren't using the pins. bitbangio.SPI will + // mark them as used. + apa102_mosi_in_use = false; + apa102_sck_in_use = false; + #if CIRCUITPY_BITBANG_APA102 + shared_module_bitbangio_spi_try_lock(&status_apa102); + // Use 1MHz for clock rate. Some APA102's are spec'd 800kHz-1200kHz, + // though many can run much faster. bitbang will probably run slower. + shared_module_bitbangio_spi_configure(&status_apa102, 1000000, 0, 0, 8); + #else + common_hal_busio_spi_try_lock(&status_apa102); + common_hal_busio_spi_configure(&status_apa102, 1000000, 0, 0, 8); + #endif #endif @@ -182,14 +182,14 @@ void rgb_led_status_init() { void reset_status_led() { #ifdef MICROPY_HW_NEOPIXEL - common_hal_reset_pin(MICROPY_HW_NEOPIXEL); + common_hal_reset_pin(MICROPY_HW_NEOPIXEL); #endif #if defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) - common_hal_reset_pin(MICROPY_HW_APA102_MOSI); - common_hal_reset_pin(MICROPY_HW_APA102_SCK); + common_hal_reset_pin(MICROPY_HW_APA102_MOSI); + common_hal_reset_pin(MICROPY_HW_APA102_SCK); #endif #if defined(CP_RGB_STATUS_LED) - // TODO: Support sharing status LED with user. + // TODO: Support sharing status LED with user. #endif } @@ -203,132 +203,132 @@ void new_status_color(uint32_t rgb) { #endif #ifdef MICROPY_HW_NEOPIXEL - if (neopixel_in_use) { - return; - } - status_neopixel_color[0] = (rgb_adjusted >> 8) & 0xff; - status_neopixel_color[1] = (rgb_adjusted >> 16) & 0xff; - status_neopixel_color[2] = rgb_adjusted & 0xff; - common_hal_neopixel_write(&status_neopixel, status_neopixel_color, 3); + if (neopixel_in_use) { + return; + } + status_neopixel_color[0] = (rgb_adjusted >> 8) & 0xff; + status_neopixel_color[1] = (rgb_adjusted >> 16) & 0xff; + status_neopixel_color[2] = rgb_adjusted & 0xff; + common_hal_neopixel_write(&status_neopixel, status_neopixel_color, 3); #endif #if defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) - if (apa102_mosi_in_use || apa102_sck_in_use) { - return; - } - status_apa102_color[5] = rgb_adjusted & 0xff; - status_apa102_color[6] = (rgb_adjusted >> 8) & 0xff; - status_apa102_color[7] = (rgb_adjusted >> 16) & 0xff; + if (apa102_mosi_in_use || apa102_sck_in_use) { + return; + } + status_apa102_color[5] = rgb_adjusted & 0xff; + status_apa102_color[6] = (rgb_adjusted >> 8) & 0xff; + status_apa102_color[7] = (rgb_adjusted >> 16) & 0xff; - #if CIRCUITPY_BITBANG_APA102 - shared_module_bitbangio_spi_write(&status_apa102, status_apa102_color, APA102_BUFFER_LENGTH); - #else - common_hal_busio_spi_write(&status_apa102, status_apa102_color, APA102_BUFFER_LENGTH); - #endif + #if CIRCUITPY_BITBANG_APA102 + shared_module_bitbangio_spi_write(&status_apa102, status_apa102_color, APA102_BUFFER_LENGTH); + #else + common_hal_busio_spi_write(&status_apa102, status_apa102_color, APA102_BUFFER_LENGTH); + #endif #endif #if defined(CP_RGB_STATUS_LED) - uint8_t red_u8 = (rgb_adjusted >> 16) & 0xFF; - uint8_t green_u8 = (rgb_adjusted >> 8) & 0xFF; - uint8_t blue_u8 = rgb_adjusted & 0xFF; + uint8_t red_u8 = (rgb_adjusted >> 16) & 0xFF; + uint8_t green_u8 = (rgb_adjusted >> 8) & 0xFF; + uint8_t blue_u8 = rgb_adjusted & 0xFF; - #if defined(CP_RGB_STATUS_INVERTED_PWM) - status_rgb_color[0] = (1 << 16) - 1 - ((uint16_t) (red_u8 << 8) + red_u8); - status_rgb_color[1] = (1 << 16) - 1 - ((uint16_t) (green_u8 << 8) + green_u8); - status_rgb_color[2] = (1 << 16) - 1 - ((uint16_t) (blue_u8 << 8) + blue_u8); + #if defined(CP_RGB_STATUS_INVERTED_PWM) + status_rgb_color[0] = (1 << 16) - 1 - ((uint16_t)(red_u8 << 8) + red_u8); + status_rgb_color[1] = (1 << 16) - 1 - ((uint16_t)(green_u8 << 8) + green_u8); + status_rgb_color[2] = (1 << 16) - 1 - ((uint16_t)(blue_u8 << 8) + blue_u8); #else - status_rgb_color[0] = (uint16_t) (red_u8 << 8) + red_u8; - status_rgb_color[1] = (uint16_t) (green_u8 << 8) + green_u8; - status_rgb_color[2] = (uint16_t) (blue_u8 << 8) + blue_u8; - #endif + status_rgb_color[0] = (uint16_t)(red_u8 << 8) + red_u8; + status_rgb_color[1] = (uint16_t)(green_u8 << 8) + green_u8; + status_rgb_color[2] = (uint16_t)(blue_u8 << 8) + blue_u8; + #endif - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_r, status_rgb_color[0]); - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_g, status_rgb_color[1]); - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_b, status_rgb_color[2]); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_r, status_rgb_color[0]); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_g, status_rgb_color[1]); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_b, status_rgb_color[2]); #endif } void temp_status_color(uint32_t rgb) { #if defined(MICROPY_HW_NEOPIXEL) || (defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK)) || (defined(CP_RGB_STATUS_LED)) - uint32_t rgb_adjusted = rgb; - rgb_adjusted = color_brightness(rgb, rgb_status_brightness); + uint32_t rgb_adjusted = rgb; + rgb_adjusted = color_brightness(rgb, rgb_status_brightness); #endif #ifdef MICROPY_HW_NEOPIXEL - if (neopixel_in_use) { - return; - } - uint8_t colors[3] = {(rgb_adjusted >> 8) & 0xff, (rgb_adjusted >> 16) & 0xff, rgb_adjusted & 0xff}; - common_hal_neopixel_write(&status_neopixel, colors, 3); + if (neopixel_in_use) { + return; + } + uint8_t colors[3] = {(rgb_adjusted >> 8) & 0xff, (rgb_adjusted >> 16) & 0xff, rgb_adjusted & 0xff}; + common_hal_neopixel_write(&status_neopixel, colors, 3); #endif #if defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) - if (apa102_mosi_in_use || apa102_sck_in_use) { - return; - } - uint8_t colors[APA102_BUFFER_LENGTH] = {0, 0, 0, 0, 0xff, rgb_adjusted & 0xff, (rgb_adjusted >> 8) & 0xff, (rgb_adjusted >> 16) & 0xff, 0xff, 0xff, 0xff, 0xff}; - #if CIRCUITPY_BITBANG_APA102 - shared_module_bitbangio_spi_write(&status_apa102, colors, APA102_BUFFER_LENGTH); - #else - common_hal_busio_spi_write(&status_apa102, colors, APA102_BUFFER_LENGTH); - #endif + if (apa102_mosi_in_use || apa102_sck_in_use) { + return; + } + uint8_t colors[APA102_BUFFER_LENGTH] = {0, 0, 0, 0, 0xff, rgb_adjusted & 0xff, (rgb_adjusted >> 8) & 0xff, (rgb_adjusted >> 16) & 0xff, 0xff, 0xff, 0xff, 0xff}; + #if CIRCUITPY_BITBANG_APA102 + shared_module_bitbangio_spi_write(&status_apa102, colors, APA102_BUFFER_LENGTH); + #else + common_hal_busio_spi_write(&status_apa102, colors, APA102_BUFFER_LENGTH); + #endif #endif #if defined(CP_RGB_STATUS_LED) - uint8_t red_u8 = (rgb_adjusted >> 16) & 0xFF; - uint8_t green_u8 = (rgb_adjusted >> 8) & 0xFF; - uint8_t blue_u8 = rgb_adjusted & 0xFF; + uint8_t red_u8 = (rgb_adjusted >> 16) & 0xFF; + uint8_t green_u8 = (rgb_adjusted >> 8) & 0xFF; + uint8_t blue_u8 = rgb_adjusted & 0xFF; - uint16_t temp_status_color_rgb[3] = {0}; + uint16_t temp_status_color_rgb[3] = {0}; - #if defined(CP_RGB_STATUS_INVERTED_PWM) - temp_status_color_rgb[0] = (1 << 16) - 1 - ((uint16_t) (red_u8 << 8) + red_u8); - temp_status_color_rgb[1] = (1 << 16) - 1 - ((uint16_t) (green_u8 << 8) + green_u8); - temp_status_color_rgb[2] = (1 << 16) - 1 - ((uint16_t) (blue_u8 << 8) + blue_u8); - #else - temp_status_color_rgb[0] = (uint16_t) (red_u8 << 8) + red_u8; - temp_status_color_rgb[1] = (uint16_t) (green_u8 << 8) + green_u8; - temp_status_color_rgb[2] = (uint16_t) (blue_u8 << 8) + blue_u8; + #if defined(CP_RGB_STATUS_INVERTED_PWM) + temp_status_color_rgb[0] = (1 << 16) - 1 - ((uint16_t)(red_u8 << 8) + red_u8); + temp_status_color_rgb[1] = (1 << 16) - 1 - ((uint16_t)(green_u8 << 8) + green_u8); + temp_status_color_rgb[2] = (1 << 16) - 1 - ((uint16_t)(blue_u8 << 8) + blue_u8); + #else + temp_status_color_rgb[0] = (uint16_t)(red_u8 << 8) + red_u8; + temp_status_color_rgb[1] = (uint16_t)(green_u8 << 8) + green_u8; + temp_status_color_rgb[2] = (uint16_t)(blue_u8 << 8) + blue_u8; #endif - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_r, temp_status_color_rgb[0]); - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_g, temp_status_color_rgb[1]); - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_b, temp_status_color_rgb[2]); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_r, temp_status_color_rgb[0]); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_g, temp_status_color_rgb[1]); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_b, temp_status_color_rgb[2]); #endif } void clear_temp_status() { #ifdef MICROPY_HW_NEOPIXEL - if (neopixel_in_use) { - return; - } - common_hal_neopixel_write(&status_neopixel, status_neopixel_color, 3); + if (neopixel_in_use) { + return; + } + common_hal_neopixel_write(&status_neopixel, status_neopixel_color, 3); #endif #if defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) - if (apa102_mosi_in_use || apa102_sck_in_use) { - return; - } - #if CIRCUITPY_BITBANG_APA102 - shared_module_bitbangio_spi_write(&status_apa102, status_apa102_color, APA102_BUFFER_LENGTH); - #else - common_hal_busio_spi_write(&status_apa102, status_apa102_color, APA102_BUFFER_LENGTH); - #endif + if (apa102_mosi_in_use || apa102_sck_in_use) { + return; + } + #if CIRCUITPY_BITBANG_APA102 + shared_module_bitbangio_spi_write(&status_apa102, status_apa102_color, APA102_BUFFER_LENGTH); + #else + common_hal_busio_spi_write(&status_apa102, status_apa102_color, APA102_BUFFER_LENGTH); + #endif #endif #if defined(CP_RGB_STATUS_LED) - uint16_t red = 0; - uint16_t green = 0; - uint16_t blue = 0; + uint16_t red = 0; + uint16_t green = 0; + uint16_t blue = 0; - #if defined(CP_RGB_STATUS_INVERTED_PWM) - red = (1 << 16) - 1 - status_rgb_color[0]; - green = (1 << 16) - 1 - status_rgb_color[1]; - blue = (1 << 16) - 1 - status_rgb_color[2]; - #else - red = status_rgb_color[0]; - green = status_rgb_color[1]; - blue = status_rgb_color[2]; - #endif + #if defined(CP_RGB_STATUS_INVERTED_PWM) + red = (1 << 16) - 1 - status_rgb_color[0]; + green = (1 << 16) - 1 - status_rgb_color[1]; + blue = (1 << 16) - 1 - status_rgb_color[2]; + #else + red = status_rgb_color[0]; + green = status_rgb_color[1]; + blue = status_rgb_color[2]; + #endif - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_r, red); - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_g, green); - common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_b, blue); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_r, red); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_g, green); + common_hal_pwmio_pwmout_set_duty_cycle(&rgb_status_b, blue); #endif } @@ -343,7 +343,7 @@ uint32_t color_brightness(uint32_t color, uint8_t brightness) { #endif } -void set_rgb_status_brightness(uint8_t level){ +void set_rgb_status_brightness(uint8_t level) { #if defined(MICROPY_HW_NEOPIXEL) || (defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK)) || (defined(CP_RGB_STATUS_LED)) rgb_status_brightness = level; uint32_t current_color = current_status_color; @@ -355,10 +355,10 @@ void set_rgb_status_brightness(uint8_t level){ #endif } -void prep_rgb_status_animation(const pyexec_result_t* result, - bool found_main, - safe_mode_t safe_mode, - rgb_status_animation_t* status) { +void prep_rgb_status_animation(const pyexec_result_t *result, + bool found_main, + safe_mode_t safe_mode, + rgb_status_animation_t *status) { #if defined(MICROPY_HW_NEOPIXEL) || (defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK)) || (defined(CP_RGB_STATUS_LED)) new_status_color(ALL_DONE); status->pattern_start = supervisor_ticks_ms32(); @@ -410,7 +410,7 @@ void prep_rgb_status_animation(const pyexec_result_t* result, #endif } -bool tick_rgb_status_animation(rgb_status_animation_t* status) { +bool tick_rgb_status_animation(rgb_status_animation_t *status) { #if defined(MICROPY_HW_NEOPIXEL) || (defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK)) || (defined(CP_RGB_STATUS_LED)) uint32_t tick_diff = supervisor_ticks_ms32() - status->pattern_start; if (status->ok) { @@ -442,12 +442,12 @@ bool tick_rgb_status_animation(rgb_status_animation_t* status) { } else { new_status_color(BOOT_RUNNING); } - // Next flash the exception color. + // Next flash the exception color. } else if (tick_diff < EXCEPTION_TYPE_LENGTH_MS * 2) { new_status_color(status->exception_color); - // Finally flash the line number digits from highest to lowest. - // Zeroes will not produce a flash but can be read by the absence of - // a color from the sequence. + // Finally flash the line number digits from highest to lowest. + // Zeroes will not produce a flash but can be read by the absence of + // a color from the sequence. } else if (tick_diff < (EXCEPTION_TYPE_LENGTH_MS * 2 + LINE_NUMBER_TOGGLE_LENGTH * status->digit_sum)) { uint32_t digit_diff = tick_diff - EXCEPTION_TYPE_LENGTH_MS * 2; if ((digit_diff % LINE_NUMBER_TOGGLE_LENGTH) < (LINE_NUMBER_TOGGLE_LENGTH / 2)) { diff --git a/supervisor/shared/rgb_led_status.h b/supervisor/shared/rgb_led_status.h index 84c97796a4..753a1167cb 100644 --- a/supervisor/shared/rgb_led_status.h +++ b/supervisor/shared/rgb_led_status.h @@ -72,10 +72,10 @@ typedef struct { bool found_main; } rgb_status_animation_t; -void prep_rgb_status_animation(const pyexec_result_t* result, - bool found_main, - safe_mode_t safe_mode, - rgb_status_animation_t* status); -bool tick_rgb_status_animation(rgb_status_animation_t* status); +void prep_rgb_status_animation(const pyexec_result_t *result, + bool found_main, + safe_mode_t safe_mode, + rgb_status_animation_t *status); +bool tick_rgb_status_animation(rgb_status_animation_t *status); #endif // MICROPY_INCLUDED_SUPERVISOR_RGB_LED_STATUS_H diff --git a/supervisor/shared/safe_mode.c b/supervisor/shared/safe_mode.c index 5d3b416f17..e8778216a6 100644 --- a/supervisor/shared/safe_mode.c +++ b/supervisor/shared/safe_mode.c @@ -85,7 +85,7 @@ safe_mode_t wait_for_safe_mode_reset(void) { #endif #ifdef CIRCUITPY_BOOT_BUTTON if (!common_hal_digitalio_digitalinout_get_value(&boot_button)) { - return USER_SAFE_MODE; + return USER_SAFE_MODE; } #endif diff = supervisor_ticks_ms64() - start_ticks; @@ -128,13 +128,13 @@ void print_safe_mode_message(safe_mode_t reason) { switch (reason) { case USER_SAFE_MODE: #ifdef BOARD_USER_SAFE_MODE_ACTION - // Output a user safe mode string if it's set. - serial_write_compressed(translate("You requested starting safe mode by ")); - serial_write_compressed(BOARD_USER_SAFE_MODE_ACTION); - serial_write_compressed(translate("To exit, please reset the board without ")); - serial_write_compressed(BOARD_USER_SAFE_MODE_ACTION); + // Output a user safe mode string if it's set. + serial_write_compressed(translate("You requested starting safe mode by ")); + serial_write_compressed(BOARD_USER_SAFE_MODE_ACTION); + serial_write_compressed(translate("To exit, please reset the board without ")); + serial_write_compressed(BOARD_USER_SAFE_MODE_ACTION); #else - break; + break; #endif return; case MANUAL_SAFE_MODE: @@ -178,13 +178,13 @@ void print_safe_mode_message(safe_mode_t reason) { case GC_ALLOC_OUTSIDE_VM: serial_write_compressed(translate("Attempted heap allocation when MicroPython VM not running.")); break; - #ifdef SOFTDEVICE_PRESENT + #ifdef SOFTDEVICE_PRESENT // defined in ports/nrf/bluetooth/bluetooth_common.mk // will print "Unknown reason" if somehow encountered on other ports case NORDIC_SOFT_DEVICE_ASSERT: serial_write_compressed(translate("Nordic Soft Device failure assertion.")); break; - #endif + #endif case FLASH_WRITE_FAIL: serial_write_compressed(translate("Failed to write internal flash.")); break; diff --git a/supervisor/shared/safe_mode.h b/supervisor/shared/safe_mode.h index 34fc3c8ae1..722e970333 100644 --- a/supervisor/shared/safe_mode.h +++ b/supervisor/shared/safe_mode.h @@ -30,21 +30,21 @@ #include "py/mpconfig.h" typedef enum { - NO_SAFE_MODE = 0, - BROWNOUT, - HARD_CRASH, - USER_SAFE_MODE, - HEAP_OVERWRITTEN, - MANUAL_SAFE_MODE, - MICROPY_NLR_JUMP_FAIL, - MICROPY_FATAL_ERROR, - GC_ALLOC_OUTSIDE_VM, - PROGRAMMATIC_SAFE_MODE, - NORDIC_SOFT_DEVICE_ASSERT, - FLASH_WRITE_FAIL, - MEM_MANAGE, - WATCHDOG_RESET, - NO_HEAP, + NO_SAFE_MODE = 0, + BROWNOUT, + HARD_CRASH, + USER_SAFE_MODE, + HEAP_OVERWRITTEN, + MANUAL_SAFE_MODE, + MICROPY_NLR_JUMP_FAIL, + MICROPY_FATAL_ERROR, + GC_ALLOC_OUTSIDE_VM, + PROGRAMMATIC_SAFE_MODE, + NORDIC_SOFT_DEVICE_ASSERT, + FLASH_WRITE_FAIL, + MEM_MANAGE, + WATCHDOG_RESET, + NO_HEAP, } safe_mode_t; safe_mode_t wait_for_safe_mode_reset(void); diff --git a/supervisor/shared/serial.c b/supervisor/shared/serial.c index 9cc12de512..268cebdbba 100644 --- a/supervisor/shared/serial.c +++ b/supervisor/shared/serial.c @@ -52,17 +52,17 @@ bool tud_vendor_connected(void); #endif void serial_early_init(void) { -#if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) + #if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) debug_uart.base.type = &busio_uart_type; - const mcu_pin_obj_t* rx = MP_OBJ_TO_PTR(DEBUG_UART_RX); - const mcu_pin_obj_t* tx = MP_OBJ_TO_PTR(DEBUG_UART_TX); + const mcu_pin_obj_t *rx = MP_OBJ_TO_PTR(DEBUG_UART_RX); + const mcu_pin_obj_t *tx = MP_OBJ_TO_PTR(DEBUG_UART_TX); common_hal_busio_uart_construct(&debug_uart, tx, rx, NULL, NULL, NULL, - false, 115200, 8, UART_PARITY_NONE, 1, 1.0f, 64, - buf_array, true); + false, 115200, 8, UART_PARITY_NONE, 1, 1.0f, 64, + buf_array, true); common_hal_busio_uart_never_reset(&debug_uart); -#endif + #endif } void serial_init(void) { @@ -70,68 +70,68 @@ void serial_init(void) { } bool serial_connected(void) { -#if CIRCUITPY_USB_VENDOR + #if CIRCUITPY_USB_VENDOR if (tud_vendor_connected()) { return true; } -#endif + #endif -#if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) + #if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) return true; -#else + #else return tud_cdc_connected(); -#endif + #endif } char serial_read(void) { -#if CIRCUITPY_USB_VENDOR + #if CIRCUITPY_USB_VENDOR if (tud_vendor_connected() && tud_vendor_available() > 0) { char tiny_buffer; tud_vendor_read(&tiny_buffer, 1); return tiny_buffer; } -#endif + #endif -#if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) + #if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) if (tud_cdc_connected() && tud_cdc_available() > 0) { - return (char) tud_cdc_read_char(); + return (char)tud_cdc_read_char(); } int uart_errcode; char text; - common_hal_busio_uart_read(&debug_uart, (uint8_t*) &text, 1, &uart_errcode); + common_hal_busio_uart_read(&debug_uart, (uint8_t *)&text, 1, &uart_errcode); return text; -#else - return (char) tud_cdc_read_char(); -#endif + #else + return (char)tud_cdc_read_char(); + #endif } bool serial_bytes_available(void) { -#if CIRCUITPY_USB_VENDOR + #if CIRCUITPY_USB_VENDOR if (tud_vendor_connected() && tud_vendor_available() > 0) { return true; } -#endif + #endif -#if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) + #if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) return common_hal_busio_uart_rx_characters_available(&debug_uart) || (tud_cdc_available() > 0); -#else + #else return tud_cdc_available() > 0; -#endif + #endif } -void serial_write_substring(const char* text, uint32_t length) { +void serial_write_substring(const char *text, uint32_t length) { if (length == 0) { return; } -#if CIRCUITPY_TERMINALIO + #if CIRCUITPY_TERMINALIO int errcode; - common_hal_terminalio_terminal_write(&supervisor_terminal, (const uint8_t*) text, length, &errcode); -#endif + common_hal_terminalio_terminal_write(&supervisor_terminal, (const uint8_t *)text, length, &errcode); + #endif -#if CIRCUITPY_USB_VENDOR + #if CIRCUITPY_USB_VENDOR if (tud_vendor_connected()) { tud_vendor_write(text, length); } -#endif + #endif uint32_t count = 0; while (count < length && tud_cdc_connected()) { @@ -139,12 +139,12 @@ void serial_write_substring(const char* text, uint32_t length) { usb_background(); } -#if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) + #if defined(DEBUG_UART_TX) && defined(DEBUG_UART_RX) int uart_errcode; - common_hal_busio_uart_write(&debug_uart, (const uint8_t*) text, length, &uart_errcode); -#endif + common_hal_busio_uart_write(&debug_uart, (const uint8_t *)text, length, &uart_errcode); + #endif } -void serial_write(const char* text) { +void serial_write(const char *text) { serial_write_substring(text, strlen(text)); } diff --git a/supervisor/shared/stack.c b/supervisor/shared/stack.c old mode 100755 new mode 100644 index afea204010..f3077b46c3 --- a/supervisor/shared/stack.c +++ b/supervisor/shared/stack.c @@ -38,7 +38,7 @@ extern uint32_t _estack; static uint32_t next_stack_size = CIRCUITPY_DEFAULT_STACK_SIZE; static uint32_t current_stack_size = 0; // Actual location and size, may be larger than requested. -static uint32_t* stack_limit = NULL; +static uint32_t *stack_limit = NULL; static size_t stack_length = 0; #define EXCEPTION_STACK_SIZE 1024 @@ -47,14 +47,14 @@ void allocate_stack(void) { if (port_has_fixed_stack()) { stack_limit = port_stack_get_limit(); - stack_length = (port_stack_get_top() - stack_limit)*sizeof(uint32_t); + stack_length = (port_stack_get_top() - stack_limit) * sizeof(uint32_t); current_stack_size = stack_length; } else { mp_uint_t regs[10]; mp_uint_t sp = cpu_get_regs_and_sp(regs); - mp_uint_t c_size = (uint32_t) port_stack_get_top() - sp; - supervisor_allocation* stack_alloc = allocate_memory(c_size + next_stack_size + EXCEPTION_STACK_SIZE, true, false); + mp_uint_t c_size = (uint32_t)port_stack_get_top() - sp; + supervisor_allocation *stack_alloc = allocate_memory(c_size + next_stack_size + EXCEPTION_STACK_SIZE, true, false); if (stack_alloc == NULL) { stack_alloc = allocate_memory(c_size + CIRCUITPY_DEFAULT_STACK_SIZE + EXCEPTION_STACK_SIZE, true, false); current_stack_size = CIRCUITPY_DEFAULT_STACK_SIZE; @@ -95,7 +95,7 @@ void stack_resize(void) { allocate_stack(); } -uint32_t* stack_get_bottom(void) { +uint32_t *stack_get_bottom(void) { return stack_limit; } diff --git a/supervisor/shared/stack.h b/supervisor/shared/stack.h old mode 100755 new mode 100644 index 1c75de5f78..98cc5a1685 --- a/supervisor/shared/stack.h +++ b/supervisor/shared/stack.h @@ -34,7 +34,7 @@ void stack_init(void); void stack_resize(void); // Actual stack location and size, may be larger than requested. -uint32_t* stack_get_bottom(void); +uint32_t *stack_get_bottom(void); size_t stack_get_length(void); // Next/current requested stack size. void set_next_stack_size(uint32_t size); diff --git a/supervisor/shared/tick.c b/supervisor/shared/tick.c index e51c48c739..f40151988e 100644 --- a/supervisor/shared/tick.c +++ b/supervisor/shared/tick.c @@ -105,13 +105,13 @@ bool supervisor_background_tasks_ok(void) { } void supervisor_tick(void) { -#if CIRCUITPY_FILESYSTEM_FLUSH_INTERVAL_MS > 0 + #if CIRCUITPY_FILESYSTEM_FLUSH_INTERVAL_MS > 0 filesystem_tick(); -#endif -#ifdef CIRCUITPY_AUTORELOAD_DELAY_MS + #endif + #ifdef CIRCUITPY_AUTORELOAD_DELAY_MS autoreload_tick(); -#endif -#ifdef CIRCUITPY_GAMEPAD_TICKS + #endif + #ifdef CIRCUITPY_GAMEPAD_TICKS if (!(port_get_raw_ticks(NULL) & CIRCUITPY_GAMEPAD_TICKS)) { #if CIRCUITPY_GAMEPAD gamepad_tick(); @@ -120,7 +120,7 @@ void supervisor_tick(void) { gamepadshift_tick(); #endif } -#endif + #endif background_callback_add(&tick_callback, supervisor_background_tasks, NULL); } diff --git a/supervisor/shared/translate.c b/supervisor/shared/translate.c index 8bd3c5acde..54135a4935 100644 --- a/supervisor/shared/translate.c +++ b/supervisor/shared/translate.c @@ -37,17 +37,17 @@ #include "py/misc.h" #include "supervisor/serial.h" -void serial_write_compressed(const compressed_string_t* compressed) { +void serial_write_compressed(const compressed_string_t *compressed) { char decompressed[decompress_length(compressed)]; decompress(compressed, decompressed); serial_write(decompressed); } STATIC int put_utf8(char *buf, int u) { - if(u <= 0x7f) { + if (u <= 0x7f) { *buf = u; return 1; - } else if(word_start <= u && u <= word_end) { + } else if (word_start <= u && u <= word_end) { uint n = (u - word_start); size_t pos = 0; if (n > 0) { @@ -57,25 +57,25 @@ STATIC int put_utf8(char *buf, int u) { // note that at present, entries in the words table are // guaranteed not to represent words themselves, so this adds // at most 1 level of recursive call - for(; pos < wends[n] + (n + 1) * 2; pos++) { + for (; pos < wends[n] + (n + 1) * 2; pos++) { int len = put_utf8(buf, words[pos]); buf += len; ret += len; } return ret; - } else if(u <= 0x07ff) { + } else if (u <= 0x07ff) { *buf++ = 0b11000000 | (u >> 6); - *buf = 0b10000000 | (u & 0b00111111); + *buf = 0b10000000 | (u & 0b00111111); return 2; } else { // u <= 0xffff *buf++ = 0b11100000 | (u >> 12); *buf++ = 0b10000000 | ((u >> 6) & 0b00111111); - *buf = 0b10000000 | (u & 0b00111111); + *buf = 0b10000000 | (u & 0b00111111); return 3; } } -uint16_t decompress_length(const compressed_string_t* compressed) { +uint16_t decompress_length(const compressed_string_t *compressed) { if (compress_max_length_bits <= 8) { return 1 + (compressed->data >> (8 - compress_max_length_bits)); } else { @@ -83,7 +83,7 @@ uint16_t decompress_length(const compressed_string_t* compressed) { } } -char* decompress(const compressed_string_t* compressed, char* decompressed) { +char *decompress(const compressed_string_t *compressed, char *decompressed) { uint8_t this_byte = compress_max_length_bits / 8; uint8_t this_bit = 7 - compress_max_length_bits % 8; uint8_t b = (&compressed->data)[this_byte]; @@ -118,22 +118,22 @@ char* decompress(const compressed_string_t* compressed, char* decompressed) { i += put_utf8(decompressed + i, values[searched_length + bits - max_code]); } - decompressed[length-1] = '\0'; + decompressed[length - 1] = '\0'; return decompressed; } inline // gcc10 -flto has issues with this being always_inline for debug builds. #if CIRCUITPY_DEBUG < 1 - __attribute__((always_inline)) +__attribute__((always_inline)) #endif -const compressed_string_t* translate(const char* original) { +const compressed_string_t *translate(const char *original) { #ifndef NO_QSTR #define QDEF(id, str) #define TRANSLATION(id, firstbyte, ...) if (strcmp(original, id) == 0) { static const compressed_string_t v = { .data = firstbyte, .tail = { __VA_ARGS__ } }; return &v; } else #include "genhdr/qstrdefs.generated.h" - #undef TRANSLATION - #undef QDEF +#undef TRANSLATION +#undef QDEF #endif return NULL; } diff --git a/supervisor/shared/translate.h b/supervisor/shared/translate.h index 16296a4161..2c440acc14 100644 --- a/supervisor/shared/translate.h +++ b/supervisor/shared/translate.h @@ -74,9 +74,9 @@ typedef struct { // Return the compressed, translated version of a source string // Usually, due to LTO, this is optimized into a load of a constant // pointer. -const compressed_string_t* translate(const char* c); -void serial_write_compressed(const compressed_string_t* compressed); -char* decompress(const compressed_string_t* compressed, char* decompressed); -uint16_t decompress_length(const compressed_string_t* compressed); +const compressed_string_t *translate(const char *c); +void serial_write_compressed(const compressed_string_t *compressed); +char *decompress(const compressed_string_t *compressed, char *decompressed); +uint16_t decompress_length(const compressed_string_t *compressed); #endif // MICROPY_INCLUDED_SUPERVISOR_TRANSLATE_H diff --git a/supervisor/shared/usb/tusb_config.h b/supervisor/shared/usb/tusb_config.h index 6768101190..0b23d56b9b 100644 --- a/supervisor/shared/usb/tusb_config.h +++ b/supervisor/shared/usb/tusb_config.h @@ -41,12 +41,12 @@ #include "genhdr/autogen_usb_descriptor.h" #ifdef __cplusplus - extern "C" { +extern "C" { #endif -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ // COMMON CONFIGURATION -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ #ifndef CFG_TUSB_DEBUG #define CFG_TUSB_DEBUG 0 #endif @@ -55,15 +55,15 @@ #ifndef CFG_TUSB_OS #define CFG_TUSB_OS OPT_OS_NONE #endif -//#define CFG_TUD_TASK_QUEUE_SZ 16 +// #define CFG_TUD_TASK_QUEUE_SZ 16 -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ // DEVICE CONFIGURATION -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ #define CFG_TUD_ENDPOINT0_SIZE 64 -//------------- CLASS -------------// +// ------------- CLASS -------------// // Could be 2 if secondary CDC channel requested. #ifndef CFG_TUD_CDC @@ -84,15 +84,15 @@ #define CFG_TUD_MSC_PRODUCT_REV "1.0" -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ // USB RAM PLACEMENT -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ #define CFG_TUSB_ATTR_USBRAM #define CFG_TUSB_MEM_ALIGN __attribute__ ((aligned(4))) #ifdef __cplusplus - } +} #endif #endif /* _TUSB_CONFIG_H_ */ diff --git a/supervisor/shared/usb/usb.c b/supervisor/shared/usb/usb.c index 614bf85e05..ea5faaf06b 100644 --- a/supervisor/shared/usb/usb.c +++ b/supervisor/shared/usb/usb.c @@ -76,7 +76,8 @@ bool usb_enabled(void) { return tusb_inited(); } -MP_WEAK void post_usb_init(void) {} +MP_WEAK void post_usb_init(void) { +} void usb_init(void) { init_usb_hardware(); @@ -86,15 +87,15 @@ void usb_init(void) { post_usb_init(); -#if MICROPY_KBD_EXCEPTION + #if MICROPY_KBD_EXCEPTION // Set Ctrl+C as wanted char, tud_cdc_rx_wanted_cb() usb_callback will be invoked when Ctrl+C is received // This usb_callback always got invoked regardless of mp_interrupt_char value since we only set it once here tud_cdc_set_wanted_char(CHAR_CTRL_C); -#endif + #endif -#if CIRCUITPY_USB_MIDI + #if CIRCUITPY_USB_MIDI usb_midi_init(); -#endif + #endif } void usb_disconnect(void) { @@ -111,12 +112,11 @@ void usb_background(void) { } static background_callback_t usb_callback; -static void usb_background_do(void* unused) { +static void usb_background_do(void *unused) { usb_background(); } -void usb_background_schedule(void) -{ +void usb_background_schedule(void) { background_callback_add(&usb_callback, usb_background_do, NULL); } @@ -125,22 +125,22 @@ void usb_irq_handler(void) { usb_background_schedule(); } -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ // tinyusb callbacks -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ // Invoked when device is mounted void tud_mount_cb(void) { -#if CIRCUITPY_USB_MSC + #if CIRCUITPY_USB_MSC usb_msc_mount(); -#endif + #endif } // Invoked when device is unmounted void tud_umount_cb(void) { -#if CIRCUITPY_USB_MSC + #if CIRCUITPY_USB_MSC usb_msc_umount(); -#endif + #endif } // Invoked when usb bus is suspended @@ -156,73 +156,69 @@ void tud_resume_cb(void) { // Invoked when cdc when line state changed e.g connected/disconnected // Use to reset to DFU when disconnect with 1200 bps void tud_cdc_line_state_cb(uint8_t itf, bool dtr, bool rts) { - (void) itf; // interface ID, not used + (void)itf; // interface ID, not used // DTR = false is counted as disconnected - if ( !dtr ) - { + if (!dtr) { cdc_line_coding_t coding; tud_cdc_get_line_coding(&coding); - if ( coding.bit_rate == 1200 ) - { + if (coding.bit_rate == 1200) { reset_to_bootloader(); } } } #if CIRCUITPY_USB_VENDOR -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ // WebUSB use vendor class -//--------------------------------------------------------------------+ +// --------------------------------------------------------------------+ -bool tud_vendor_connected(void) -{ - return web_serial_connected; +bool tud_vendor_connected(void) { + return web_serial_connected; } // Invoked when a control transfer occurred on an interface of this class // Driver response accordingly to the request and the transfer stage (setup/data/ack) // return false to stall control endpoint (e.g unsupported request) -bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const * request) -{ - // nothing to with DATA & ACK stage - if (stage != CONTROL_STAGE_SETUP ) return true; +bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_request_t const *request) { + // nothing to with DATA & ACK stage + if (stage != CONTROL_STAGE_SETUP) { + return true; + } - switch (request->bRequest) - { - case VENDOR_REQUEST_WEBUSB: - // match vendor request in BOS descriptor - // Get landing page url - return tud_control_xfer(rhport, request, (void*) &desc_webusb_url, desc_webusb_url.bLength); + switch (request->bRequest) + { + case VENDOR_REQUEST_WEBUSB: + // match vendor request in BOS descriptor + // Get landing page url + return tud_control_xfer(rhport, request, (void *)&desc_webusb_url, desc_webusb_url.bLength); - case VENDOR_REQUEST_MICROSOFT: - if ( request->wIndex == 7 ) - { - // Get Microsoft OS 2.0 compatible descriptor - uint16_t total_len; - memcpy(&total_len, desc_ms_os_20+8, 2); + case VENDOR_REQUEST_MICROSOFT: + if (request->wIndex == 7) { + // Get Microsoft OS 2.0 compatible descriptor + uint16_t total_len; + memcpy(&total_len, desc_ms_os_20 + 8, 2); - return tud_control_xfer(rhport, request, (void*) desc_ms_os_20, total_len); - } else - { - return false; - } + return tud_control_xfer(rhport, request, (void *)desc_ms_os_20, total_len); + } else { + return false; + } - case 0x22: - // Webserial simulate the CDC_REQUEST_SET_CONTROL_LINE_STATE (0x22) to - // connect and disconnect. - web_serial_connected = (request->wValue != 0); + case 0x22: + // Webserial simulate the CDC_REQUEST_SET_CONTROL_LINE_STATE (0x22) to + // connect and disconnect. + web_serial_connected = (request->wValue != 0); - // response with status OK - return tud_control_status(rhport, request); + // response with status OK + return tud_control_status(rhport, request); - default: - // stall unknown request - return false; - } + default: + // stall unknown request + return false; + } - return true; + return true; } #endif // CIRCUITPY_USB_VENDOR @@ -234,9 +230,8 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ * @param itf Interface index (for multiple cdc interfaces) * @param wanted_char The wanted char (set previously) */ -void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char) -{ - (void) itf; // not used +void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char) { + (void)itf; // not used // Workaround for using lib/utils/interrupt_char.c // Compare mp_interrupt_char with wanted_char and ignore if not matched diff --git a/supervisor/shared/usb/usb_desc.c b/supervisor/shared/usb/usb_desc.c index b08d3b2274..67df4f44bf 100644 --- a/supervisor/shared/usb/usb_desc.c +++ b/supervisor/shared/usb/usb_desc.c @@ -31,15 +31,15 @@ // Invoked when received GET DEVICE DESCRIPTOR // Application return pointer to descriptor -uint8_t const * tud_descriptor_device_cb(void) { +uint8_t const *tud_descriptor_device_cb(void) { return usb_desc_dev; } // Invoked when received GET CONFIGURATION DESCRIPTOR // Application return pointer to descriptor // Descriptor contents must exist long enough for transfer to complete -uint8_t const * tud_descriptor_configuration_cb(uint8_t index) { - (void) index; // for multiple configurations +uint8_t const *tud_descriptor_configuration_cb(uint8_t index) { + (void)index; // for multiple configurations return usb_desc_cfg; } @@ -47,15 +47,15 @@ uint8_t const * tud_descriptor_configuration_cb(uint8_t index) { // Invoked when received GET HID REPORT DESCRIPTOR // Application return pointer to descriptor // Descriptor contents must exist long enough for transfer to complete -uint8_t const * tud_hid_descriptor_report_cb(uint8_t itf) { - (void) itf; +uint8_t const *tud_hid_descriptor_report_cb(uint8_t itf) { + (void)itf; return hid_report_descriptor; } #endif // Invoked when received GET STRING DESCRIPTOR request // Application return pointer to descriptor, whose contents must exist long enough for transfer to complete -uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) { - uint8_t const max_index = sizeof(string_desc_arr)/sizeof(string_desc_arr[0]); +uint16_t const *tud_descriptor_string_cb(uint8_t index, uint16_t langid) { + uint8_t const max_index = sizeof(string_desc_arr) / sizeof(string_desc_arr[0]); return (index < max_index) ? string_desc_arr[index] : NULL; } diff --git a/supervisor/shared/usb/usb_msc_flash.c b/supervisor/shared/usb/usb_msc_flash.c index 7532b6aead..409bf0ea6c 100644 --- a/supervisor/shared/usb/usb_msc_flash.c +++ b/supervisor/shared/usb/usb_msc_flash.c @@ -62,13 +62,13 @@ bool usb_msc_ejected(void) { } // The root FS is always at the end of the list. -static fs_user_mount_t* get_vfs(int lun) { +static fs_user_mount_t *get_vfs(int lun) { // TODO(tannewt): Return the mount which matches the lun where 0 is the end // and is counted in reverse. if (lun > 0) { return NULL; } - mp_vfs_mount_t* current_mount = MP_STATE_VM(vfs_mount_table); + mp_vfs_mount_t *current_mount = MP_STATE_VM(vfs_mount_table); if (current_mount == NULL) { return NULL; } @@ -81,40 +81,40 @@ static fs_user_mount_t* get_vfs(int lun) { // Callback invoked when received an SCSI command not in built-in list below // - READ_CAPACITY10, READ_FORMAT_CAPACITY, INQUIRY, TEST_UNIT_READY, START_STOP_UNIT, MODE_SENSE6, REQUEST_SENSE // - READ10 and WRITE10 have their own callbacks -int32_t tud_msc_scsi_cb (uint8_t lun, const uint8_t scsi_cmd[16], void* buffer, uint16_t bufsize) { - const void* response = NULL; +int32_t tud_msc_scsi_cb(uint8_t lun, const uint8_t scsi_cmd[16], void *buffer, uint16_t bufsize) { + const void *response = NULL; int32_t resplen = 0; - switch ( scsi_cmd[0] ) { + switch (scsi_cmd[0]) { case SCSI_CMD_PREVENT_ALLOW_MEDIUM_REMOVAL: // Host is about to read/write etc ... better not to disconnect disk resplen = 0; - break; + break; default: - // Set Sense = Invalid Command Operation - tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); + // Set Sense = Invalid Command Operation + tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); - // negative means error -> tinyusb could stall and/or response with failed status - resplen = -1; - break; + // negative means error -> tinyusb could stall and/or response with failed status + resplen = -1; + break; } // return len must not larger than bufsize - if ( resplen > bufsize ) { + if (resplen > bufsize) { resplen = bufsize; } // copy response to stack's buffer if any - if ( response && (resplen > 0) ) { + if (response && (resplen > 0)) { memcpy(buffer, response, resplen); } return resplen; } -void tud_msc_capacity_cb(uint8_t lun, uint32_t* block_count, uint16_t* block_size) { - fs_user_mount_t * vfs = get_vfs(lun); +void tud_msc_capacity_cb(uint8_t lun, uint32_t *block_count, uint16_t *block_size) { + fs_user_mount_t *vfs = get_vfs(lun); disk_ioctl(vfs, GET_SECTOR_COUNT, block_count); disk_ioctl(vfs, GET_SECTOR_SIZE, block_size); } @@ -124,7 +124,7 @@ bool tud_msc_is_writable_cb(uint8_t lun) { return false; } - fs_user_mount_t* vfs = get_vfs(lun); + fs_user_mount_t *vfs = get_vfs(lun); if (vfs == NULL) { return false; } @@ -136,13 +136,13 @@ bool tud_msc_is_writable_cb(uint8_t lun) { // Callback invoked when received READ10 command. // Copy disk's data to buffer (up to bufsize) and return number of copied bytes. -int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buffer, uint32_t bufsize) { - (void) lun; - (void) offset; +int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void *buffer, uint32_t bufsize) { + (void)lun; + (void)offset; const uint32_t block_count = bufsize / MSC_FLASH_BLOCK_SIZE; - fs_user_mount_t * vfs = get_vfs(lun); + fs_user_mount_t *vfs = get_vfs(lun); disk_read(vfs, buffer, lba, block_count); return block_count * MSC_FLASH_BLOCK_SIZE; @@ -150,13 +150,13 @@ int32_t tud_msc_read10_cb (uint8_t lun, uint32_t lba, uint32_t offset, void* buf // Callback invoked when received WRITE10 command. // Process data in buffer to disk's storage and return number of written bytes -int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* buffer, uint32_t bufsize) { - (void) lun; - (void) offset; +int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t *buffer, uint32_t bufsize) { + (void)lun; + (void)offset; const uint32_t block_count = bufsize / MSC_FLASH_BLOCK_SIZE; - fs_user_mount_t * vfs = get_vfs(lun); + fs_user_mount_t *vfs = get_vfs(lun); disk_write(vfs, buffer, lba, block_count); // Since by getting here we assume the mount is read-only to // MicroPython let's update the cached FatFs sector if it's the one @@ -166,11 +166,11 @@ int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* #else // The compiler can optimize this away. if (_MAX_SS == FILESYSTEM_BLOCK_SIZE) { - #endif + #endif if (lba == vfs->fatfs.winsect && lba > 0) { memcpy(vfs->fatfs.win, - buffer + MSC_FLASH_BLOCK_SIZE * (vfs->fatfs.winsect - lba), - MSC_FLASH_BLOCK_SIZE); + buffer + MSC_FLASH_BLOCK_SIZE * (vfs->fatfs.winsect - lba), + MSC_FLASH_BLOCK_SIZE); } } @@ -179,8 +179,8 @@ int32_t tud_msc_write10_cb (uint8_t lun, uint32_t lba, uint32_t offset, uint8_t* // Callback invoked when WRITE10 command is completed (status received and accepted by host). // used to flush any pending cache. -void tud_msc_write10_complete_cb (uint8_t lun) { - (void) lun; +void tud_msc_write10_complete_cb(uint8_t lun) { + (void)lun; // This write is complete, start the autoreload clock. autoreload_start(); @@ -189,10 +189,10 @@ void tud_msc_write10_complete_cb (uint8_t lun) { // Invoked when received SCSI_CMD_INQUIRY // Application fill vendor id, product id and revision with string up to 8, 16, 4 characters respectively void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16], uint8_t product_rev[4]) { - (void) lun; + (void)lun; - memcpy(vendor_id , CFG_TUD_MSC_VENDOR , strlen(CFG_TUD_MSC_VENDOR)); - memcpy(product_id , CFG_TUD_MSC_PRODUCT , strlen(CFG_TUD_MSC_PRODUCT)); + memcpy(vendor_id, CFG_TUD_MSC_VENDOR, strlen(CFG_TUD_MSC_VENDOR)); + memcpy(product_id, CFG_TUD_MSC_PRODUCT, strlen(CFG_TUD_MSC_PRODUCT)); memcpy(product_rev, CFG_TUD_MSC_PRODUCT_REV, strlen(CFG_TUD_MSC_PRODUCT_REV)); } @@ -203,7 +203,7 @@ bool tud_msc_test_unit_ready_cb(uint8_t lun) { return false; } - fs_user_mount_t* current_mount = get_vfs(lun); + fs_user_mount_t *current_mount = get_vfs(lun); if (current_mount == NULL) { return false; } @@ -223,7 +223,7 @@ bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, boo if (lun > 1) { return false; } - fs_user_mount_t* current_mount = get_vfs(lun); + fs_user_mount_t *current_mount = get_vfs(lun); if (current_mount == NULL) { return false; } diff --git a/supervisor/spi_flash_api.h b/supervisor/spi_flash_api.h index f59346e25a..ed80b8207b 100644 --- a/supervisor/spi_flash_api.h +++ b/supervisor/spi_flash_api.h @@ -33,17 +33,17 @@ #include "shared-bindings/busio/SPI.h" -extern busio_spi_obj_t supervisor_flash_spi_bus; //Used to share SPI bus on some boards +extern busio_spi_obj_t supervisor_flash_spi_bus; // Used to share SPI bus on some boards // This API is implemented for both normal SPI peripherals and QSPI peripherals. bool spi_flash_command(uint8_t command); -bool spi_flash_read_command(uint8_t command, uint8_t* response, uint32_t length); -bool spi_flash_write_command(uint8_t command, uint8_t* data, uint32_t length); +bool spi_flash_read_command(uint8_t command, uint8_t *response, uint32_t length); +bool spi_flash_write_command(uint8_t command, uint8_t *data, uint32_t length); bool spi_flash_sector_command(uint8_t command, uint32_t address); -bool spi_flash_write_data(uint32_t address, uint8_t* data, uint32_t data_length); -bool spi_flash_read_data(uint32_t address, uint8_t* data, uint32_t data_length); +bool spi_flash_write_data(uint32_t address, uint8_t *data, uint32_t data_length); +bool spi_flash_read_data(uint32_t address, uint8_t *data, uint32_t data_length); void spi_flash_init(void); -void spi_flash_init_device(const external_flash_device* device); +void spi_flash_init_device(const external_flash_device *device); #endif // MICROPY_INCLUDED_SUPERVISOR_SPI_FLASH_H diff --git a/supervisor/stub/filesystem.c b/supervisor/stub/filesystem.c index 1c4a3e12dd..2b518f4142 100644 --- a/supervisor/stub/filesystem.c +++ b/supervisor/stub/filesystem.c @@ -27,15 +27,15 @@ #include "supervisor/filesystem.h" void filesystem_init(bool create_allowed, bool force_create) { - (void) create_allowed; - (void) force_create; + (void)create_allowed; + (void)force_create; } void filesystem_flush(void) { } bool filesystem_is_writable_by_python(fs_user_mount_t *vfs) { - (void) vfs; + (void)vfs; return true; } diff --git a/supervisor/stub/safe_mode.c b/supervisor/stub/safe_mode.c index a70ac6b6d0..b62cc05d78 100644 --- a/supervisor/stub/safe_mode.c +++ b/supervisor/stub/safe_mode.c @@ -33,10 +33,10 @@ safe_mode_t wait_for_safe_mode_reset(void) { } void reset_into_safe_mode(safe_mode_t reason) { - (void) reason; + (void)reason; abort(); } void print_safe_mode_message(safe_mode_t reason) { - (void) reason; + (void)reason; } diff --git a/supervisor/stub/serial.c b/supervisor/stub/serial.c index 34b433e536..fc8bd221e7 100644 --- a/supervisor/stub/serial.c +++ b/supervisor/stub/serial.c @@ -46,6 +46,6 @@ bool serial_bytes_available(void) { return false; } -void serial_write(const char* text) { - (void) text; +void serial_write(const char *text) { + (void)text; } diff --git a/supervisor/stub/stack.c b/supervisor/stub/stack.c index 9a9ecd32f6..2abc197878 100644 --- a/supervisor/stub/stack.c +++ b/supervisor/stub/stack.c @@ -40,7 +40,7 @@ void stack_resize(void) { } void set_next_stack_size(uint32_t size) { - (void) size; + (void)size; } uint32_t get_current_stack_size(void) { diff --git a/tests/bench/arrayop-1-list_inplace.py b/tests/bench/arrayop-1-list_inplace.py index 0ee1ef2eca..b29593c1a1 100644 --- a/tests/bench/arrayop-1-list_inplace.py +++ b/tests/bench/arrayop-1-list_inplace.py @@ -3,10 +3,12 @@ # method is that it doesn't require any extra memory allocation. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = [0] * 1000 for i in range(len(arr)): arr[i] += 1 + bench.run(test) diff --git a/tests/bench/arrayop-2-list_map.py b/tests/bench/arrayop-2-list_map.py index 9d5095c53a..5959d3f469 100644 --- a/tests/bench/arrayop-2-list_map.py +++ b/tests/bench/arrayop-2-list_map.py @@ -4,9 +4,11 @@ # array). On the other hand, input array stays intact. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = [0] * 1000 arr2 = list(map(lambda x: x + 1, arr)) + bench.run(test) diff --git a/tests/bench/arrayop-3-bytearray_inplace.py b/tests/bench/arrayop-3-bytearray_inplace.py index a6d6280705..fbbade2cac 100644 --- a/tests/bench/arrayop-3-bytearray_inplace.py +++ b/tests/bench/arrayop-3-bytearray_inplace.py @@ -3,10 +3,12 @@ # method is that it doesn't require any extra memory allocation. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = bytearray(b"\0" * 1000) for i in range(len(arr)): arr[i] += 1 + bench.run(test) diff --git a/tests/bench/arrayop-4-bytearray_map.py b/tests/bench/arrayop-4-bytearray_map.py index 1b92a40961..8fa9879705 100644 --- a/tests/bench/arrayop-4-bytearray_map.py +++ b/tests/bench/arrayop-4-bytearray_map.py @@ -4,9 +4,11 @@ # array). On the other hand, input array stays intact. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): arr = bytearray(b"\0" * 1000) arr2 = bytearray(map(lambda x: x + 1, arr)) + bench.run(test) diff --git a/tests/bench/bench.py b/tests/bench/bench.py index 0cd40a93fc..d7087e0e09 100644 --- a/tests/bench/bench.py +++ b/tests/bench/bench.py @@ -3,6 +3,7 @@ import time ITERS = 20000000 + def run(f): t = time.time() f(ITERS) diff --git a/tests/bench/bytealloc-1-bytes_n.py b/tests/bench/bytealloc-1-bytes_n.py index 4a4bbc6fae..8b8120a530 100644 --- a/tests/bench/bytealloc-1-bytes_n.py +++ b/tests/bench/bytealloc-1-bytes_n.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num // 1000)): bytes(10000) + bench.run(test) diff --git a/tests/bench/bytealloc-2-repeat.py b/tests/bench/bytealloc-2-repeat.py index 786a804622..8d6b5d5289 100644 --- a/tests/bench/bytealloc-2-repeat.py +++ b/tests/bench/bytealloc-2-repeat.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num // 1000)): b"\0" * 10000 + bench.run(test) diff --git a/tests/bench/bytebuf-1-inplace.py b/tests/bench/bytebuf-1-inplace.py index 7e7d9391cc..e1b6016a57 100644 --- a/tests/bench/bytebuf-1-inplace.py +++ b/tests/bench/bytebuf-1-inplace.py @@ -2,10 +2,12 @@ # Inplace - the most memory efficient way import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) for i in range(len(ba)): ba[i] += 1 + bench.run(test) diff --git a/tests/bench/bytebuf-2-join_map_bytes.py b/tests/bench/bytebuf-2-join_map_bytes.py index daa622991f..9ecee47978 100644 --- a/tests/bench/bytebuf-2-join_map_bytes.py +++ b/tests/bench/bytebuf-2-join_map_bytes.py @@ -4,9 +4,11 @@ # this is slowest way to do it. import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) - ba2 = b''.join(map(lambda x:bytes([x + 1]), ba)) + ba2 = b"".join(map(lambda x: bytes([x + 1]), ba)) + bench.run(test) diff --git a/tests/bench/bytebuf-3-bytarray_map.py b/tests/bench/bytebuf-3-bytarray_map.py index 078d08e99b..2752d4e784 100644 --- a/tests/bench/bytebuf-3-bytarray_map.py +++ b/tests/bench/bytebuf-3-bytarray_map.py @@ -2,9 +2,11 @@ # No joins, but still map(). import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): ba = bytearray(b"\0" * 1000) ba2 = bytearray(map(lambda x: x + 1, ba)) + bench.run(test) diff --git a/tests/bench/from_iter-1-list_bound.py b/tests/bench/from_iter-1-list_bound.py index d209daecc5..384d52903f 100644 --- a/tests/bench/from_iter-1-list_bound.py +++ b/tests/bench/from_iter-1-list_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = list(l) + bench.run(test) diff --git a/tests/bench/from_iter-2-list_unbound.py b/tests/bench/from_iter-2-list_unbound.py index be019c52fe..98e22d6813 100644 --- a/tests/bench/from_iter-2-list_unbound.py +++ b/tests/bench/from_iter-2-list_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = list(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/bench/from_iter-3-tuple_bound.py b/tests/bench/from_iter-3-tuple_bound.py index 7b7fa36c6e..f052f6deea 100644 --- a/tests/bench/from_iter-3-tuple_bound.py +++ b/tests/bench/from_iter-3-tuple_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = tuple(l) + bench.run(test) diff --git a/tests/bench/from_iter-4-tuple_unbound.py b/tests/bench/from_iter-4-tuple_unbound.py index 7c7f134c85..ff9d1b4df5 100644 --- a/tests/bench/from_iter-4-tuple_unbound.py +++ b/tests/bench/from_iter-4-tuple_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = tuple(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/bench/from_iter-5-bytes_bound.py b/tests/bench/from_iter-5-bytes_bound.py index b793a3207e..967cb99eea 100644 --- a/tests/bench/from_iter-5-bytes_bound.py +++ b/tests/bench/from_iter-5-bytes_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytes(l) + bench.run(test) diff --git a/tests/bench/from_iter-6-bytes_unbound.py b/tests/bench/from_iter-6-bytes_unbound.py index 20aa556277..b855019160 100644 --- a/tests/bench/from_iter-6-bytes_unbound.py +++ b/tests/bench/from_iter-6-bytes_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytes(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/bench/from_iter-7-bytearray_bound.py b/tests/bench/from_iter-7-bytearray_bound.py index 72001a05c7..d0c4c65a74 100644 --- a/tests/bench/from_iter-7-bytearray_bound.py +++ b/tests/bench/from_iter-7-bytearray_bound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytearray(l) + bench.run(test) diff --git a/tests/bench/from_iter-8-bytearray_unbound.py b/tests/bench/from_iter-8-bytearray_unbound.py index e2263b8ef9..aec2e65adf 100644 --- a/tests/bench/from_iter-8-bytearray_unbound.py +++ b/tests/bench/from_iter-8-bytearray_unbound.py @@ -1,8 +1,10 @@ import bench + def test(num): - for i in iter(range(num//10000)): + for i in iter(range(num // 10000)): l = [0] * 1000 l2 = bytearray(map(lambda x: x, l)) + bench.run(test) diff --git a/tests/bench/func_args-1.1-pos_1.py b/tests/bench/func_args-1.1-pos_1.py index eee0ea8289..cadb17768c 100644 --- a/tests/bench/func_args-1.1-pos_1.py +++ b/tests/bench/func_args-1.1-pos_1.py @@ -1,10 +1,13 @@ import bench + def func(a): pass + def test(num): for i in iter(range(num)): func(i) + bench.run(test) diff --git a/tests/bench/func_args-1.2-pos_3.py b/tests/bench/func_args-1.2-pos_3.py index 7e03ee2f85..12010d0150 100644 --- a/tests/bench/func_args-1.2-pos_3.py +++ b/tests/bench/func_args-1.2-pos_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b, c): pass + def test(num): for i in iter(range(num)): func(i, i, i) + bench.run(test) diff --git a/tests/bench/func_args-2-pos_default_2_of_3.py b/tests/bench/func_args-2-pos_default_2_of_3.py index 1fa0fbda59..4dc5650902 100644 --- a/tests/bench/func_args-2-pos_default_2_of_3.py +++ b/tests/bench/func_args-2-pos_default_2_of_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b=1, c=2): pass + def test(num): for i in iter(range(num)): func(i) + bench.run(test) diff --git a/tests/bench/func_args-3.1-kw_1.py b/tests/bench/func_args-3.1-kw_1.py index 7bc81e5bea..18252570c1 100644 --- a/tests/bench/func_args-3.1-kw_1.py +++ b/tests/bench/func_args-3.1-kw_1.py @@ -1,10 +1,13 @@ import bench + def func(a): pass + def test(num): for i in iter(range(num)): func(a=i) + bench.run(test) diff --git a/tests/bench/func_args-3.2-kw_3.py b/tests/bench/func_args-3.2-kw_3.py index 7f95106841..deac15cb41 100644 --- a/tests/bench/func_args-3.2-kw_3.py +++ b/tests/bench/func_args-3.2-kw_3.py @@ -1,10 +1,13 @@ import bench + def func(a, b, c): pass + def test(num): for i in iter(range(num)): func(c=i, b=i, a=i) + bench.run(test) diff --git a/tests/bench/func_builtin-1-enum_pos.py b/tests/bench/func_builtin-1-enum_pos.py index 20935164e8..c7c148df10 100644 --- a/tests/bench/func_builtin-1-enum_pos.py +++ b/tests/bench/func_builtin-1-enum_pos.py @@ -1,7 +1,9 @@ import bench + def test(num): - for i in iter(range(num//20)): + for i in iter(range(num // 20)): enumerate([1, 2], 1) + bench.run(test) diff --git a/tests/bench/func_builtin-2-enum_kw.py b/tests/bench/func_builtin-2-enum_kw.py index 6c5e44419c..a25ab241c6 100644 --- a/tests/bench/func_builtin-2-enum_kw.py +++ b/tests/bench/func_builtin-2-enum_kw.py @@ -1,7 +1,9 @@ import bench + def test(num): - for i in iter(range(num//20)): + for i in iter(range(num // 20)): enumerate(iterable=[1, 2], start=1) + bench.run(test) diff --git a/tests/bench/funcall-1-inline.py b/tests/bench/funcall-1-inline.py index fbeb79630d..8c3f0ccd59 100644 --- a/tests/bench/funcall-1-inline.py +++ b/tests/bench/funcall-1-inline.py @@ -2,8 +2,10 @@ # Establish a baseline for performing a trivial operation inline import bench + def test(num): for i in iter(range(num)): a = i + 1 + bench.run(test) diff --git a/tests/bench/funcall-2-funcall.py b/tests/bench/funcall-2-funcall.py index d5c36c60aa..a245258040 100644 --- a/tests/bench/funcall-2-funcall.py +++ b/tests/bench/funcall-2-funcall.py @@ -2,11 +2,14 @@ # Perform the same trivial operation as global function call import bench + def f(x): return x + 1 + def test(num): for i in iter(range(num)): a = f(i) + bench.run(test) diff --git a/tests/bench/funcall-3-funcall-local.py b/tests/bench/funcall-3-funcall-local.py index 1a6d728c63..d922888685 100644 --- a/tests/bench/funcall-3-funcall-local.py +++ b/tests/bench/funcall-3-funcall-local.py @@ -5,12 +5,15 @@ # variables are accessed by offset, not by name) import bench + def f(x): return x + 1 + def test(num): f_ = f for i in iter(range(num)): a = f_(i) + bench.run(test) diff --git a/tests/bench/loop_count-1-range.py b/tests/bench/loop_count-1-range.py index e22adf6cbe..fdb11eaac6 100644 --- a/tests/bench/loop_count-1-range.py +++ b/tests/bench/loop_count-1-range.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in range(num): pass + bench.run(test) diff --git a/tests/bench/loop_count-2-range_iter.py b/tests/bench/loop_count-2-range_iter.py index fe4a3857e1..4189bf329d 100644 --- a/tests/bench/loop_count-2-range_iter.py +++ b/tests/bench/loop_count-2-range_iter.py @@ -1,7 +1,9 @@ import bench + def test(num): for i in iter(range(num)): pass + bench.run(test) diff --git a/tests/bench/loop_count-3-while_up.py b/tests/bench/loop_count-3-while_up.py index 1ab8054a0f..22c64403bf 100644 --- a/tests/bench/loop_count-3-while_up.py +++ b/tests/bench/loop_count-3-while_up.py @@ -1,8 +1,10 @@ import bench + def test(num): i = 0 while i < num: i += 1 + bench.run(test) diff --git a/tests/bench/loop_count-4-while_down_gt.py b/tests/bench/loop_count-4-while_down_gt.py index de8dee2ca9..47b004c2bd 100644 --- a/tests/bench/loop_count-4-while_down_gt.py +++ b/tests/bench/loop_count-4-while_down_gt.py @@ -1,7 +1,9 @@ import bench + def test(num): while num > 0: num -= 1 + bench.run(test) diff --git a/tests/bench/loop_count-5-while_down_ne.py b/tests/bench/loop_count-5-while_down_ne.py index b9a1af414b..419c817c8f 100644 --- a/tests/bench/loop_count-5-while_down_ne.py +++ b/tests/bench/loop_count-5-while_down_ne.py @@ -1,7 +1,9 @@ import bench + def test(num): while num != 0: num -= 1 + bench.run(test) diff --git a/tests/bench/loop_count-5.1-while_down_ne_localvar.py b/tests/bench/loop_count-5.1-while_down_ne_localvar.py index 96bdb9129f..d25102a630 100644 --- a/tests/bench/loop_count-5.1-while_down_ne_localvar.py +++ b/tests/bench/loop_count-5.1-while_down_ne_localvar.py @@ -1,8 +1,10 @@ import bench + def test(num): zero = 0 while num != zero: num -= 1 + bench.run(test) diff --git a/tests/bench/var-1-constant.py b/tests/bench/var-1-constant.py index eec977909c..4a24194725 100644 --- a/tests/bench/var-1-constant.py +++ b/tests/bench/var-1-constant.py @@ -1,8 +1,10 @@ import bench + def test(num): i = 0 while i < 20000000: i += 1 + bench.run(test) diff --git a/tests/bench/var-2-global.py b/tests/bench/var-2-global.py index 5758ad61aa..a47240d646 100644 --- a/tests/bench/var-2-global.py +++ b/tests/bench/var-2-global.py @@ -2,9 +2,11 @@ import bench ITERS = 20000000 + def test(num): i = 0 while i < ITERS: i += 1 + bench.run(test) diff --git a/tests/bench/var-3-local.py b/tests/bench/var-3-local.py index 124b484295..182bb95f6f 100644 --- a/tests/bench/var-3-local.py +++ b/tests/bench/var-3-local.py @@ -7,4 +7,5 @@ def test(num): while i < ITERS: i += 1 + bench.run(test) diff --git a/tests/bench/var-4-arg.py b/tests/bench/var-4-arg.py index cf050c58fd..b9734357c8 100644 --- a/tests/bench/var-4-arg.py +++ b/tests/bench/var-4-arg.py @@ -6,4 +6,5 @@ def test(num): while i < num: i += 1 -bench.run(lambda n:test(20000000)) + +bench.run(lambda n: test(20000000)) diff --git a/tests/bench/var-5-class-attr.py b/tests/bench/var-5-class-attr.py index 02ae874ac2..e10770ee5b 100644 --- a/tests/bench/var-5-class-attr.py +++ b/tests/bench/var-5-class-attr.py @@ -1,11 +1,14 @@ import bench + class Foo: num = 20000000 + def test(num): i = 0 while i < Foo.num: i += 1 + bench.run(test) diff --git a/tests/bench/var-6-instance-attr.py b/tests/bench/var-6-instance-attr.py index 787ed870fb..0124ef51b3 100644 --- a/tests/bench/var-6-instance-attr.py +++ b/tests/bench/var-6-instance-attr.py @@ -1,14 +1,16 @@ import bench -class Foo: +class Foo: def __init__(self): self.num = 20000000 + def test(num): o = Foo() i = 0 while i < o.num: i += 1 + bench.run(test) diff --git a/tests/bench/var-6.1-instance-attr-5.py b/tests/bench/var-6.1-instance-attr-5.py index e8d3383605..692cef20df 100644 --- a/tests/bench/var-6.1-instance-attr-5.py +++ b/tests/bench/var-6.1-instance-attr-5.py @@ -1,7 +1,7 @@ import bench -class Foo: +class Foo: def __init__(self): self.num1 = 0 self.num2 = 0 @@ -9,10 +9,12 @@ class Foo: self.num4 = 0 self.num = 20000000 + def test(num): o = Foo() i = 0 while i < o.num: i += 1 + bench.run(test) diff --git a/tests/bench/var-7-instance-meth.py b/tests/bench/var-7-instance-meth.py index f9d463f40a..2ed7800be5 100644 --- a/tests/bench/var-7-instance-meth.py +++ b/tests/bench/var-7-instance-meth.py @@ -1,17 +1,19 @@ import bench -class Foo: +class Foo: def __init__(self): self._num = 20000000 def num(self): return self._num + def test(num): o = Foo() i = 0 while i < o.num(): i += 1 + bench.run(test) diff --git a/tests/bench/var-8-namedtuple-1st.py b/tests/bench/var-8-namedtuple-1st.py index 90ae7209d8..e3a2fa19cd 100644 --- a/tests/bench/var-8-namedtuple-1st.py +++ b/tests/bench/var-8-namedtuple-1st.py @@ -3,10 +3,12 @@ from collections import namedtuple T = namedtuple("Tup", ["num", "bar"]) + def test(num): t = T(20000000, 0) i = 0 while i < t.num: i += 1 + bench.run(test) diff --git a/tests/bench/var-8.1-namedtuple-5th.py b/tests/bench/var-8.1-namedtuple-5th.py index 0d5789d2ed..3e52121746 100644 --- a/tests/bench/var-8.1-namedtuple-5th.py +++ b/tests/bench/var-8.1-namedtuple-5th.py @@ -3,10 +3,12 @@ from collections import namedtuple T = namedtuple("Tup", ["foo1", "foo2", "foo3", "foo4", "num"]) + def test(num): t = T(0, 0, 0, 0, 20000000) i = 0 while i < t.num: i += 1 + bench.run(test) diff --git a/tests/circuitpython-manual/audiobusio/i2s_sample_loop.py b/tests/circuitpython-manual/audiobusio/i2s_sample_loop.py index c0ee5de315..8b40e916dc 100644 --- a/tests/circuitpython-manual/audiobusio/i2s_sample_loop.py +++ b/tests/circuitpython-manual/audiobusio/i2s_sample_loop.py @@ -24,8 +24,7 @@ for i in range(length): sample = audiocore.RawSample(s16, sample_rate=8000) -dac = audiobusio.I2SOut(bit_clock=board.D10, - word_select=board.D11, data=board.D12) +dac = audiobusio.I2SOut(bit_clock=board.D10, word_select=board.D11, data=board.D12) trigger.value = False dac.play(sample, loop=True) diff --git a/tests/circuitpython-manual/audiobusio/pdmin_rms.py b/tests/circuitpython-manual/audiobusio/pdmin_rms.py index 8d15957527..53a6fea156 100644 --- a/tests/circuitpython-manual/audiobusio/pdmin_rms.py +++ b/tests/circuitpython-manual/audiobusio/pdmin_rms.py @@ -8,19 +8,18 @@ import math trigger = digitalio.DigitalInOut(board.D4) trigger.switch_to_output(True) + def mean(values): return sum(values) / len(values) def normalized_rms(values): minbuf = int(mean(values)) - samples_sum = sum( - float(sample - minbuf) * (sample - minbuf) - for sample in values - ) + samples_sum = sum(float(sample - minbuf) * (sample - minbuf) for sample in values) return math.sqrt(samples_sum / len(values)) + # signed 16 bit s16 = array.array("H", [0] * 10000) diff --git a/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py b/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py index dfac475b5b..6013892a95 100644 --- a/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py +++ b/tests/circuitpython-manual/audiopwmio/single_buffer_loop.py @@ -13,12 +13,7 @@ trigger.switch_to_output(True) length = 8000 // 440 samples = [] -sample_names = [ -"unsigned 8 bit", -"signed 8 bit", -"unsigned 16 bit", -"signed 16 bit" -] +sample_names = ["unsigned 8 bit", "signed 8 bit", "unsigned 16 bit", "signed 16 bit"] # unsigned 8 bit diff --git a/tests/circuitpython-manual/busio/uart_echo.py b/tests/circuitpython-manual/busio/uart_echo.py index f55d4db9ec..d429c7781c 100644 --- a/tests/circuitpython-manual/busio/uart_echo.py +++ b/tests/circuitpython-manual/busio/uart_echo.py @@ -9,10 +9,10 @@ u = busio.UART(tx=board.TX, rx=board.RX) while True: u.write(str(i).encode("utf-8")) time.sleep(0.1) - print(i, u.in_waiting) # should be the number of digits + print(i, u.in_waiting) # should be the number of digits time.sleep(0.1) - print(i, u.in_waiting) # should be the number of digits + print(i, u.in_waiting) # should be the number of digits r = u.read(64 + 10) - print(i, u.in_waiting) # should be 0 + print(i, u.in_waiting) # should be 0 print(len(r), r) i += 1 diff --git a/tests/circuitpython-manual/socketpool/client/cpy-client.py b/tests/circuitpython-manual/socketpool/client/cpy-client.py index dcc742c9f8..a6e9e6b3e9 100644 --- a/tests/circuitpython-manual/socketpool/client/cpy-client.py +++ b/tests/circuitpython-manual/socketpool/client/cpy-client.py @@ -4,7 +4,7 @@ import ssl import time TIMEOUT = None -HOST = '192.168.10.179' +HOST = "192.168.10.179" PORT = 5000 # Connect to wifi @@ -19,7 +19,7 @@ with pool.socket(pool.AF_INET, pool.SOCK_STREAM) as s: print("Connecting") s.connect((HOST, PORT)) print("Sending") - sent = s.send(b'Hello, world') + sent = s.send(b"Hello, world") print("Receiving") buff = bytearray(128) numbytes = s.recv_into(buff) diff --git a/tests/circuitpython-manual/socketpool/client/host-server.py b/tests/circuitpython-manual/socketpool/client/host-server.py index fd7ceb7f14..49da4055f9 100644 --- a/tests/circuitpython-manual/socketpool/client/host-server.py +++ b/tests/circuitpython-manual/socketpool/client/host-server.py @@ -20,7 +20,7 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: with conn: s.settimeout(TIMEOUT) - print('Connected by', addr) + print("Connected by", addr) data = conn.recv(128) print("got: " + str(data)) conn.sendall(data) diff --git a/tests/circuitpython-manual/socketpool/datagram/ntp.py b/tests/circuitpython-manual/socketpool/datagram/ntp.py index 31d922858a..df5fadb138 100644 --- a/tests/circuitpython-manual/socketpool/datagram/ntp.py +++ b/tests/circuitpython-manual/socketpool/datagram/ntp.py @@ -10,7 +10,7 @@ pool = socketpool.SocketPool(wifi.radio) # make socket print("Creating socket") -sock = pool.socket(pool.AF_INET,pool.SOCK_DGRAM) +sock = pool.socket(pool.AF_INET, pool.SOCK_DGRAM) # Fill packet packet = bytearray(48) diff --git a/tests/circuitpython-manual/socketpool/server/cpy-server.py b/tests/circuitpython-manual/socketpool/server/cpy-server.py index d865156bc8..bce1f9d6a2 100644 --- a/tests/circuitpython-manual/socketpool/server/cpy-server.py +++ b/tests/circuitpython-manual/socketpool/server/cpy-server.py @@ -11,21 +11,21 @@ pool = socketpool.SocketPool(wifi.radio) print("Finding IP address") print(wifi.radio.ipv4_address) HOST = str(wifi.radio.ipv4_address) -PORT = 80 # Port to listen on +PORT = 80 # Port to listen on print("Creating socket") -sock = pool.socket(pool.AF_INET,pool.SOCK_STREAM) +sock = pool.socket(pool.AF_INET, pool.SOCK_STREAM) sock.bind((HOST, PORT)) sock.listen(1) print("Accepting connections") conn, addr = sock.accept() with conn: - print('Connected by', addr) + print("Connected by", addr) buff = bytearray(128) print("Receiving") numbytes = conn.recvfrom_into(buff) - print(buff[:numbytes[0]]) + print(buff[: numbytes[0]]) if numbytes: print("Sending") - conn.send(buff[:numbytes[0]]) + conn.send(buff[: numbytes[0]]) diff --git a/tests/circuitpython-manual/socketpool/server/host-client.py b/tests/circuitpython-manual/socketpool/server/host-client.py index b482755d88..e2cc77c4e6 100644 --- a/tests/circuitpython-manual/socketpool/server/host-client.py +++ b/tests/circuitpython-manual/socketpool/server/host-client.py @@ -1,7 +1,7 @@ import socket -HOST = '192.168.10.128' # The server's hostname or IP address -PORT = 80 # The port used by the server +HOST = "192.168.10.128" # The server's hostname or IP address +PORT = 80 # The port used by the server with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(None) @@ -10,8 +10,8 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.connect((HOST, PORT)) print("Sending") - s.send(b'Hello, world') + s.send(b"Hello, world") print("Receiving") data = s.recv(1024) - print('Received', repr(data)) + print("Received", repr(data)) diff --git a/tests/circuitpython/nvm_not_present.py b/tests/circuitpython/nvm_not_present.py index 141e60b01e..53ad3ada5b 100644 --- a/tests/circuitpython/nvm_not_present.py +++ b/tests/circuitpython/nvm_not_present.py @@ -1,6 +1,7 @@ import skip_if + skip_if.board_not_in("gemma_m0", "trinket_m0") import microcontroller -assert(microcontroller.nvm == None) +assert microcontroller.nvm == None diff --git a/tests/circuitpython/nvm_present.py b/tests/circuitpython/nvm_present.py index bef80dcc61..ceaadc60bf 100644 --- a/tests/circuitpython/nvm_present.py +++ b/tests/circuitpython/nvm_present.py @@ -1,24 +1,26 @@ import skip_if + # TODO(tannewt): Remove this when we add nvm support to 3.x skip_if.always() skip_if.board_not_in("metro_m0_express", "feather_m0_express", "circuitplayground_express") import microcontroller import random + nvm = microcontroller.nvm len(nvm) single = random.randint(0, 255) nvm[1] = single -assert(nvm[1] == single) +assert nvm[1] == single nvm[0] = single -assert(nvm[0] == single) +assert nvm[0] == single b = bytearray() for i in range(10): b.append(random.randint(0, 255)) microcontroller.nvm[10:20] = b -assert(microcontroller.nvm[10:20] == b) +assert microcontroller.nvm[10:20] == b diff --git a/tests/cmdline/cmd_parsetree.py b/tests/cmdline/cmd_parsetree.py index da36c80703..50da369543 100644 --- a/tests/cmdline/cmd_parsetree.py +++ b/tests/cmdline/cmd_parsetree.py @@ -4,9 +4,9 @@ for i in (): pass a = None -b = 'str' -c = 'a very long str that will not be interned' -d = b'bytes' -e = b'a very long bytes that will not be interned' +b = "str" +c = "a very long str that will not be interned" +d = b"bytes" +e = b"a very long bytes that will not be interned" f = 123456789012345678901234567890 g = 123 diff --git a/tests/cmdline/cmd_showbc.py b/tests/cmdline/cmd_showbc.py index 6e99fc4189..58f8a7f70d 100644 --- a/tests/cmdline/cmd_showbc.py +++ b/tests/cmdline/cmd_showbc.py @@ -1,5 +1,6 @@ # cmdline: -v -v # test printing of all bytecodes +# fmt: off def f(): # constants diff --git a/tests/cpydiff/core_class_delnotimpl.py b/tests/cpydiff/core_class_delnotimpl.py index c51c3d536f..18c176e9bb 100644 --- a/tests/cpydiff/core_class_delnotimpl.py +++ b/tests/cpydiff/core_class_delnotimpl.py @@ -6,9 +6,11 @@ workaround: Unknown """ import gc -class Foo(): + +class Foo: def __del__(self): - print('__del__') + print("__del__") + f = Foo() del f diff --git a/tests/cpydiff/core_class_mro.py b/tests/cpydiff/core_class_mro.py index 99713e790c..bdd6dd5df6 100644 --- a/tests/cpydiff/core_class_mro.py +++ b/tests/cpydiff/core_class_mro.py @@ -4,12 +4,16 @@ description: Method Resolution Order (MRO) is not compliant with CPython cause: Depth first non-exhaustive method resolution order workaround: Avoid complex class hierarchies with multiple inheritance and complex method overrides. Keep in mind that many languages don't support multiple inheritance at all. """ + + class Foo: def __str__(self): return "Foo" + class C(tuple, Foo): pass + t = C((1, 2, 3)) print(t) diff --git a/tests/cpydiff/core_class_supermultiple.py b/tests/cpydiff/core_class_supermultiple.py index f0823ee11d..9a87b85a87 100644 --- a/tests/cpydiff/core_class_supermultiple.py +++ b/tests/cpydiff/core_class_supermultiple.py @@ -4,24 +4,29 @@ description: When inheriting from multiple classes super() only calls one class cause: See :ref:`cpydiff_core_class_mro` workaround: See :ref:`cpydiff_core_class_mro` """ + + class A: def __init__(self): print("A.__init__") + class B(A): def __init__(self): print("B.__init__") super().__init__() + class C(A): def __init__(self): print("C.__init__") super().__init__() -class D(B,C): +class D(B, C): def __init__(self): print("D.__init__") super().__init__() + D() diff --git a/tests/cpydiff/core_function_userattr.py b/tests/cpydiff/core_function_userattr.py index 2972939084..a8380c690a 100644 --- a/tests/cpydiff/core_function_userattr.py +++ b/tests/cpydiff/core_function_userattr.py @@ -4,8 +4,11 @@ description: User-defined attributes for functions are not supported cause: MicroPython is highly optimized for memory usage. workaround: Use external dictionary, e.g. ``FUNC_X[f] = 0``. """ + + def f(): pass + f.x = 0 print(f.x) diff --git a/tests/cpydiff/core_generator_noexit.py b/tests/cpydiff/core_generator_noexit.py index c25fbe75a2..149e9a0a90 100644 --- a/tests/cpydiff/core_generator_noexit.py +++ b/tests/cpydiff/core_generator_noexit.py @@ -4,11 +4,15 @@ description: Context manager __exit__() not called in a generator which does not cause: Unknown workaround: Unknown """ + + class foo(object): def __enter__(self): - print('Enter') + print("Enter") + def __exit__(self, *args): - print('Exit') + print("Exit") + def bar(x): with foo(): @@ -16,9 +20,11 @@ def bar(x): x += 1 yield x + def func(): g = bar(0) for _ in range(3): print(next(g)) + func() diff --git a/tests/cpydiff/core_import_prereg.py b/tests/cpydiff/core_import_prereg.py index 4a71217821..3ce2340c68 100644 --- a/tests/cpydiff/core_import_prereg.py +++ b/tests/cpydiff/core_import_prereg.py @@ -12,6 +12,7 @@ except NameError as e: print(e) try: from modules import foo - print('Should not get here') + + print("Should not get here") except NameError as e: print(e) diff --git a/tests/cpydiff/core_import_split_ns_pkgs.py b/tests/cpydiff/core_import_split_ns_pkgs.py index 700620c470..62bf337a22 100644 --- a/tests/cpydiff/core_import_split_ns_pkgs.py +++ b/tests/cpydiff/core_import_split_ns_pkgs.py @@ -5,6 +5,7 @@ cause: MicroPython's import system is highly optimized for simplicity, minimal m workaround: Don't install modules belonging to the same namespace package in different directories. For MicroPython, it's recommended to have at most 3-component module search paths: for your current application, per-user (writable), system-wide (non-writable). """ import sys + sys.path.append(sys.path[1] + "/modules") sys.path.append(sys.path[1] + "/modules2") diff --git a/tests/cpydiff/core_locals.py b/tests/cpydiff/core_locals.py index 0240e5a1a9..af3280c6d7 100644 --- a/tests/cpydiff/core_locals.py +++ b/tests/cpydiff/core_locals.py @@ -4,8 +4,11 @@ description: Local variables aren't included in locals() result cause: MicroPython doesn't maintain symbolic local environment, it is optimized to an array of slots. Thus, local variables can't be accessed by a name. workaround: Unknown """ + + def test(): val = 2 print(locals()) + test() diff --git a/tests/cpydiff/core_locals_eval.py b/tests/cpydiff/core_locals_eval.py index 8416e3b069..025d226372 100644 --- a/tests/cpydiff/core_locals_eval.py +++ b/tests/cpydiff/core_locals_eval.py @@ -6,9 +6,11 @@ workaround: Unknown """ val = 1 + def test(): val = 2 print(val) eval("print(val)") + test() diff --git a/tests/cpydiff/modules/foo.py b/tests/cpydiff/modules/foo.py index e6e33a7b46..51cd4b2490 100644 --- a/tests/cpydiff/modules/foo.py +++ b/tests/cpydiff/modules/foo.py @@ -1,2 +1,2 @@ -print('foo') +print("foo") xxx diff --git a/tests/cpydiff/modules_array_containment.py b/tests/cpydiff/modules_array_containment.py index 190a3c2760..8f25b0d491 100644 --- a/tests/cpydiff/modules_array_containment.py +++ b/tests/cpydiff/modules_array_containment.py @@ -5,4 +5,5 @@ cause: Unknown workaround: Unknown """ import array -print(1 in array.array('B', b'12')) + +print(1 in array.array("B", b"12")) diff --git a/tests/cpydiff/modules_array_deletion.py b/tests/cpydiff/modules_array_deletion.py index 97f988da23..3376527373 100644 --- a/tests/cpydiff/modules_array_deletion.py +++ b/tests/cpydiff/modules_array_deletion.py @@ -5,6 +5,7 @@ cause: Unknown workaround: Unknown """ import array -a = array.array('b', (1, 2, 3)) + +a = array.array("b", (1, 2, 3)) del a[1] print(a) diff --git a/tests/cpydiff/modules_array_subscrstep.py b/tests/cpydiff/modules_array_subscrstep.py index 1103f18269..24308bd904 100644 --- a/tests/cpydiff/modules_array_subscrstep.py +++ b/tests/cpydiff/modules_array_subscrstep.py @@ -5,5 +5,6 @@ cause: Unknown workaround: Unknown """ import array -a = array.array('b', (1, 2, 3)) + +a = array.array("b", (1, 2, 3)) print(a[3:2:2]) diff --git a/tests/cpydiff/modules_deque.py b/tests/cpydiff/modules_deque.py index a503ea4f55..4d2746d1f8 100644 --- a/tests/cpydiff/modules_deque.py +++ b/tests/cpydiff/modules_deque.py @@ -5,5 +5,6 @@ cause: Unknown workaround: Use regular lists. micropython-lib has implementation of collections.deque. """ import collections + D = collections.deque() print(D) diff --git a/tests/cpydiff/modules_json_nonserializable.py b/tests/cpydiff/modules_json_nonserializable.py index 913b734e8b..ffe523786f 100644 --- a/tests/cpydiff/modules_json_nonserializable.py +++ b/tests/cpydiff/modules_json_nonserializable.py @@ -5,10 +5,11 @@ cause: Unknown workaround: Unknown """ import json + a = bytes(x for x in range(256)) try: z = json.dumps(a) x = json.loads(z) - print('Should not get here') + print("Should not get here") except TypeError: - print('TypeError') + print("TypeError") diff --git a/tests/cpydiff/modules_struct_fewargs.py b/tests/cpydiff/modules_struct_fewargs.py index 08d32ca672..cb6b0fd874 100644 --- a/tests/cpydiff/modules_struct_fewargs.py +++ b/tests/cpydiff/modules_struct_fewargs.py @@ -5,8 +5,9 @@ cause: Unknown workaround: Unknown """ import struct + try: - print(struct.pack('bb', 1)) - print('Should not get here') + print(struct.pack("bb", 1)) + print("Should not get here") except: - print('struct.error') + print("struct.error") diff --git a/tests/cpydiff/modules_struct_manyargs.py b/tests/cpydiff/modules_struct_manyargs.py index cdbb5c672c..03395baad3 100644 --- a/tests/cpydiff/modules_struct_manyargs.py +++ b/tests/cpydiff/modules_struct_manyargs.py @@ -5,8 +5,9 @@ cause: Unknown workaround: Unknown """ import struct + try: - print(struct.pack('bb', 1, 2, 3)) - print('Should not get here') + print(struct.pack("bb", 1, 2, 3)) + print("Should not get here") except: - print('struct.error') + print("struct.error") diff --git a/tests/cpydiff/modules_sys_stdassign.py b/tests/cpydiff/modules_sys_stdassign.py index 1bf2a598a0..7d086078a9 100644 --- a/tests/cpydiff/modules_sys_stdassign.py +++ b/tests/cpydiff/modules_sys_stdassign.py @@ -5,5 +5,6 @@ cause: They are stored in read-only memory. workaround: Unknown """ import sys + sys.stdin = None print(sys.stdin) diff --git a/tests/cpydiff/syntax_spaces.py b/tests/cpydiff/syntax_spaces.py index 8578a51e28..c308240a78 100644 --- a/tests/cpydiff/syntax_spaces.py +++ b/tests/cpydiff/syntax_spaces.py @@ -5,14 +5,14 @@ cause: Unknown workaround: Unknown """ try: - print(eval('1and 0')) + print(eval("1and 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") try: - print(eval('1or 0')) + print(eval("1or 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") try: - print(eval('1if 1else 0')) + print(eval("1if 1else 0")) except SyntaxError: - print('Should have worked') + print("Should have worked") diff --git a/tests/cpydiff/types_bytes_keywords.py b/tests/cpydiff/types_bytes_keywords.py index 4dc383f262..550ce12bbd 100644 --- a/tests/cpydiff/types_bytes_keywords.py +++ b/tests/cpydiff/types_bytes_keywords.py @@ -4,4 +4,4 @@ description: bytes() with keywords not implemented cause: Unknown workaround: Pass the encoding as a positional paramter, e.g. ``print(bytes('abc', 'utf-8'))`` """ -print(bytes('abc', encoding='utf8')) +print(bytes("abc", encoding="utf8")) diff --git a/tests/cpydiff/types_bytes_subscrstep.py b/tests/cpydiff/types_bytes_subscrstep.py index 2871bda6c1..51b94cb710 100644 --- a/tests/cpydiff/types_bytes_subscrstep.py +++ b/tests/cpydiff/types_bytes_subscrstep.py @@ -4,4 +4,4 @@ description: Bytes subscription with step != 1 not implemented cause: MicroPython is highly optimized for memory usage. workaround: Use explicit loop for this very rare operation. """ -print(b'123'[0:3:2]) +print(b"123"[0:3:2]) diff --git a/tests/cpydiff/types_exception_subclassinit.py b/tests/cpydiff/types_exception_subclassinit.py index 39cdaf45b8..ade9ebc7ab 100644 --- a/tests/cpydiff/types_exception_subclassinit.py +++ b/tests/cpydiff/types_exception_subclassinit.py @@ -8,8 +8,11 @@ workaround: Call using ``super()`` instead:: def __init__(self): super().__init__() """ + + class A(Exception): def __init__(self): Exception.__init__(self) + a = A() diff --git a/tests/cpydiff/types_float_rounding.py b/tests/cpydiff/types_float_rounding.py index c8d3cfbe88..a5b591966b 100644 --- a/tests/cpydiff/types_float_rounding.py +++ b/tests/cpydiff/types_float_rounding.py @@ -4,4 +4,4 @@ description: uPy and CPython outputs formats may differ cause: Unknown workaround: Unknown """ -print('%.1g' % -9.9) +print("%.1g" % -9.9) diff --git a/tests/cpydiff/types_int_subclassconv.py b/tests/cpydiff/types_int_subclassconv.py index 260b060ed6..5d337412c7 100644 --- a/tests/cpydiff/types_int_subclassconv.py +++ b/tests/cpydiff/types_int_subclassconv.py @@ -4,8 +4,11 @@ description: No int conversion for int-derived types available cause: Unknown workaround: Avoid subclassing builtin types unless really needed. Prefer https://en.wikipedia.org/wiki/Composition_over_inheritance . """ + + class A(int): __add__ = lambda self, other: A(int(self) + other) + a = A(42) -print(a+a) +print(a + a) diff --git a/tests/cpydiff/types_str_endswith.py b/tests/cpydiff/types_str_endswith.py index ac2600bd25..f222ac1cd3 100644 --- a/tests/cpydiff/types_str_endswith.py +++ b/tests/cpydiff/types_str_endswith.py @@ -4,4 +4,4 @@ description: Start/end indices such as str.endswith(s, start) not implemented cause: Unknown workaround: Unknown """ -print('abc'.endswith('c', 1)) +print("abc".endswith("c", 1)) diff --git a/tests/cpydiff/types_str_formatsubscr.py b/tests/cpydiff/types_str_formatsubscr.py index dd1d8d33d7..1b83cfff6c 100644 --- a/tests/cpydiff/types_str_formatsubscr.py +++ b/tests/cpydiff/types_str_formatsubscr.py @@ -4,4 +4,4 @@ description: Attributes/subscr not implemented cause: Unknown workaround: Unknown """ -print('{a[0]}'.format(a=[1, 2])) +print("{a[0]}".format(a=[1, 2])) diff --git a/tests/cpydiff/types_str_keywords.py b/tests/cpydiff/types_str_keywords.py index b336b1a73e..77a4eac1c1 100644 --- a/tests/cpydiff/types_str_keywords.py +++ b/tests/cpydiff/types_str_keywords.py @@ -4,4 +4,4 @@ description: str(...) with keywords not implemented cause: Unknown workaround: Input the encoding format directly. eg ``print(bytes('abc', 'utf-8'))`` """ -print(str(b'abc', encoding='utf8')) +print(str(b"abc", encoding="utf8")) diff --git a/tests/cpydiff/types_str_ljust_rjust.py b/tests/cpydiff/types_str_ljust_rjust.py index fa3f594c1f..72e5105e02 100644 --- a/tests/cpydiff/types_str_ljust_rjust.py +++ b/tests/cpydiff/types_str_ljust_rjust.py @@ -4,4 +4,4 @@ description: str.ljust() and str.rjust() not implemented cause: MicroPython is highly optimized for memory usage. Easy workarounds available. workaround: Instead of ``s.ljust(10)`` use ``"%-10s" % s``, instead of ``s.rjust(10)`` use ``"% 10s" % s``. Alternatively, ``"{:<10}".format(s)`` or ``"{:>10}".format(s)``. """ -print('abc'.ljust(10)) +print("abc".ljust(10)) diff --git a/tests/cpydiff/types_str_rsplitnone.py b/tests/cpydiff/types_str_rsplitnone.py index cadf869877..5d334fea2f 100644 --- a/tests/cpydiff/types_str_rsplitnone.py +++ b/tests/cpydiff/types_str_rsplitnone.py @@ -4,4 +4,4 @@ description: None as first argument for rsplit such as str.rsplit(None, n) not i cause: Unknown workaround: Unknown """ -print('a a a'.rsplit(None, 1)) +print("a a a".rsplit(None, 1)) diff --git a/tests/cpydiff/types_str_subclassequality.py b/tests/cpydiff/types_str_subclassequality.py index 8aec1ea78f..e44198fccf 100644 --- a/tests/cpydiff/types_str_subclassequality.py +++ b/tests/cpydiff/types_str_subclassequality.py @@ -4,8 +4,11 @@ description: Instance of a subclass of str cannot be compared for equality with cause: Unknown workaround: Unknown """ + + class S(str): pass -s = S('hello') -print(s == 'hello') + +s = S("hello") +print(s == "hello") diff --git a/tests/cpydiff/types_str_subscrstep.py b/tests/cpydiff/types_str_subscrstep.py index 0c2fce1b11..2d3245e558 100644 --- a/tests/cpydiff/types_str_subscrstep.py +++ b/tests/cpydiff/types_str_subscrstep.py @@ -4,4 +4,4 @@ description: Subscript with step != 1 is not yet implemented cause: Unknown workaround: Unknown """ -print('abcdefghi'[0:9:2]) +print("abcdefghi"[0:9:2]) diff --git a/tests/extmod/btree1.py b/tests/extmod/btree1.py index 59638ef0a4..4890d92b42 100644 --- a/tests/extmod/btree1.py +++ b/tests/extmod/btree1.py @@ -6,7 +6,7 @@ except ImportError: print("SKIP") raise SystemExit -#f = open("_test.db", "w+b") +# f = open("_test.db", "w+b") f = uio.BytesIO() db = btree.open(f, pagesize=512) diff --git a/tests/extmod/framebuf1.py b/tests/extmod/framebuf1.py index 2c13665228..c8e0132265 100644 --- a/tests/extmod/framebuf1.py +++ b/tests/extmod/framebuf1.py @@ -8,9 +8,11 @@ w = 5 h = 16 size = w * h // 8 buf = bytearray(size) -maps = {framebuf.MONO_VLSB : 'MONO_VLSB', - framebuf.MONO_HLSB : 'MONO_HLSB', - framebuf.MONO_HMSB : 'MONO_HMSB'} +maps = { + framebuf.MONO_VLSB: "MONO_VLSB", + framebuf.MONO_HLSB: "MONO_HLSB", + framebuf.MONO_HMSB: "MONO_HMSB", +} for mapping in maps.keys(): for x in range(size): @@ -43,33 +45,33 @@ for mapping in maps.keys(): # hline fbuf.fill(0) fbuf.hline(0, 1, w, 1) - print('hline', buf) + print("hline", buf) # vline fbuf.fill(0) fbuf.vline(1, 0, h, 1) - print('vline', buf) + print("vline", buf) # rect fbuf.fill(0) fbuf.rect(1, 1, 3, 3, 1) - print('rect', buf) + print("rect", buf) - #fill rect + # fill rect fbuf.fill(0) - fbuf.fill_rect(0, 0, 0, 3, 1) # zero width, no-operation + fbuf.fill_rect(0, 0, 0, 3, 1) # zero width, no-operation fbuf.fill_rect(1, 1, 3, 3, 1) - print('fill_rect', buf) + print("fill_rect", buf) # line fbuf.fill(0) fbuf.line(1, 1, 3, 3, 1) - print('line', buf) + print("line", buf) # line steep negative gradient fbuf.fill(0) fbuf.line(3, 3, 2, 1, 1) - print('line', buf) + print("line", buf) # scroll fbuf.fill(0) @@ -89,7 +91,7 @@ for mapping in maps.keys(): fbuf.fill(0) fbuf.text("hello", 0, 0, 1) print(buf) - fbuf.text("hello", 0, 0, 0) # clear + fbuf.text("hello", 0, 0, 0) # clear print(buf) # char out of font range set to chr(127) diff --git a/tests/extmod/framebuf16.py b/tests/extmod/framebuf16.py index fe81f7f93f..e658f1345a 100644 --- a/tests/extmod/framebuf16.py +++ b/tests/extmod/framebuf16.py @@ -4,28 +4,30 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): - print(buf[y * w * 2:(y + 1) * w * 2]) + print(buf[y * w * 2 : (y + 1) * w * 2]) print("-->8--") + w = 4 h = 5 buf = bytearray(w * h * 2) fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.RGB565) # fill -fbuf.fill(0xffff) +fbuf.fill(0xFFFF) printbuf() fbuf.fill(0x0000) printbuf() # put pixel -fbuf.pixel(0, 0, 0xeeee) -fbuf.pixel(3, 0, 0xee00) -fbuf.pixel(0, 4, 0x00ee) -fbuf.pixel(3, 4, 0x0ee0) +fbuf.pixel(0, 0, 0xEEEE) +fbuf.pixel(3, 0, 0xEE00) +fbuf.pixel(0, 4, 0x00EE) +fbuf.pixel(3, 4, 0x0EE0) printbuf() # get pixel @@ -33,7 +35,7 @@ print(fbuf.pixel(0, 4), fbuf.pixel(1, 1)) # scroll fbuf.fill(0x0000) -fbuf.pixel(2, 2, 0xffff) +fbuf.pixel(2, 2, 0xFFFF) printbuf() fbuf.scroll(0, 1) printbuf() @@ -48,11 +50,11 @@ buf2 = bytearray(w2 * h2 * 2) fbuf2 = framebuf.FrameBuffer(buf2, w2, h2, framebuf.RGB565) fbuf2.fill(0x0000) -fbuf2.pixel(0, 0, 0x0ee0) -fbuf2.pixel(0, 2, 0xee00) -fbuf2.pixel(1, 0, 0x00ee) -fbuf2.pixel(1, 2, 0xe00e) -fbuf.fill(0xffff) +fbuf2.pixel(0, 0, 0x0EE0) +fbuf2.pixel(0, 2, 0xEE00) +fbuf2.pixel(1, 0, 0x00EE) +fbuf2.pixel(1, 2, 0xE00E) +fbuf.fill(0xFFFF) fbuf.blit(fbuf2, 3, 3, 0x0000) fbuf.blit(fbuf2, -1, -1, 0x0000) fbuf.blit(fbuf2, 16, 16, 0x0000) diff --git a/tests/extmod/framebuf2.py b/tests/extmod/framebuf2.py index a313170eb5..097057fe96 100644 --- a/tests/extmod/framebuf2.py +++ b/tests/extmod/framebuf2.py @@ -4,14 +4,16 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): for x in range(w): - print('%u' % ((buf[(x + y * w) // 4] >> ((x & 3) << 1)) & 3), end='') + print("%u" % ((buf[(x + y * w) // 4] >> ((x & 3) << 1)) & 3), end="") print() print("-->8--") + w = 8 h = 5 buf = bytearray(w * h // 4) diff --git a/tests/extmod/framebuf4.py b/tests/extmod/framebuf4.py index 8358fa55b9..56593ee155 100644 --- a/tests/extmod/framebuf4.py +++ b/tests/extmod/framebuf4.py @@ -4,50 +4,52 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): - print(buf[y * w // 2:(y + 1) * w // 2]) + print(buf[y * w // 2 : (y + 1) * w // 2]) print("-->8--") + w = 16 h = 8 buf = bytearray(w * h // 2) fbuf = framebuf.FrameBuffer(buf, w, h, framebuf.GS4_HMSB) # fill -fbuf.fill(0x0f) +fbuf.fill(0x0F) printbuf() -fbuf.fill(0xa0) +fbuf.fill(0xA0) printbuf() # put pixel fbuf.pixel(0, 0, 0x01) printbuf() -fbuf.pixel(w-1, 0, 0x02) +fbuf.pixel(w - 1, 0, 0x02) printbuf() -fbuf.pixel(w-1, h-1, 0x03) +fbuf.pixel(w - 1, h - 1, 0x03) printbuf() -fbuf.pixel(0, h-1, 0x04) +fbuf.pixel(0, h - 1, 0x04) printbuf() # get pixel -print(fbuf.pixel(0, 0), fbuf.pixel(w-1, 0), fbuf.pixel(w-1, h-1), fbuf.pixel(0, h-1)) -print(fbuf.pixel(1, 0), fbuf.pixel(w-2, 0), fbuf.pixel(w-2, h-1), fbuf.pixel(1, h-1)) +print(fbuf.pixel(0, 0), fbuf.pixel(w - 1, 0), fbuf.pixel(w - 1, h - 1), fbuf.pixel(0, h - 1)) +print(fbuf.pixel(1, 0), fbuf.pixel(w - 2, 0), fbuf.pixel(w - 2, h - 1), fbuf.pixel(1, h - 1)) # fill rect -fbuf.fill_rect(0, 0, w, h, 0x0f) +fbuf.fill_rect(0, 0, w, h, 0x0F) printbuf() -fbuf.fill_rect(0, 0, w, h, 0xf0) -fbuf.fill_rect(1, 0, w//2+1, 1, 0xf1) +fbuf.fill_rect(0, 0, w, h, 0xF0) +fbuf.fill_rect(1, 0, w // 2 + 1, 1, 0xF1) printbuf() -fbuf.fill_rect(1, 0, w//2+1, 1, 0x10) -fbuf.fill_rect(1, 0, w//2, 1, 0xf1) +fbuf.fill_rect(1, 0, w // 2 + 1, 1, 0x10) +fbuf.fill_rect(1, 0, w // 2, 1, 0xF1) printbuf() -fbuf.fill_rect(1, 0, w//2, 1, 0x10) -fbuf.fill_rect(0, h-4, w//2+1, 4, 0xaf) +fbuf.fill_rect(1, 0, w // 2, 1, 0x10) +fbuf.fill_rect(0, h - 4, w // 2 + 1, 4, 0xAF) printbuf() -fbuf.fill_rect(0, h-4, w//2+1, 4, 0xb0) -fbuf.fill_rect(0, h-4, w//2, 4, 0xaf) +fbuf.fill_rect(0, h - 4, w // 2 + 1, 4, 0xB0) +fbuf.fill_rect(0, h - 4, w // 2, 4, 0xAF) printbuf() -fbuf.fill_rect(0, h-4, w//2, 4, 0xb0) +fbuf.fill_rect(0, h - 4, w // 2, 4, 0xB0) diff --git a/tests/extmod/framebuf8.py b/tests/extmod/framebuf8.py index b6899aae91..a3ca6fcd4f 100644 --- a/tests/extmod/framebuf8.py +++ b/tests/extmod/framebuf8.py @@ -4,14 +4,16 @@ except ImportError: print("SKIP") raise SystemExit + def printbuf(): print("--8<--") for y in range(h): for x in range(w): - print('%02x' % buf[(x + y * w)], end='') + print("%02x" % buf[(x + y * w)], end="") print() print("-->8--") + w = 8 h = 5 buf = bytearray(w * h) @@ -25,7 +27,7 @@ printbuf() fbuf.pixel(0, 0, 0x11) fbuf.pixel(w - 1, 0, 0x22) fbuf.pixel(0, h - 1, 0x33) -fbuf.pixel(w - 1, h - 1, 0xff) +fbuf.pixel(w - 1, h - 1, 0xFF) printbuf() # get pixel diff --git a/tests/extmod/framebuf_subclass.py b/tests/extmod/framebuf_subclass.py index 6363c224fb..b429776bc2 100644 --- a/tests/extmod/framebuf_subclass.py +++ b/tests/extmod/framebuf_subclass.py @@ -3,9 +3,10 @@ try: import framebuf except ImportError: - print('SKIP') + print("SKIP") raise SystemExit + class FB(framebuf.FrameBuffer): def __init__(self, n): self.n = n @@ -14,6 +15,7 @@ class FB(framebuf.FrameBuffer): def foo(self): self.hline(0, 2, self.n, 0x0304) + fb = FB(n=3) fb.pixel(0, 0, 0x0102) fb.foo() diff --git a/tests/extmod/machine_pinbase.py b/tests/extmod/machine_pinbase.py index e91775504d..f6b27d1d1d 100644 --- a/tests/extmod/machine_pinbase.py +++ b/tests/extmod/machine_pinbase.py @@ -10,7 +10,6 @@ except AttributeError: class MyPin(machine.PinBase): - def __init__(self): print("__init__") self.v = False @@ -21,6 +20,7 @@ class MyPin(machine.PinBase): self.v = not self.v return int(self.v) + p = MyPin() print(p.value()) diff --git a/tests/extmod/machine_pulse.py b/tests/extmod/machine_pulse.py index d525974e0c..7a8fe14d06 100644 --- a/tests/extmod/machine_pulse.py +++ b/tests/extmod/machine_pulse.py @@ -11,7 +11,6 @@ except AttributeError: class ConstPin(machine.PinBase): - def __init__(self, value): self.v = value @@ -23,7 +22,6 @@ class ConstPin(machine.PinBase): class TogglePin(machine.PinBase): - def __init__(self): self.v = 0 diff --git a/tests/extmod/machine_signal.py b/tests/extmod/machine_signal.py index 53f4f5890c..c453098402 100644 --- a/tests/extmod/machine_signal.py +++ b/tests/extmod/machine_signal.py @@ -11,6 +11,7 @@ except AttributeError: print("SKIP") raise SystemExit + class Pin(machine.PinBase): def __init__(self): self.v = 0 diff --git a/tests/extmod/time_ms_us.py b/tests/extmod/time_ms_us.py index 135cf1e096..0e4749b898 100644 --- a/tests/extmod/time_ms_us.py +++ b/tests/extmod/time_ms_us.py @@ -1,4 +1,5 @@ import utime + try: utime.sleep_ms except AttributeError: diff --git a/tests/extmod/ubinascii_a2b_base64.py b/tests/extmod/ubinascii_a2b_base64.py index 5e642ec515..39b85274b6 100644 --- a/tests/extmod/ubinascii_a2b_base64.py +++ b/tests/extmod/ubinascii_a2b_base64.py @@ -7,43 +7,43 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.a2b_base64(b'')) -print(binascii.a2b_base64(b'Zg==')) -print(binascii.a2b_base64(b'Zm8=')) -print(binascii.a2b_base64(b'Zm9v')) -print(binascii.a2b_base64(b'Zm9vYg==')) -print(binascii.a2b_base64(b'Zm9vYmE=')) -print(binascii.a2b_base64(b'Zm9vYmFy')) +print(binascii.a2b_base64(b"")) +print(binascii.a2b_base64(b"Zg==")) +print(binascii.a2b_base64(b"Zm8=")) +print(binascii.a2b_base64(b"Zm9v")) +print(binascii.a2b_base64(b"Zm9vYg==")) +print(binascii.a2b_base64(b"Zm9vYmE=")) +print(binascii.a2b_base64(b"Zm9vYmFy")) -print(binascii.a2b_base64(b'AAECAwQFBgc=')) -print(binascii.a2b_base64(b'CAkKCwwNDg8=')) -print(binascii.a2b_base64(b'f4D/')) -print(binascii.a2b_base64(b'f4D+')) # convert '+' -print(binascii.a2b_base64(b'MTIzNEFCQ0RhYmNk')) +print(binascii.a2b_base64(b"AAECAwQFBgc=")) +print(binascii.a2b_base64(b"CAkKCwwNDg8=")) +print(binascii.a2b_base64(b"f4D/")) +print(binascii.a2b_base64(b"f4D+")) # convert '+' +print(binascii.a2b_base64(b"MTIzNEFCQ0RhYmNk")) # Ignore invalid characters and pad sequences -print(binascii.a2b_base64(b'Zm9v\n')) -print(binascii.a2b_base64(b'Zm\x009v\n')) -print(binascii.a2b_base64(b'Zm9v==')) -print(binascii.a2b_base64(b'Zm9v===')) -print(binascii.a2b_base64(b'Zm9v===YmFy')) +print(binascii.a2b_base64(b"Zm9v\n")) +print(binascii.a2b_base64(b"Zm\x009v\n")) +print(binascii.a2b_base64(b"Zm9v==")) +print(binascii.a2b_base64(b"Zm9v===")) +print(binascii.a2b_base64(b"Zm9v===YmFy")) # Unicode strings can be decoded -print(binascii.a2b_base64(u'Zm9v===YmFy')) +print(binascii.a2b_base64(u"Zm9v===YmFy")) try: - print(binascii.a2b_base64(b'abc')) + print(binascii.a2b_base64(b"abc")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'abcde=')) + print(binascii.a2b_base64(b"abcde=")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'ab*d')) + print(binascii.a2b_base64(b"ab*d")) except ValueError: print("ValueError") try: - print(binascii.a2b_base64(b'ab=cdef=')) + print(binascii.a2b_base64(b"ab=cdef=")) except ValueError: print("ValueError") diff --git a/tests/extmod/ubinascii_b2a_base64.py b/tests/extmod/ubinascii_b2a_base64.py index 283c3936d3..8c63b545a3 100644 --- a/tests/extmod/ubinascii_b2a_base64.py +++ b/tests/extmod/ubinascii_b2a_base64.py @@ -7,20 +7,20 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.b2a_base64(b'')) -print(binascii.b2a_base64(b'f')) -print(binascii.b2a_base64(b'fo')) -print(binascii.b2a_base64(b'foo')) -print(binascii.b2a_base64(b'foob')) -print(binascii.b2a_base64(b'fooba')) -print(binascii.b2a_base64(b'foobar')) +print(binascii.b2a_base64(b"")) +print(binascii.b2a_base64(b"f")) +print(binascii.b2a_base64(b"fo")) +print(binascii.b2a_base64(b"foo")) +print(binascii.b2a_base64(b"foob")) +print(binascii.b2a_base64(b"fooba")) +print(binascii.b2a_base64(b"foobar")) -print(binascii.b2a_base64(b'\x00\x01\x02\x03\x04\x05\x06\x07')) -print(binascii.b2a_base64(b'\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f')) -print(binascii.b2a_base64(b'\x7f\x80\xff')) -print(binascii.b2a_base64(b'1234ABCDabcd')) -print(binascii.b2a_base64(b'\x00\x00>')) # convert into '+' +print(binascii.b2a_base64(b"\x00\x01\x02\x03\x04\x05\x06\x07")) +print(binascii.b2a_base64(b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")) +print(binascii.b2a_base64(b"\x7f\x80\xff")) +print(binascii.b2a_base64(b"1234ABCDabcd")) +print(binascii.b2a_base64(b"\x00\x00>")) # convert into '+' try: - print(binascii.b2a_base64('')) + print(binascii.b2a_base64("")) except TypeError: print("TypeError") diff --git a/tests/extmod/ubinascii_crc32.py b/tests/extmod/ubinascii_crc32.py index a826662f11..186bd699ae 100644 --- a/tests/extmod/ubinascii_crc32.py +++ b/tests/extmod/ubinascii_crc32.py @@ -13,16 +13,16 @@ except AttributeError: print("SKIP") raise SystemExit -print(hex(binascii.crc32(b'The quick brown fox jumps over the lazy dog'))) -print(hex(binascii.crc32(b'\x00' * 32))) -print(hex(binascii.crc32(b'\xff' * 32))) +print(hex(binascii.crc32(b"The quick brown fox jumps over the lazy dog"))) +print(hex(binascii.crc32(b"\x00" * 32))) +print(hex(binascii.crc32(b"\xff" * 32))) print(hex(binascii.crc32(bytes(range(32))))) -print(hex(binascii.crc32(b' over the lazy dog', binascii.crc32(b'The quick brown fox jumps')))) -print(hex(binascii.crc32(b'\x00' * 16, binascii.crc32(b'\x00' * 16)))) -print(hex(binascii.crc32(b'\xff' * 16, binascii.crc32(b'\xff' * 16)))) +print(hex(binascii.crc32(b" over the lazy dog", binascii.crc32(b"The quick brown fox jumps")))) +print(hex(binascii.crc32(b"\x00" * 16, binascii.crc32(b"\x00" * 16)))) +print(hex(binascii.crc32(b"\xff" * 16, binascii.crc32(b"\xff" * 16)))) print(hex(binascii.crc32(bytes(range(16, 32)), binascii.crc32(bytes(range(16)))))) try: - binascii.crc32('') + binascii.crc32("") except TypeError: print("TypeError") diff --git a/tests/extmod/ubinascii_hexlify.py b/tests/extmod/ubinascii_hexlify.py index dabc3c7e4c..3dcf0c4271 100644 --- a/tests/extmod/ubinascii_hexlify.py +++ b/tests/extmod/ubinascii_hexlify.py @@ -7,11 +7,11 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.hexlify(b'\x00\x01\x02\x03\x04\x05\x06\x07')) -print(binascii.hexlify(b'\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f')) -print(binascii.hexlify(b'\x7f\x80\xff')) -print(binascii.hexlify(b'1234ABCDabcd')) +print(binascii.hexlify(b"\x00\x01\x02\x03\x04\x05\x06\x07")) +print(binascii.hexlify(b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")) +print(binascii.hexlify(b"\x7f\x80\xff")) +print(binascii.hexlify(b"1234ABCDabcd")) try: - binascii.hexlify('') + binascii.hexlify("") except TypeError: print("TypeError") diff --git a/tests/extmod/ubinascii_micropython.py b/tests/extmod/ubinascii_micropython.py index 77084ec9ee..94e8daa557 100644 --- a/tests/extmod/ubinascii_micropython.py +++ b/tests/extmod/ubinascii_micropython.py @@ -8,8 +8,8 @@ except ImportError: raise SystemExit # two arguments supported in uPy but not CPython -a = binascii.hexlify(b'123', ':') +a = binascii.hexlify(b"123", ":") print(a) # zero length buffer -print(binascii.hexlify(b'', b':')) +print(binascii.hexlify(b"", b":")) diff --git a/tests/extmod/ubinascii_unhexlify.py b/tests/extmod/ubinascii_unhexlify.py index 41a1bd1b8f..f656bcd758 100644 --- a/tests/extmod/ubinascii_unhexlify.py +++ b/tests/extmod/ubinascii_unhexlify.py @@ -7,20 +7,20 @@ except ImportError: print("SKIP") raise SystemExit -print(binascii.unhexlify(b'0001020304050607')) -print(binascii.unhexlify(b'08090a0b0c0d0e0f')) -print(binascii.unhexlify(b'7f80ff')) -print(binascii.unhexlify(b'313233344142434461626364')) +print(binascii.unhexlify(b"0001020304050607")) +print(binascii.unhexlify(b"08090a0b0c0d0e0f")) +print(binascii.unhexlify(b"7f80ff")) +print(binascii.unhexlify(b"313233344142434461626364")) # Unicode strings can be decoded -print(binascii.unhexlify('313233344142434461626364')) +print(binascii.unhexlify("313233344142434461626364")) try: - a = binascii.unhexlify(b'0') # odd buffer length + a = binascii.unhexlify(b"0") # odd buffer length except ValueError: - print('ValueError') + print("ValueError") try: - a = binascii.unhexlify(b'gg') # digit not hex + a = binascii.unhexlify(b"gg") # digit not hex except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/uctypes_32bit_intbig.py b/tests/extmod/uctypes_32bit_intbig.py index 6b4d3d76cd..eed36e8774 100644 --- a/tests/extmod/uctypes_32bit_intbig.py +++ b/tests/extmod/uctypes_32bit_intbig.py @@ -10,16 +10,16 @@ buf = b"12345678abcd" struct = uctypes.struct( uctypes.addressof(buf), {"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4}, - uctypes.LITTLE_ENDIAN + uctypes.LITTLE_ENDIAN, ) -struct.f32 = 0x7fffffff +struct.f32 = 0x7FFFFFFF print(buf) struct.f32 = 0x80000000 print(buf) -struct.f32 = 0xff010203 +struct.f32 = 0xFF010203 print(buf) struct.f64 = 0x80000000 @@ -34,16 +34,16 @@ buf = b"12345678abcd" struct = uctypes.struct( uctypes.addressof(buf), {"f32": uctypes.UINT32 | 0, "f64": uctypes.UINT64 | 4}, - uctypes.BIG_ENDIAN + uctypes.BIG_ENDIAN, ) -struct.f32 = 0x7fffffff +struct.f32 = 0x7FFFFFFF print(buf) struct.f32 = 0x80000000 print(buf) -struct.f32 = 0xff010203 +struct.f32 = 0xFF010203 print(buf) struct.f64 = 0x80000000 diff --git a/tests/extmod/uctypes_array_assign_le.py b/tests/extmod/uctypes_array_assign_le.py index 37c52388d6..d822faf7e8 100644 --- a/tests/extmod/uctypes_array_assign_le.py +++ b/tests/extmod/uctypes_array_assign_le.py @@ -10,19 +10,17 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), # unaligned "arr6": (uctypes.ARRAY | 1, uctypes.UINT32 | 1), - "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 1, 1, {"l": uctypes.UINT32 | 0}) + "arr8": (uctypes.ARRAY | 1, 1, {"l": uctypes.UINT32 | 0}), } data = bytearray(5) -S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) +S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) # assign byte S.arr[0] = 0x11 diff --git a/tests/extmod/uctypes_array_assign_native_le.py b/tests/extmod/uctypes_array_assign_native_le.py index a538bf9add..d4c27fc4b3 100644 --- a/tests/extmod/uctypes_array_assign_native_le.py +++ b/tests/extmod/uctypes_array_assign_native_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -15,16 +16,14 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1), "arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1), "arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1), "arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1), - "arr12": (uctypes.ARRAY | 0, uctypes.UINT64| 1), + "arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1), "arr13": (uctypes.ARRAY | 1, 1, {"l": {}}), } diff --git a/tests/extmod/uctypes_array_assign_native_le_intbig.py b/tests/extmod/uctypes_array_assign_native_le_intbig.py index 84dfba0e29..f33c63b4ef 100644 --- a/tests/extmod/uctypes_array_assign_native_le_intbig.py +++ b/tests/extmod/uctypes_array_assign_native_le_intbig.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -15,16 +16,14 @@ desc = { # arr2 is array at offset 0, size 2, of structures defined recursively "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), - # aligned "arr5": (uctypes.ARRAY | 0, uctypes.UINT32 | 1), "arr7": (uctypes.ARRAY | 0, 1, {"l": uctypes.UINT32 | 0}), - "arr8": (uctypes.ARRAY | 0, uctypes.INT8 | 1), "arr9": (uctypes.ARRAY | 0, uctypes.INT16 | 1), "arr10": (uctypes.ARRAY | 0, uctypes.INT32 | 1), "arr11": (uctypes.ARRAY | 0, uctypes.INT64 | 1), - "arr12": (uctypes.ARRAY | 0, uctypes.UINT64| 1), + "arr12": (uctypes.ARRAY | 0, uctypes.UINT64 | 1), "arr13": (uctypes.ARRAY | 1, 1, {"l": {}}), } diff --git a/tests/extmod/uctypes_byteat.py b/tests/extmod/uctypes_byteat.py index 784209f803..0619d31dc9 100644 --- a/tests/extmod/uctypes_byteat.py +++ b/tests/extmod/uctypes_byteat.py @@ -4,7 +4,7 @@ except ImportError: print("SKIP") raise SystemExit -data = bytearray(b'01234567') +data = bytearray(b"01234567") print(uctypes.bytes_at(uctypes.addressof(data), 4)) print(uctypes.bytearray_at(uctypes.addressof(data), 4)) diff --git a/tests/extmod/uctypes_error.py b/tests/extmod/uctypes_error.py index 2500e29278..fb876de6d9 100644 --- a/tests/extmod/uctypes_error.py +++ b/tests/extmod/uctypes_error.py @@ -13,25 +13,25 @@ S = uctypes.struct(uctypes.addressof(data), {}) try: del S[0] except TypeError: - print('TypeError') + print("TypeError") # list is an invalid descriptor S = uctypes.struct(uctypes.addressof(data), []) try: S.x except TypeError: - print('TypeError') + print("TypeError") # can't access attribute with invalid descriptor -S = uctypes.struct(uctypes.addressof(data), {'x':[]}) +S = uctypes.struct(uctypes.addressof(data), {"x": []}) try: S.x except TypeError: - print('TypeError') + print("TypeError") # can't assign to aggregate -S = uctypes.struct(uctypes.addressof(data), {'x':(uctypes.ARRAY | 0, uctypes.INT8 | 2)}) +S = uctypes.struct(uctypes.addressof(data), {"x": (uctypes.ARRAY | 0, uctypes.INT8 | 2)}) try: S.x = 1 except TypeError: - print('TypeError') + print("TypeError") diff --git a/tests/extmod/uctypes_le.py b/tests/extmod/uctypes_le.py index 7df5ac0909..f69da30b61 100644 --- a/tests/extmod/uctypes_le.py +++ b/tests/extmod/uctypes_le.py @@ -6,20 +6,15 @@ except ImportError: desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "sub": (0, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, "bitf1": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 8 << uctypes.BF_LEN, - - "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "bf3": uctypes.BFUINT16 | 0 | 12 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } @@ -28,10 +23,10 @@ data = bytearray(b"01") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) -#print(S) +# print(S) print(hex(S.s0)) assert hex(S.s0) == "0x3130" -#print(S.sub.b0) +# print(S.sub.b0) print(S.sub.b0, S.sub.b1) assert S.sub.b0, S.sub.b1 == (0x30, 0x31) @@ -73,7 +68,7 @@ assert bytes(data) == b"2Q" desc2 = { "bf8": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN + "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN, } data2 = bytearray(b"0123") diff --git a/tests/extmod/uctypes_le_float.py b/tests/extmod/uctypes_le_float.py index 84ff2b84cf..89e9a9e0ab 100644 --- a/tests/extmod/uctypes_le_float.py +++ b/tests/extmod/uctypes_le_float.py @@ -7,7 +7,7 @@ except ImportError: desc = { "f32": uctypes.FLOAT32 | 0, "f64": uctypes.FLOAT64 | 0, - "uf64": uctypes.FLOAT64 | 2, # unaligned + "uf64": uctypes.FLOAT64 | 2, # unaligned } data = bytearray(10) @@ -15,10 +15,10 @@ data = bytearray(10) S = uctypes.struct(uctypes.addressof(data), desc, uctypes.LITTLE_ENDIAN) S.f32 = 12.34 -print('%.4f' % S.f32) +print("%.4f" % S.f32) S.f64 = 12.34 -print('%.4f' % S.f64) +print("%.4f" % S.f64) S.uf64 = 12.34 -print('%.4f' % S.uf64) +print("%.4f" % S.uf64) diff --git a/tests/extmod/uctypes_native_float.py b/tests/extmod/uctypes_native_float.py index acef47036d..1fdc658499 100644 --- a/tests/extmod/uctypes_native_float.py +++ b/tests/extmod/uctypes_native_float.py @@ -4,17 +4,14 @@ except ImportError: print("SKIP") raise SystemExit -desc = { - "f32": uctypes.FLOAT32 | 0, - "f64": uctypes.FLOAT64 | 0, -} +desc = {"f32": uctypes.FLOAT32 | 0, "f64": uctypes.FLOAT64 | 0} data = bytearray(8) S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) S.f32 = 12.34 -print('%.4f' % S.f32) +print("%.4f" % S.f32) S.f64 = 12.34 -print('%.4f' % S.f64) +print("%.4f" % S.f64) diff --git a/tests/extmod/uctypes_native_le.py b/tests/extmod/uctypes_native_le.py index 8bba03b38c..7958e5c22a 100644 --- a/tests/extmod/uctypes_native_le.py +++ b/tests/extmod/uctypes_native_le.py @@ -2,6 +2,7 @@ # Codepaths for packed vs native structures are different. This test only works # on little-endian machine (no matter if 32 or 64 bit). import sys + try: import uctypes except ImportError: @@ -15,20 +16,15 @@ if sys.byteorder != "little": desc = { "s0": uctypes.UINT16 | 0, - "sub": (0, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "sub": (0, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 2), "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "bitf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 8 << uctypes.BF_LEN, "bitf1": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 8 << uctypes.BF_LEN, - - "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf0": uctypes.BFUINT16 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf1": uctypes.BFUINT16 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "bf2": uctypes.BFUINT16 | 0 | 8 << uctypes.BF_POS | 4 << uctypes.BF_LEN, "bf3": uctypes.BFUINT16 | 0 | 12 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "ptr": (uctypes.PTR | 0, uctypes.UINT8), "ptr2": (uctypes.PTR | 0, {"b": uctypes.UINT8 | 0}), } @@ -37,10 +33,10 @@ data = bytearray(b"01") S = uctypes.struct(uctypes.addressof(data), desc, uctypes.NATIVE) -#print(S) +# print(S) print(hex(S.s0)) assert hex(S.s0) == "0x3130" -#print(S.sub.b0) +# print(S.sub.b0) print(S.sub.b0, S.sub.b1) assert S.sub.b0, S.sub.b1 == (0x30, 0x31) @@ -81,7 +77,7 @@ assert bytes(data) == b"2Q" desc2 = { "bf8": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN + "bf32": uctypes.BFUINT32 | 0 | 20 << uctypes.BF_POS | 4 << uctypes.BF_LEN, } data2 = bytearray(b"0123") diff --git a/tests/extmod/uctypes_print.py b/tests/extmod/uctypes_print.py index c310238e54..6e0018abc7 100644 --- a/tests/extmod/uctypes_print.py +++ b/tests/extmod/uctypes_print.py @@ -16,10 +16,10 @@ desc2 = [(uctypes.ARRAY | 0, uctypes.UINT8 | 1)] S2 = uctypes.struct(0, desc2) print(S2) -desc3 = ((uctypes.ARRAY | 0, uctypes.UINT8 | 1)) +desc3 = (uctypes.ARRAY | 0, uctypes.UINT8 | 1) S3 = uctypes.struct(0, desc3) print(S3) -desc4 = ((uctypes.PTR | 0, uctypes.UINT8 | 1)) +desc4 = (uctypes.PTR | 0, uctypes.UINT8 | 1) S4 = uctypes.struct(0, desc4) print(S4) diff --git a/tests/extmod/uctypes_ptr_le.py b/tests/extmod/uctypes_ptr_le.py index 056e456506..a69467e62c 100644 --- a/tests/extmod/uctypes_ptr_le.py +++ b/tests/extmod/uctypes_ptr_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -29,6 +30,6 @@ assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) -print (S.ptr2[0].b, S.ptr2[1].b) +print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49) diff --git a/tests/extmod/uctypes_ptr_native_le.py b/tests/extmod/uctypes_ptr_native_le.py index 24508b1cb4..8ca4d2c55c 100644 --- a/tests/extmod/uctypes_ptr_native_le.py +++ b/tests/extmod/uctypes_ptr_native_le.py @@ -1,4 +1,5 @@ import sys + try: import uctypes except ImportError: @@ -30,6 +31,6 @@ assert S.ptr[1] == ord("1") print(hex(S.ptr16[0])) assert hex(S.ptr16[0]) == "0x3130" print(S.ptr2[0].b, S.ptr2[1].b) -print (S.ptr2[0].b, S.ptr2[1].b) +print(S.ptr2[0].b, S.ptr2[1].b) print(hex(S.ptr16[0])) assert (S.ptr2[0].b, S.ptr2[1].b) == (48, 49) diff --git a/tests/extmod/uctypes_sizeof.py b/tests/extmod/uctypes_sizeof.py index e42e06c924..6e52232e39 100644 --- a/tests/extmod/uctypes_sizeof.py +++ b/tests/extmod/uctypes_sizeof.py @@ -11,10 +11,13 @@ desc = { "arr2": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0}), "arr3": (uctypes.ARRAY | 2, uctypes.UINT16 | 2), "arr4": (uctypes.ARRAY | 0, 2, {"b": uctypes.UINT8 | 0, "w": uctypes.UINT16 | 1}), - "sub": (0, { - 'b1': uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - 'b2': uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, - }), + "sub": ( + 0, + { + "b1": uctypes.BFUINT8 | 0 | 4 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + "b2": uctypes.BFUINT8 | 0 | 0 << uctypes.BF_POS | 4 << uctypes.BF_LEN, + }, + ), } data = bytearray(b"01234567") diff --git a/tests/extmod/uctypes_sizeof_float.py b/tests/extmod/uctypes_sizeof_float.py index 1ba8871bdc..351632d76b 100644 --- a/tests/extmod/uctypes_sizeof_float.py +++ b/tests/extmod/uctypes_sizeof_float.py @@ -4,5 +4,5 @@ except ImportError: print("SKIP") raise SystemExit -print(uctypes.sizeof({'f':uctypes.FLOAT32})) -print(uctypes.sizeof({'f':uctypes.FLOAT64})) +print(uctypes.sizeof({"f": uctypes.FLOAT32})) +print(uctypes.sizeof({"f": uctypes.FLOAT64})) diff --git a/tests/extmod/uctypes_sizeof_native.py b/tests/extmod/uctypes_sizeof_native.py index 32c740e773..9aa5d84ec6 100644 --- a/tests/extmod/uctypes_sizeof_native.py +++ b/tests/extmod/uctypes_sizeof_native.py @@ -10,17 +10,10 @@ assert uctypes.sizeof(S1) == 0 S2 = {"a": uctypes.UINT8 | 0} assert uctypes.sizeof(S2) == 1 -S3 = { - "a": uctypes.UINT8 | 0, - "b": uctypes.UINT8 | 1, -} +S3 = {"a": uctypes.UINT8 | 0, "b": uctypes.UINT8 | 1} assert uctypes.sizeof(S3) == 2 -S4 = { - "a": uctypes.UINT8 | 0, - "b": uctypes.UINT32 | 4, - "c": uctypes.UINT8 | 8, -} +S4 = {"a": uctypes.UINT8 | 0, "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8} assert uctypes.sizeof(S4) == 12 S5 = { @@ -28,10 +21,7 @@ S5 = { "b": uctypes.UINT32 | 4, "c": uctypes.UINT8 | 8, "d": uctypes.UINT32 | 0, - "sub": (4, { - "b0": uctypes.UINT8 | 0, - "b1": uctypes.UINT8 | 1, - }), + "sub": (4, {"b0": uctypes.UINT8 | 0, "b1": uctypes.UINT8 | 1}), } assert uctypes.sizeof(S5) == 12 @@ -40,18 +30,12 @@ s5 = uctypes.struct(0, S5) assert uctypes.sizeof(s5) == 12 assert uctypes.sizeof(s5.sub) == 2 -S6 = { - "ptr": (uctypes.PTR | 0, uctypes.UINT8), -} +S6 = {"ptr": (uctypes.PTR | 0, uctypes.UINT8)} # As if there're no other arch bitnesses assert uctypes.sizeof(S6) in (4, 8) -S7 = { - "arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5), -} +S7 = {"arr": (uctypes.ARRAY | 0, uctypes.UINT8 | 5)} assert uctypes.sizeof(S7) == 5 -S8 = { - "arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4}), -} +S8 = {"arr": (uctypes.ARRAY | 0, 3, {"a": uctypes.UINT32 | 0, "b": uctypes.UINT8 | 4})} assert uctypes.sizeof(S8) == 24 diff --git a/tests/extmod/uhashlib_sha1.py b/tests/extmod/uhashlib_sha1.py index 9d6427b33f..a0ad8473a1 100644 --- a/tests/extmod/uhashlib_sha1.py +++ b/tests/extmod/uhashlib_sha1.py @@ -16,13 +16,13 @@ except AttributeError: print("SKIP") raise SystemExit -sha1 = hashlib.sha1(b'hello') -sha1.update(b'world') +sha1 = hashlib.sha1(b"hello") +sha1.update(b"world") print(sha1.digest()) -sha1 = hashlib.sha1(b'hello') +sha1 = hashlib.sha1(b"hello") try: - sha1.update(u'world') + sha1.update(u"world") except TypeError as e: print("TypeError") print(sha1.digest()) diff --git a/tests/extmod/uhashlib_sha256.py b/tests/extmod/uhashlib_sha256.py index a793ea4930..ad5aa124cb 100644 --- a/tests/extmod/uhashlib_sha256.py +++ b/tests/extmod/uhashlib_sha256.py @@ -26,20 +26,20 @@ print(hashlib.sha256(b"\xff" * 64).digest()) # 56 bytes is a boundary case in the algorithm print(hashlib.sha256(b"\xff" * 56).digest()) -sha256 = hashlib.sha256(b'hello') +sha256 = hashlib.sha256(b"hello") try: - sha256.update(u'world') + sha256.update(u"world") except TypeError as e: print("TypeError") print(sha256.digest()) # TODO: running .digest() several times in row is not supported() -#h = hashlib.sha256(b'123') -#print(h.digest()) -#print(h.digest()) +# h = hashlib.sha256(b'123') +# print(h.digest()) +# print(h.digest()) # TODO: partial digests are not supported -#h = hashlib.sha256(b'123') -#print(h.digest()) -#h.update(b'456') -#print(h.digest()) +# h = hashlib.sha256(b'123') +# print(h.digest()) +# h.update(b'456') +# print(h.digest()) diff --git a/tests/extmod/uheapq1.py b/tests/extmod/uheapq1.py index 7c1fe4e1ec..a470bb6f71 100644 --- a/tests/extmod/uheapq1.py +++ b/tests/extmod/uheapq1.py @@ -17,11 +17,13 @@ try: except TypeError: print("TypeError") + def pop_and_print(h): l = [] while h: l.append(str(heapq.heappop(h))) - print(' '.join(l)) + print(" ".join(l)) + h = [] heapq.heappush(h, 3) diff --git a/tests/extmod/ujson_dump.py b/tests/extmod/ujson_dump.py index b1cb4a9cbc..feda8a47dd 100644 --- a/tests/extmod/ujson_dump.py +++ b/tests/extmod/ujson_dump.py @@ -20,11 +20,11 @@ print(s.getvalue()) # dump to a small-int not allowed try: json.dump(123, 1) -except (AttributeError, OSError): # CPython and uPy have different errors - print('Exception') +except (AttributeError, OSError): # CPython and uPy have different errors + print("Exception") # dump to an object not allowed try: json.dump(123, {}) -except (AttributeError, OSError): # CPython and uPy have different errors - print('Exception') +except (AttributeError, OSError): # CPython and uPy have different errors + print("Exception") diff --git a/tests/extmod/ujson_dump_iobase.py b/tests/extmod/ujson_dump_iobase.py index 6280fb11b6..c51994ef5d 100644 --- a/tests/extmod/ujson_dump_iobase.py +++ b/tests/extmod/ujson_dump_iobase.py @@ -7,22 +7,23 @@ except ImportError: try: import io, json except ImportError: - print('SKIP') + print("SKIP") raise SystemExit -if not hasattr(io, 'IOBase'): - print('SKIP') +if not hasattr(io, "IOBase"): + print("SKIP") raise SystemExit # a user stream that only has the write method class S(io.IOBase): def __init__(self): - self.buf = '' + self.buf = "" + def write(self, buf): if type(buf) == bytearray: # uPy passes a bytearray, CPython passes a str - buf = str(buf, 'ascii') + buf = str(buf, "ascii") self.buf += buf diff --git a/tests/extmod/ujson_dumps.py b/tests/extmod/ujson_dumps.py index d732718019..bfdae62643 100644 --- a/tests/extmod/ujson_dumps.py +++ b/tests/extmod/ujson_dumps.py @@ -11,8 +11,8 @@ print(json.dumps(False)) print(json.dumps(True)) print(json.dumps(None)) print(json.dumps(1)) -print(json.dumps('abc')) -print(json.dumps('\x00\x01\x7e')) +print(json.dumps("abc")) +print(json.dumps("\x00\x01\x7e")) print(json.dumps([])) print(json.dumps([1])) print(json.dumps([1, 2])) @@ -22,7 +22,7 @@ print(json.dumps((1,))) print(json.dumps((1, 2))) print(json.dumps((1, (2, 3)))) print(json.dumps({})) -print(json.dumps({"a":1})) -print(json.dumps({"a":(2,[3,None])})) +print(json.dumps({"a": 1})) +print(json.dumps({"a": (2, [3, None])})) print(json.dumps('"quoted"')) -print(json.dumps('space\n\r\tspace')) +print(json.dumps("space\n\r\tspace")) diff --git a/tests/extmod/ujson_dumps_extra.py b/tests/extmod/ujson_dumps_extra.py index 21a388c32d..f2aa7f249f 100644 --- a/tests/extmod/ujson_dumps_extra.py +++ b/tests/extmod/ujson_dumps_extra.py @@ -6,4 +6,4 @@ except ImportError: print("SKIP") raise SystemExit -print(ujson.dumps(b'1234')) +print(ujson.dumps(b"1234")) diff --git a/tests/extmod/ujson_load.py b/tests/extmod/ujson_load.py index 9725ab2ddc..7cec9246b8 100644 --- a/tests/extmod/ujson_load.py +++ b/tests/extmod/ujson_load.py @@ -9,7 +9,7 @@ except: print("SKIP") raise SystemExit -print(json.load(StringIO('null'))) +print(json.load(StringIO("null"))) print(json.load(StringIO('"abc\\u0064e"'))) -print(json.load(StringIO('[false, true, 1, -2]'))) +print(json.load(StringIO("[false, true, 1, -2]"))) print(json.load(StringIO('{"a":true}'))) diff --git a/tests/extmod/ujson_load_readinto.py b/tests/extmod/ujson_load_readinto.py index a277f40efc..001aa4fb2c 100644 --- a/tests/extmod/ujson_load_readinto.py +++ b/tests/extmod/ujson_load_readinto.py @@ -2,6 +2,7 @@ import ujson as json # Test that json can load from any object with readinto + class Buffer: def __init__(self, data): self._data = data @@ -12,11 +13,12 @@ class Buffer: remaining = len(self._data) - self._i end = min(end, len(self._data)) l = min(len(buf), remaining) - buf[:l] = self._data[self._i:end] + buf[:l] = self._data[self._i : end] self._i += l return l -print(json.load(Buffer(b'null'))) + +print(json.load(Buffer(b"null"))) print(json.load(Buffer(b'"abc\\u0064e"'))) -print(json.load(Buffer(b'[false, true, 1, -2]'))) +print(json.load(Buffer(b"[false, true, 1, -2]"))) print(json.load(Buffer(b'{"a":true}'))) diff --git a/tests/extmod/ujson_loads.py b/tests/extmod/ujson_loads.py index adba3c068d..2de9cdcbc1 100644 --- a/tests/extmod/ujson_loads.py +++ b/tests/extmod/ujson_loads.py @@ -7,23 +7,25 @@ except ImportError: print("SKIP") raise SystemExit + def my_print(o): if isinstance(o, dict): - print('sorted dict', sorted(o.items())) + print("sorted dict", sorted(o.items())) else: print(o) -my_print(json.loads('null')) -my_print(json.loads('false')) -my_print(json.loads('true')) -my_print(json.loads('1')) -my_print(json.loads('-2')) + +my_print(json.loads("null")) +my_print(json.loads("false")) +my_print(json.loads("true")) +my_print(json.loads("1")) +my_print(json.loads("-2")) my_print(json.loads('"abc\\u0064e"')) -my_print(json.loads('[]')) -my_print(json.loads('[null]')) -my_print(json.loads('[null,false,true]')) -my_print(json.loads(' [ null , false , true ] ')) -my_print(json.loads('{}')) +my_print(json.loads("[]")) +my_print(json.loads("[null]")) +my_print(json.loads("[null,false,true]")) +my_print(json.loads(" [ null , false , true ] ")) +my_print(json.loads("{}")) my_print(json.loads('{"a":true}')) my_print(json.loads('{"a":null, "b":false, "c":true}')) my_print(json.loads('{"a":[], "b":[1], "c":{"3":4}}')) @@ -39,36 +41,36 @@ my_print(json.loads('{\n\t"a":[]\r\n, "b":[1], "c":{"3":4} \n\r\t\r\r\r\n}') # loading nothing should raise exception try: - json.loads('') + json.loads("") except ValueError: - print('ValueError') + print("ValueError") # string which is not closed try: my_print(json.loads('"abc')) except ValueError: - print('ValueError') + print("ValueError") # unaccompanied closing brace try: - my_print(json.loads(']')) + my_print(json.loads("]")) except ValueError: - print('ValueError') + print("ValueError") # unspecified object type try: - my_print(json.loads('a')) + my_print(json.loads("a")) except ValueError: - print('ValueError') + print("ValueError") # bad property name try: my_print(json.loads('{{}:"abc"}')) except ValueError: - print('ValueError') + print("ValueError") # unexpected characters after white space try: - my_print(json.loads('[null] a')) + my_print(json.loads("[null] a")) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/ujson_loads_float.py b/tests/extmod/ujson_loads_float.py index f1b8cc364c..e368ca42e7 100644 --- a/tests/extmod/ujson_loads_float.py +++ b/tests/extmod/ujson_loads_float.py @@ -7,11 +7,13 @@ except ImportError: print("SKIP") raise SystemExit -def my_print(o): - print('%.3f' % o) -my_print(json.loads('1.2')) -my_print(json.loads('1e2')) -my_print(json.loads('-2.3')) -my_print(json.loads('-2e3')) -my_print(json.loads('-2e-3')) +def my_print(o): + print("%.3f" % o) + + +my_print(json.loads("1.2")) +my_print(json.loads("1e2")) +my_print(json.loads("-2.3")) +my_print(json.loads("-2e3")) +my_print(json.loads("-2e-3")) diff --git a/tests/extmod/umsgpack_pack.py b/tests/extmod/umsgpack_pack.py index d9f0005e1b..7ea5ae8d6a 100644 --- a/tests/extmod/umsgpack_pack.py +++ b/tests/extmod/umsgpack_pack.py @@ -20,11 +20,11 @@ print(b.getvalue()) # pack to a small-int not allowed try: msgpack.pack(123, 1) -except (AttributeError, OSError): # CPython and uPy have different errors - print('Exception') +except (AttributeError, OSError): # CPython and uPy have different errors + print("Exception") # pack to an object not allowed try: msgpack.pack(123, {}) -except (AttributeError, OSError): # CPython and uPy have different errors - print('Exception') +except (AttributeError, OSError): # CPython and uPy have different errors + print("Exception") diff --git a/tests/extmod/urandom_basic.py b/tests/extmod/urandom_basic.py index 57e6b26cba..180197398f 100644 --- a/tests/extmod/urandom_basic.py +++ b/tests/extmod/urandom_basic.py @@ -26,4 +26,4 @@ print(random.getrandbits(16) == r) try: random.getrandbits(0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/extmod/urandom_extra.py b/tests/extmod/urandom_extra.py index f5a34e1687..636a225394 100644 --- a/tests/extmod/urandom_extra.py +++ b/tests/extmod/urandom_extra.py @@ -10,10 +10,10 @@ except ImportError: try: random.randint except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit -print('randrange') +print("randrange") for i in range(50): assert 0 <= random.randrange(4) < 4 assert 2 <= random.randrange(2, 6) < 6 @@ -25,27 +25,27 @@ for i in range(50): try: random.randrange(0) except ValueError: - print('ValueError') + print("ValueError") # empty range try: random.randrange(2, 1) except ValueError: - print('ValueError') + print("ValueError") # zero step try: random.randrange(2, 1, 0) except ValueError: - print('ValueError') + print("ValueError") # empty range try: random.randrange(2, 1, 1) except ValueError: - print('ValueError') + print("ValueError") -print('randint') +print("randint") for i in range(50): assert 0 <= random.randint(0, 4) <= 4 assert 2 <= random.randint(2, 6) <= 6 @@ -55,9 +55,9 @@ for i in range(50): try: random.randint(2, 1) except ValueError: - print('ValueError') + print("ValueError") -print('choice') +print("choice") lst = [1, 2, 5, 6] for i in range(50): assert random.choice(lst) in lst @@ -66,13 +66,13 @@ for i in range(50): try: random.choice([]) except IndexError: - print('IndexError') + print("IndexError") -print('random') +print("random") for i in range(50): assert 0 <= random.random() < 1 -print('uniform') +print("uniform") for i in range(50): assert 0 <= random.uniform(0, 4) <= 4 assert 2 <= random.uniform(2, 6) <= 6 diff --git a/tests/extmod/ure1.py b/tests/extmod/ure1.py index 710720c8b6..d1cb9a05d9 100644 --- a/tests/extmod/ure1.py +++ b/tests/extmod/ure1.py @@ -83,11 +83,16 @@ print(m.group(0)) m = re.search("w.r", "hello world") print(m.group(0)) -m = re.match('a+?', 'ab'); print(m.group(0)) -m = re.match('a*?', 'ab'); print(m.group(0)) -m = re.match('^ab$', 'ab'); print(m.group(0)) -m = re.match('a|b', 'b'); print(m.group(0)) -m = re.match('a|b|c', 'c'); print(m.group(0)) +m = re.match("a+?", "ab") +print(m.group(0)) +m = re.match("a*?", "ab") +print(m.group(0)) +m = re.match("^ab$", "ab") +print(m.group(0)) +m = re.match("a|b", "b") +print(m.group(0)) +m = re.match("a|b|c", "c") +print(m.group(0)) # Case where anchors fail to match r = re.compile("^b|b$") @@ -100,4 +105,5 @@ except: print("Caught invalid regex") # bytes objects -m = re.match(rb'a+?', b'ab'); print(m.group(0)) +m = re.match(rb"a+?", b"ab") +print(m.group(0)) diff --git a/tests/extmod/ure_debug.py b/tests/extmod/ure_debug.py index cfb264bb6d..4cef4c98ae 100644 --- a/tests/extmod/ure_debug.py +++ b/tests/extmod/ure_debug.py @@ -5,4 +5,4 @@ except ImportError: print("SKIP") raise SystemExit -ure.compile('^a|b[0-9]\w$', ure.DEBUG) +ure.compile("^a|b[0-9]\w$", ure.DEBUG) diff --git a/tests/extmod/ure_error.py b/tests/extmod/ure_error.py index f52f735c7f..a99a47f97e 100644 --- a/tests/extmod/ure_error.py +++ b/tests/extmod/ure_error.py @@ -9,17 +9,19 @@ except ImportError: print("SKIP") raise SystemExit + def test_re(r): try: re.compile(r) print("OK") - except: # uPy and CPy use different errors, so just ignore the type + except: # uPy and CPy use different errors, so just ignore the type print("Error") -test_re(r'?') -test_re(r'*') -test_re(r'+') -test_re(r')') -test_re(r'[') -test_re(r'([') -test_re(r'([)') + +test_re(r"?") +test_re(r"*") +test_re(r"+") +test_re(r")") +test_re(r"[") +test_re(r"([") +test_re(r"([)") diff --git a/tests/extmod/ure_group.py b/tests/extmod/ure_group.py index 4e39468c5b..41425dd623 100644 --- a/tests/extmod/ure_group.py +++ b/tests/extmod/ure_group.py @@ -9,8 +9,9 @@ except ImportError: print("SKIP") raise SystemExit + def print_groups(match): - print('----') + print("----") try: i = 0 while True: @@ -19,14 +20,15 @@ def print_groups(match): except IndexError: pass -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') + +m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print_groups(m) -m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567') +m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print_groups(m) # optional group that matches -print_groups(re.match(r'(a)?b(c)', 'abc')) +print_groups(re.match(r"(a)?b(c)", "abc")) # optional group that doesn't match -print_groups(re.match(r'(a)?b(c)', 'bc')) +print_groups(re.match(r"(a)?b(c)", "bc")) diff --git a/tests/extmod/ure_groups.py b/tests/extmod/ure_groups.py index 4fac896d7f..7da072a920 100644 --- a/tests/extmod/ure_groups.py +++ b/tests/extmod/ure_groups.py @@ -13,21 +13,21 @@ try: m = re.match(".", "a") m.groups except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') +m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print(m.groups()) -m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567') +m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print(m.groups()) # optional group that matches -print(re.match(r'(a)?b(c)', 'abc').groups()) +print(re.match(r"(a)?b(c)", "abc").groups()) # optional group that doesn't match -print(re.match(r'(a)?b(c)', 'bc').groups()) +print(re.match(r"(a)?b(c)", "bc").groups()) # only a single match -print(re.match(r'abc', 'abc').groups()) +print(re.match(r"abc", "abc").groups()) diff --git a/tests/extmod/ure_namedclass.py b/tests/extmod/ure_namedclass.py index 215d09613f..00d58ad98a 100644 --- a/tests/extmod/ure_namedclass.py +++ b/tests/extmod/ure_namedclass.py @@ -9,8 +9,9 @@ except ImportError: print("SKIP") raise SystemExit + def print_groups(match): - print('----') + print("----") try: i = 0 while True: @@ -19,14 +20,15 @@ def print_groups(match): except IndexError: pass -m = re.match(r'\w+','1234hello567 abc') + +m = re.match(r"\w+", "1234hello567 abc") print_groups(m) -m = re.match(r'(\w+)\s+(\w+)','ABC \t1234hello567 abc') +m = re.match(r"(\w+)\s+(\w+)", "ABC \t1234hello567 abc") print_groups(m) -m = re.match(r'(\S+)\s+(\D+)','ABC \thello abc567 abc') +m = re.match(r"(\S+)\s+(\D+)", "ABC \thello abc567 abc") print_groups(m) -m = re.match(r'(([0-9]*)([a-z]*)\d*)','1234hello567') +m = re.match(r"(([0-9]*)([a-z]*)\d*)", "1234hello567") print_groups(m) diff --git a/tests/extmod/ure_span.py b/tests/extmod/ure_span.py index 50f44399ce..03a3fef9f3 100644 --- a/tests/extmod/ure_span.py +++ b/tests/extmod/ure_span.py @@ -13,12 +13,12 @@ try: m = re.match(".", "a") m.span except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit def print_spans(match): - print('----') + print("----") try: i = 0 while True: @@ -27,14 +27,15 @@ def print_spans(match): except IndexError: pass -m = re.match(r'(([0-9]*)([a-z]*)[0-9]*)','1234hello567') + +m = re.match(r"(([0-9]*)([a-z]*)[0-9]*)", "1234hello567") print_spans(m) -m = re.match(r'([0-9]*)(([a-z]*)([0-9]*))','1234hello567') +m = re.match(r"([0-9]*)(([a-z]*)([0-9]*))", "1234hello567") print_spans(m) # optional span that matches -print_spans(re.match(r'(a)?b(c)', 'abc')) +print_spans(re.match(r"(a)?b(c)", "abc")) # optional span that doesn't match -print_spans(re.match(r'(a)?b(c)', 'bc')) +print_spans(re.match(r"(a)?b(c)", "bc")) diff --git a/tests/extmod/ure_split_notimpl.py b/tests/extmod/ure_split_notimpl.py index da6e9652d0..51bad791ef 100644 --- a/tests/extmod/ure_split_notimpl.py +++ b/tests/extmod/ure_split_notimpl.py @@ -4,8 +4,8 @@ except ImportError: print("SKIP") raise SystemExit -r = re.compile('( )') +r = re.compile("( )") try: s = r.split("a b c foobar") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") diff --git a/tests/extmod/ure_sub.py b/tests/extmod/ure_sub.py index f5a19af8db..6bb332077d 100644 --- a/tests/extmod/ure_sub.py +++ b/tests/extmod/ure_sub.py @@ -4,58 +4,59 @@ except ImportError: try: import re except ImportError: - print('SKIP') + print("SKIP") raise SystemExit try: re.sub except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit def multiply(m): return str(int(m.group(0)) * 2) + print(re.sub("\d+", multiply, "10 20 30 40 50")) print(re.sub("\d+", lambda m: str(int(m.group(0)) // 2), "10 20 30 40 50")) + def A(): return "A" -print(re.sub('a', A(), 'aBCBABCDabcda.')) + + +print(re.sub("a", A(), "aBCBABCDabcda.")) print( re.sub( - r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):', - 'static PyObject*\npy_\\1(void){\n return;\n}\n', - '\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():' + r"def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):", + "static PyObject*\npy_\\1(void){\n return;\n}\n", + "\n\ndef myfunc():\n\ndef myfunc1():\n\ndef myfunc2():", ) ) print( - re.compile( - '(calzino) (blu|bianco|verde) e (scarpa) (blu|bianco|verde)' - ).sub( - r'\g<1> colore \2 con \g<3> colore \4? ...', - 'calzino blu e scarpa verde' + re.compile("(calzino) (blu|bianco|verde) e (scarpa) (blu|bianco|verde)").sub( + r"\g<1> colore \2 con \g<3> colore \4? ...", "calzino blu e scarpa verde" ) ) # no matches at all -print(re.sub('a', 'b', 'c')) +print(re.sub("a", "b", "c")) # with maximum substitution count specified -print(re.sub('a', 'b', '1a2a3a', 2)) +print(re.sub("a", "b", "1a2a3a", 2)) # invalid group try: - re.sub('(a)', 'b\\2', 'a') + re.sub("(a)", "b\\2", "a") except: - print('invalid group') + print("invalid group") # invalid group with very large number (to test overflow in uPy) try: - re.sub('(a)', 'b\\199999999999999999999999999999999999999', 'a') + re.sub("(a)", "b\\199999999999999999999999999999999999999", "a") except: - print('invalid group') + print("invalid group") diff --git a/tests/extmod/ure_sub_unmatched.py b/tests/extmod/ure_sub_unmatched.py index 4795b3196f..d6312bfc2c 100644 --- a/tests/extmod/ure_sub_unmatched.py +++ b/tests/extmod/ure_sub_unmatched.py @@ -6,14 +6,14 @@ except ImportError: try: import re except ImportError: - print('SKIP') + print("SKIP") raise SystemExit try: re.sub except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit # first group matches, second optional group doesn't so is replaced with a blank -print(re.sub(r'(a)(b)?', r'\2-\1', '1a2')) +print(re.sub(r"(a)(b)?", r"\2-\1", "1a2")) diff --git a/tests/extmod/ussl_basic.py b/tests/extmod/ussl_basic.py index e8710ed51a..c8bdc81a48 100644 --- a/tests/extmod/ussl_basic.py +++ b/tests/extmod/ussl_basic.py @@ -11,7 +11,7 @@ except ImportError: try: ss = ssl.wrap_socket(io.BytesIO()) except OSError as er: - print('wrap_socket:', repr(er)) + print("wrap_socket:", repr(er)) # create in server mode (can use this object for further tests) socket = io.BytesIO() @@ -24,22 +24,22 @@ print(repr(ss)[:12]) try: ss.setblocking(False) except NotImplementedError: - print('setblocking: NotImplementedError') + print("setblocking: NotImplementedError") ss.setblocking(True) # write -print(ss.write(b'aaaa')) +print(ss.write(b"aaaa")) # read (underlying socket has no data) print(ss.read(8)) # read (underlying socket has data, but it's bad data) -socket.write(b'aaaaaaaaaaaaaaaa') +socket.write(b"aaaaaaaaaaaaaaaa") socket.seek(0) try: ss.read(8) except OSError as er: - print('read:', repr(er)) + print("read:", repr(er)) # close ss.close() @@ -50,10 +50,10 @@ ss.close() try: ss.read(10) except OSError as er: - print('read:', repr(er)) + print("read:", repr(er)) # write on closed socket try: - ss.write(b'aaaa') + ss.write(b"aaaa") except OSError as er: - print('write:', repr(er)) + print("write:", repr(er)) diff --git a/tests/extmod/utimeq1.py b/tests/extmod/utimeq1.py index dc7f3b6600..234d7a31dd 100644 --- a/tests/extmod/utimeq1.py +++ b/tests/extmod/utimeq1.py @@ -13,12 +13,17 @@ MAX = ticks_add(0, -1) MODULO_HALF = MAX // 2 + 1 if DEBUG: + def dprint(*v): print(*v) + + else: + def dprint(*v): pass + # Try not to crash on invalid data h = utimeq(10) try: @@ -69,22 +74,25 @@ try: except IndexError: pass + def pop_all(h): l = [] while h: item = [0, 0, 0] h.pop(item) - #print("!", item) + # print("!", item) l.append(tuple(item)) dprint(l) return l + def add(h, v): h.push(v, 0, 0) dprint("-----") - #h.dump() + # h.dump() dprint("-----") + h = utimeq(10) add(h, 0) add(h, MAX) @@ -98,6 +106,7 @@ for i in range(len(l) - 1): diff = ticks_diff(l[i + 1][0], l[i][0]) assert diff > 0 + def edge_case(edge, offset): h = utimeq(10) add(h, ticks_add(0, offset)) @@ -108,6 +117,7 @@ def edge_case(edge, offset): dprint(diff, diff > 0) return diff + dprint("===") diff = edge_case(MODULO_HALF - 1, 0) assert diff == MODULO_HALF - 1 diff --git a/tests/extmod/uzlib_decompio.py b/tests/extmod/uzlib_decompio.py index 112a825976..6a0aae8bcd 100644 --- a/tests/extmod/uzlib_decompio.py +++ b/tests/extmod/uzlib_decompio.py @@ -7,7 +7,7 @@ except ImportError: # Raw DEFLATE bitstream -buf = io.BytesIO(b'\xcbH\xcd\xc9\xc9\x07\x00') +buf = io.BytesIO(b"\xcbH\xcd\xc9\xc9\x07\x00") inp = zlib.DecompIO(buf, -8) print(buf.seek(0, 1)) print(inp.read(1)) @@ -21,12 +21,12 @@ print(buf.seek(0, 1)) # zlib bitstream -inp = zlib.DecompIO(io.BytesIO(b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc1')) +inp = zlib.DecompIO(io.BytesIO(b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc1")) print(inp.read(10)) print(inp.read()) # zlib bitstream, wrong checksum -inp = zlib.DecompIO(io.BytesIO(b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc0')) +inp = zlib.DecompIO(io.BytesIO(b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc0")) try: print(inp.read()) except OSError as e: diff --git a/tests/extmod/uzlib_decompio_gz.py b/tests/extmod/uzlib_decompio_gz.py index 02087f7639..1bc8ba885b 100644 --- a/tests/extmod/uzlib_decompio_gz.py +++ b/tests/extmod/uzlib_decompio_gz.py @@ -7,7 +7,9 @@ except ImportError: # gzip bitstream -buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" +) inp = zlib.DecompIO(buf, 16 + 8) print(buf.seek(0, 1)) print(inp.read(1)) @@ -20,24 +22,32 @@ print(inp.read()) print(buf.seek(0, 1)) # Check FHCRC field -buf = io.BytesIO(b'\x1f\x8b\x08\x02\x99\x0c\xe5W\x00\x03\x00\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8b\x08\x02\x99\x0c\xe5W\x00\x03\x00\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" +) inp = zlib.DecompIO(buf, 16 + 8) print(inp.read()) # Check FEXTRA field -buf = io.BytesIO(b'\x1f\x8b\x08\x04\x99\x0c\xe5W\x00\x03\x01\x00X\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8b\x08\x04\x99\x0c\xe5W\x00\x03\x01\x00X\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" +) inp = zlib.DecompIO(buf, 16 + 8) print(inp.read()) # broken header -buf = io.BytesIO(b'\x1f\x8c\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8c\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" +) try: inp = zlib.DecompIO(buf, 16 + 8) except ValueError: print("ValueError") # broken crc32 -buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa7\x106\x05\x00\x00\x00') +buf = io.BytesIO( + b"\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa7\x106\x05\x00\x00\x00" +) inp = zlib.DecompIO(buf, 16 + 8) try: inp.read(6) @@ -45,6 +55,6 @@ except OSError as e: print(repr(e)) # broken uncompressed size - not checked so far -#buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x06\x00\x00\x00') -#inp = zlib.DecompIO(buf, 16 + 8) -#inp.read(6) +# buf = io.BytesIO(b'\x1f\x8b\x08\x08\x99\x0c\xe5W\x00\x03hello\x00\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x06\x00\x00\x00') +# inp = zlib.DecompIO(buf, 16 + 8) +# inp.read(6) diff --git a/tests/extmod/uzlib_decompress.py b/tests/extmod/uzlib_decompress.py index dd6e4876fa..8d4a9640b4 100644 --- a/tests/extmod/uzlib_decompress.py +++ b/tests/extmod/uzlib_decompress.py @@ -9,15 +9,24 @@ except ImportError: PATTERNS = [ # Packed results produced by CPy's zlib.compress() - (b'0', b'x\x9c3\x00\x00\x001\x001'), - (b'a', b'x\x9cK\x04\x00\x00b\x00b'), - (b'0' * 100, b'x\x9c30\xa0=\x00\x00\xb3q\x12\xc1'), - (bytes(range(64)), b'x\x9cc`dbfaec\xe7\xe0\xe4\xe2\xe6\xe1\xe5\xe3\x17\x10\x14\x12\x16\x11\x15\x13\x97\x90\x94\x92\x96\x91\x95\x93WPTRVQUS\xd7\xd0\xd4\xd2\xd6\xd1\xd5\xd370426153\xb7\xb0\xb4\xb2\xb6\xb1\xb5\xb3\x07\x00\xaa\xe0\x07\xe1'), - (b'hello', b'x\x01\x01\x05\x00\xfa\xffhello\x06,\x02\x15'), # compression level 0 + (b"0", b"x\x9c3\x00\x00\x001\x001"), + (b"a", b"x\x9cK\x04\x00\x00b\x00b"), + (b"0" * 100, b"x\x9c30\xa0=\x00\x00\xb3q\x12\xc1"), + ( + bytes(range(64)), + b"x\x9cc`dbfaec\xe7\xe0\xe4\xe2\xe6\xe1\xe5\xe3\x17\x10\x14\x12\x16\x11\x15\x13\x97\x90\x94\x92\x96\x91\x95\x93WPTRVQUS\xd7\xd0\xd4\xd2\xd6\xd1\xd5\xd370426153\xb7\xb0\xb4\xb2\xb6\xb1\xb5\xb3\x07\x00\xaa\xe0\x07\xe1", + ), + (b"hello", b"x\x01\x01\x05\x00\xfa\xffhello\x06,\x02\x15"), # compression level 0 # adaptive/dynamic huffman tree - (b'13371813150|13764518736|12345678901', b'x\x9c\x05\xc1\x81\x01\x000\x04\x04\xb1\x95\\\x1f\xcfn\x86o\x82d\x06Qq\xc8\x9d\xc5X}I}\x00\x951D>I}\x00\x951D>I}\x00\x951D>I}\x00\x951D', b'x\x9c\x05\xc11\x01\x00\x00\x00\x010\x95\x14py\x84\x12C_\x9bR\x8cV\x8a\xd1J1Z)F\x1fw`\x089'), + ( + b">I}\x00\x951D>I}\x00\x951D>I}\x00\x951D>I}\x00\x951D", + b"x\x9c\x05\xc11\x01\x00\x00\x00\x010\x95\x14py\x84\x12C_\x9bR\x8cV\x8a\xd1J1Z)F\x1fw`\x089", + ), ] for unpacked, packed in PATTERNS: @@ -26,26 +35,26 @@ for unpacked, packed in PATTERNS: # Raw DEFLATE bitstream -v = b'\xcbH\xcd\xc9\xc9\x07\x00' +v = b"\xcbH\xcd\xc9\xc9\x07\x00" exp = b"hello" out = zlib.decompress(v, -15) -assert(out == exp) +assert out == exp print(exp) # Even when you ask CPython zlib.compress to produce Raw DEFLATE stream, # it returns it with adler2 and oriignal size appended, as if it was a # zlib stream. Make sure there're no random issues decompressing such. -v = b'\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00' +v = b"\xcbH\xcd\xc9\xc9\x07\x00\x86\xa6\x106\x05\x00\x00\x00" out = zlib.decompress(v, -15) -assert(out == exp) +assert out == exp # this should error try: - zlib.decompress(b'abc') + zlib.decompress(b"abc") except Exception: print("Exception") # invalid block type try: - zlib.decompress(b'\x07', -15) # final-block, block-type=3 (invalid) + zlib.decompress(b"\x07", -15) # final-block, block-type=3 (invalid) except Exception as er: - print('Exception') + print("Exception") diff --git a/tests/extmod/vfs_basic.py b/tests/extmod/vfs_basic.py index fbcc92bade..c8e203b3df 100644 --- a/tests/extmod/vfs_basic.py +++ b/tests/extmod/vfs_basic.py @@ -2,6 +2,7 @@ try: import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -11,55 +12,67 @@ except (ImportError, AttributeError): class Filesystem: def __init__(self, id): self.id = id + def mount(self, readonly, mkfs): - print(self.id, 'mount', readonly, mkfs) + print(self.id, "mount", readonly, mkfs) + def umount(self): - print(self.id, 'umount') + print(self.id, "umount") + def ilistdir(self, dir): - print(self.id, 'ilistdir', dir) - return iter([('a%d' % self.id, 0, 0)]) + print(self.id, "ilistdir", dir) + return iter([("a%d" % self.id, 0, 0)]) + def chdir(self, dir): - print(self.id, 'chdir', dir) + print(self.id, "chdir", dir) + def getcwd(self): - print(self.id, 'getcwd') - return 'dir%d' % self.id + print(self.id, "getcwd") + return "dir%d" % self.id + def mkdir(self, path): - print(self.id, 'mkdir', path) + print(self.id, "mkdir", path) + def remove(self, path): - print(self.id, 'remove', path) + print(self.id, "remove", path) + def rename(self, old_path, new_path): - print(self.id, 'rename', old_path, new_path) + print(self.id, "rename", old_path, new_path) + def rmdir(self, path): - print(self.id, 'rmdir', path) + print(self.id, "rmdir", path) + def stat(self, path): - print(self.id, 'stat', path) + print(self.id, "stat", path) return (self.id,) + def statvfs(self, path): - print(self.id, 'statvfs', path) + print(self.id, "statvfs", path) return (self.id,) + def open(self, file, mode): - print(self.id, 'open', file, mode) + print(self.id, "open", file, mode) # first we umount any existing mount points the target may have try: - uos.umount('/') + uos.umount("/") except OSError: pass -for path in uos.listdir('/'): - uos.umount('/' + path) +for path in uos.listdir("/"): + uos.umount("/" + path) # stat root dir -print(uos.stat('/')) +print(uos.stat("/")) # statvfs root dir; verify that f_namemax has a sensible size -print(uos.statvfs('/')[9] >= 32) +print(uos.statvfs("/")[9] >= 32) # getcwd when in root dir print(uos.getcwd()) # basic mounting and listdir -uos.mount(Filesystem(1), '/test_mnt') +uos.mount(Filesystem(1), "/test_mnt") print(uos.listdir()) # ilistdir @@ -68,80 +81,80 @@ print(next(i)) try: next(i) except StopIteration: - print('StopIteration') + print("StopIteration") try: next(i) except StopIteration: - print('StopIteration') + print("StopIteration") # referencing the mount point in different ways -print(uos.listdir('test_mnt')) -print(uos.listdir('/test_mnt')) +print(uos.listdir("test_mnt")) +print(uos.listdir("/test_mnt")) # mounting another filesystem -uos.mount(Filesystem(2), '/test_mnt2', readonly=True) +uos.mount(Filesystem(2), "/test_mnt2", readonly=True) print(uos.listdir()) -print(uos.listdir('/test_mnt2')) +print(uos.listdir("/test_mnt2")) # mounting over an existing mount point try: - uos.mount(Filesystem(3), '/test_mnt2') + uos.mount(Filesystem(3), "/test_mnt2") except OSError: - print('OSError') + print("OSError") # mkdir of a mount point try: - uos.mkdir('/test_mnt') + uos.mkdir("/test_mnt") except OSError: - print('OSError') + print("OSError") # rename across a filesystem try: - uos.rename('/test_mnt/a', '/test_mnt2/b') + uos.rename("/test_mnt/a", "/test_mnt2/b") except OSError: - print('OSError') + print("OSError") # delegating to mounted filesystem -uos.chdir('test_mnt') +uos.chdir("test_mnt") print(uos.listdir()) print(uos.getcwd()) -uos.mkdir('test_dir') -uos.remove('test_file') -uos.rename('test_file', 'test_file2') -uos.rmdir('test_dir') -print(uos.stat('test_file')) -print(uos.statvfs('/test_mnt')) -open('test_file') -open('test_file', 'wb') +uos.mkdir("test_dir") +uos.remove("test_file") +uos.rename("test_file", "test_file2") +uos.rmdir("test_dir") +print(uos.stat("test_file")) +print(uos.statvfs("/test_mnt")) +open("test_file") +open("test_file", "wb") # umount -uos.umount('/test_mnt') -uos.umount('/test_mnt2') +uos.umount("/test_mnt") +uos.umount("/test_mnt2") # umount a non-existent mount point try: - uos.umount('/test_mnt') + uos.umount("/test_mnt") except OSError: - print('OSError') + print("OSError") # root dir -uos.mount(Filesystem(3), '/') -print(uos.stat('/')) -print(uos.statvfs('/')) +uos.mount(Filesystem(3), "/") +print(uos.stat("/")) +print(uos.statvfs("/")) print(uos.listdir()) -open('test') +open("test") -uos.mount(Filesystem(4), '/mnt') +uos.mount(Filesystem(4), "/mnt") print(uos.listdir()) -print(uos.listdir('/mnt')) -uos.chdir('/mnt') +print(uos.listdir("/mnt")) +uos.chdir("/mnt") print(uos.listdir()) # chdir to a subdir within root-mounted vfs, and then listdir -uos.chdir('/subdir') +uos.chdir("/subdir") print(uos.listdir()) -uos.chdir('/') +uos.chdir("/") -uos.umount('/') -print(uos.listdir('/')) -uos.umount('/mnt') +uos.umount("/") +print(uos.listdir("/")) +uos.umount("/mnt") diff --git a/tests/extmod/vfs_fat_fileio1.py b/tests/extmod/vfs_fat_fileio1.py index 4635ca84b5..85a7158703 100644 --- a/tests/extmod/vfs_fat_fileio1.py +++ b/tests/extmod/vfs_fat_fileio1.py @@ -20,19 +20,19 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] return 0 def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] return 0 def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (op, arg)) + # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # BP_IOCTL_SEC_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # BP_IOCTL_SEC_SIZE @@ -47,8 +47,8 @@ except MemoryError: uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) -uos.mount(vfs, '/ramdisk') -uos.chdir('/ramdisk') +uos.mount(vfs, "/ramdisk") +uos.chdir("/ramdisk") # file IO f = open("foo_file.txt", "w") @@ -56,7 +56,7 @@ print(str(f)[:17], str(f)[-1:]) f.write("hello!") f.flush() f.close() -f.close() # allowed +f.close() # allowed try: f.write("world!") except OSError as e: @@ -84,21 +84,21 @@ with open("foo_file.txt") as f2: print(f2.read()) print(f2.tell()) - f2.seek(0, 0) # SEEK_SET + f2.seek(0, 0) # SEEK_SET print(f2.read(1)) - f2.seek(0, 1) # SEEK_CUR + f2.seek(0, 1) # SEEK_CUR print(f2.read(1)) - f2.seek(2, 1) # SEEK_CUR + f2.seek(2, 1) # SEEK_CUR print(f2.read(1)) - f2.seek(-2, 2) # SEEK_END + f2.seek(-2, 2) # SEEK_END print(f2.read(1)) # using constructor of FileIO type to open a file # no longer working with new VFS sub-system -#FileIO = type(f) -#with FileIO("/ramdisk/foo_file.txt") as f: +# FileIO = type(f) +# with FileIO("/ramdisk/foo_file.txt") as f: # print(f.read()) # dirs @@ -107,7 +107,7 @@ vfs.mkdir("foo_dir") try: vfs.rmdir("foo_file.txt") except OSError as e: - print(e.args[0] == 20) # uerrno.ENOTDIR + print(e.args[0] == 20) # uerrno.ENOTDIR vfs.remove("foo_file.txt") print(list(vfs.ilistdir())) @@ -117,23 +117,25 @@ print(list(vfs.ilistdir())) # finaliser is a different path to normal allocation. It would be better to # test this in the core tests but there are no core objects that use finaliser. import micropython + micropython.heap_lock() try: - vfs.open('x', 'r') + vfs.open("x", "r") except MemoryError: - print('MemoryError') + print("MemoryError") micropython.heap_unlock() # Here we test that the finaliser is actually called during a garbage collection. import gc + N = 4 for i in range(N): - n = 'x%d' % i - f = vfs.open(n, 'w') + n = "x%d" % i + f = vfs.open(n, "w") f.write(n) - f = None # release f without closing - [0, 1, 2, 3] # use up Python stack so f is really gone -gc.collect() # should finalise all N files by closing them + f = None # release f without closing + [0, 1, 2, 3] # use up Python stack so f is really gone +gc.collect() # should finalise all N files by closing them for i in range(N): - with vfs.open('x%d' % i, 'r') as f: + with vfs.open("x%d" % i, "r") as f: print(f.read()) diff --git a/tests/extmod/vfs_fat_fileio2.py b/tests/extmod/vfs_fat_fileio2.py index ab9623ddf8..2b8c8155c7 100644 --- a/tests/extmod/vfs_fat_fileio2.py +++ b/tests/extmod/vfs_fat_fileio2.py @@ -20,19 +20,19 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] return 0 def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] return 0 def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (op, arg)) + # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # BP_IOCTL_SEC_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # BP_IOCTL_SEC_SIZE @@ -47,8 +47,8 @@ except MemoryError: uos.VfsFat.mkfs(bdev) vfs = uos.VfsFat(bdev) -uos.mount(vfs, '/ramdisk') -uos.chdir('/ramdisk') +uos.mount(vfs, "/ramdisk") +uos.chdir("/ramdisk") try: vfs.mkdir("foo_dir") @@ -113,4 +113,4 @@ try: f = open("large_file.txt", "wb") f.write(bytearray(bsize * free)) except OSError as e: - print("ENOSPC:", e.args[0] == 28) # uerrno.ENOSPC + print("ENOSPC:", e.args[0] == 28) # uerrno.ENOSPC diff --git a/tests/extmod/vfs_fat_more.py b/tests/extmod/vfs_fat_more.py index 8ddaf49fc2..acae8c5844 100644 --- a/tests/extmod/vfs_fat_more.py +++ b/tests/extmod/vfs_fat_more.py @@ -1,4 +1,5 @@ import uerrno + try: import uos except ImportError: @@ -20,19 +21,19 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] return 0 def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] return 0 def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (op, arg)) + # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # BP_IOCTL_SEC_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # BP_IOCTL_SEC_SIZE @@ -48,75 +49,76 @@ except MemoryError: # first we umount any existing mount points the target may have try: - uos.umount('/') + uos.umount("/") except OSError: pass -for path in uos.listdir('/'): - uos.umount('/' + path) +for path in uos.listdir("/"): + uos.umount("/" + path) uos.VfsFat.mkfs(bdev) -uos.mount(bdev, '/') +uos.mount(bdev, "/") print(uos.getcwd()) -f = open('test.txt', 'w') -f.write('hello') +f = open("test.txt", "w") +f.write("hello") f.close() print(uos.listdir()) -print(uos.listdir('/')) -print(uos.stat('')[:-3]) -print(uos.stat('/')[:-3]) -print(uos.stat('test.txt')[:-3]) -print(uos.stat('/test.txt')[:-3]) +print(uos.listdir("/")) +print(uos.stat("")[:-3]) +print(uos.stat("/")[:-3]) +print(uos.stat("test.txt")[:-3]) +print(uos.stat("/test.txt")[:-3]) -f = open('/test.txt') +f = open("/test.txt") print(f.read()) f.close() -uos.rename('test.txt', 'test2.txt') +uos.rename("test.txt", "test2.txt") print(uos.listdir()) -uos.rename('test2.txt', '/test3.txt') +uos.rename("test2.txt", "/test3.txt") print(uos.listdir()) -uos.rename('/test3.txt', 'test4.txt') +uos.rename("/test3.txt", "test4.txt") print(uos.listdir()) -uos.rename('/test4.txt', '/test5.txt') +uos.rename("/test4.txt", "/test5.txt") print(uos.listdir()) -uos.mkdir('dir') +uos.mkdir("dir") print(uos.listdir()) -uos.mkdir('/dir2') +uos.mkdir("/dir2") print(uos.listdir()) -uos.mkdir('dir/subdir') -print(uos.listdir('dir')) -for exist in ('', '/', 'dir', '/dir', 'dir/subdir'): +uos.mkdir("dir/subdir") +print(uos.listdir("dir")) +for exist in ("", "/", "dir", "/dir", "dir/subdir"): try: uos.mkdir(exist) except OSError as er: - print('mkdir OSError', er.args[0] == 17) # EEXIST + print("mkdir OSError", er.args[0] == 17) # EEXIST -uos.chdir('/') -print(uos.stat('test5.txt')[:-3]) +uos.chdir("/") +print(uos.stat("test5.txt")[:-3]) uos.VfsFat.mkfs(bdev2) -uos.mount(bdev2, '/sys') +uos.mount(bdev2, "/sys") print(uos.listdir()) -print(uos.listdir('sys')) -print(uos.listdir('/sys')) +print(uos.listdir("sys")) +print(uos.listdir("/sys")) -uos.rmdir('dir2') -uos.remove('test5.txt') +uos.rmdir("dir2") +uos.remove("test5.txt") print(uos.listdir()) -uos.umount('/') +uos.umount("/") print(uos.getcwd()) print(uos.listdir()) -print(uos.listdir('sys')) +print(uos.listdir("sys")) # test importing a file from a mounted FS import sys + sys.path.clear() -sys.path.append('/sys') -with open('sys/test_module.py', 'w') as f: +sys.path.append("/sys") +with open("sys/test_module.py", "w") as f: f.write('print("test_module!")') import test_module diff --git a/tests/extmod/vfs_fat_oldproto.py b/tests/extmod/vfs_fat_oldproto.py index b671f3db2b..e447ff4eb3 100644 --- a/tests/extmod/vfs_fat_oldproto.py +++ b/tests/extmod/vfs_fat_oldproto.py @@ -11,6 +11,7 @@ except AttributeError: print("SKIP") raise SystemExit + class RAMFS_OLD: SEC_SIZE = 512 @@ -19,13 +20,13 @@ class RAMFS_OLD: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] return 0 def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] return 0 diff --git a/tests/extmod/vfs_fat_ramdisk.py b/tests/extmod/vfs_fat_ramdisk.py index 30a94ec4e1..c883d522c0 100644 --- a/tests/extmod/vfs_fat_ramdisk.py +++ b/tests/extmod/vfs_fat_ramdisk.py @@ -20,19 +20,19 @@ class RAMFS: self.data = bytearray(blocks * self.SEC_SIZE) def readblocks(self, n, buf): - #print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) + # print("readblocks(%s, %x(%d))" % (n, id(buf), len(buf))) for i in range(len(buf)): buf[i] = self.data[n * self.SEC_SIZE + i] return 0 def writeblocks(self, n, buf): - #print("writeblocks(%s, %x)" % (n, id(buf))) + # print("writeblocks(%s, %x)" % (n, id(buf))) for i in range(len(buf)): self.data[n * self.SEC_SIZE + i] = buf[i] return 0 def ioctl(self, op, arg): - #print("ioctl(%d, %r)" % (op, arg)) + # print("ioctl(%d, %r)" % (op, arg)) if op == 4: # BP_IOCTL_SEC_COUNT return len(self.data) // self.SEC_SIZE if op == 5: # BP_IOCTL_SEC_SIZE @@ -53,7 +53,7 @@ print(b"hello!" not in bdev.data) vfs = uos.VfsFat(bdev) uos.mount(vfs, "/ramdisk") -vfs.label = 'label test' +vfs.label = "label test" print("label:", vfs.label) print("statvfs:", vfs.statvfs("/ramdisk")) print("getcwd:", vfs.getcwd()) @@ -68,7 +68,7 @@ with vfs.open("foo_file.txt", "w") as f: print(list(vfs.ilistdir())) print("stat root:", vfs.stat("/")) -print("stat file:", vfs.stat("foo_file.txt")[:-3]) # timestamps differ across runs +print("stat file:", vfs.stat("foo_file.txt")[:-3]) # timestamps differ across runs print(b"FOO_FILETXT" in bdev.data) print(b"hello!" in bdev.data) @@ -98,4 +98,4 @@ print(list(vfs.ilistdir(b""))) try: vfs.ilistdir(b"no_exist") except OSError as e: - print('ENOENT:', e.args[0] == uerrno.ENOENT) + print("ENOENT:", e.args[0] == uerrno.ENOENT) diff --git a/tests/extmod/vfs_userfs.py b/tests/extmod/vfs_userfs.py index e913f9748c..60bf4d0997 100644 --- a/tests/extmod/vfs_userfs.py +++ b/tests/extmod/vfs_userfs.py @@ -6,6 +6,7 @@ import sys, uio try: uio.IOBase import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -16,8 +17,10 @@ class UserFile(uio.IOBase): def __init__(self, data): self.data = data self.pos = 0 + def read(self): return self.data + def readinto(self, buf): n = 0 while n < len(buf) and self.pos < len(self.data): @@ -25,44 +28,49 @@ class UserFile(uio.IOBase): n += 1 self.pos += 1 return n + def ioctl(self, req, arg): - print('ioctl', req, arg) + print("ioctl", req, arg) return 0 class UserFS: def __init__(self, files): self.files = files + def mount(self, readonly, mksfs): pass + def umount(self): pass + def stat(self, path): - print('stat', path) + print("stat", path) if path in self.files: return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0) raise OSError + def open(self, path, mode): - print('open', path, mode) + print("open", path, mode) return UserFile(self.files[path]) # create and mount a user filesystem user_files = { - '/data.txt': b"some data in a text file\n", - '/usermod1.py': b"print('in usermod1')\nimport usermod2", - '/usermod2.py': b"print('in usermod2')", + "/data.txt": b"some data in a text file\n", + "/usermod1.py": b"print('in usermod1')\nimport usermod2", + "/usermod2.py": b"print('in usermod2')", } -uos.mount(UserFS(user_files), '/userfs') +uos.mount(UserFS(user_files), "/userfs") # open and read a file -f = open('/userfs/data.txt') +f = open("/userfs/data.txt") print(f.read()) # import files from the user filesystem -sys.path.append('/userfs') +sys.path.append("/userfs") import usermod1 # unmount and undo path addition -uos.umount('/userfs') +uos.umount("/userfs") sys.path.pop() diff --git a/tests/extmod/websocket_basic.py b/tests/extmod/websocket_basic.py index 9a80503a03..8c5cf58257 100644 --- a/tests/extmod/websocket_basic.py +++ b/tests/extmod/websocket_basic.py @@ -11,6 +11,7 @@ def ws_read(msg, sz): ws = websocket.websocket(uio.BytesIO(msg)) return ws.read(sz) + # do a websocket write and then return the raw data from the stream def ws_write(msg, sz): s = uio.BytesIO() @@ -19,31 +20,32 @@ def ws_write(msg, sz): s.seek(0) return s.read(sz) + # basic frame print(ws_read(b"\x81\x04ping", 4)) -print(ws_read(b"\x80\x04ping", 4)) # FRAME_CONT +print(ws_read(b"\x80\x04ping", 4)) # FRAME_CONT print(ws_write(b"pong", 6)) # split frames are not supported # print(ws_read(b"\x01\x04ping", 4)) # extended payloads -print(ws_read(b'\x81~\x00\x80' + b'ping' * 32, 128)) +print(ws_read(b"\x81~\x00\x80" + b"ping" * 32, 128)) print(ws_write(b"pong" * 32, 132)) # mask (returned data will be 'mask' ^ 'mask') print(ws_read(b"\x81\x84maskmask", 4)) # close control frame -s = uio.BytesIO(b'\x88\x00') # FRAME_CLOSE +s = uio.BytesIO(b"\x88\x00") # FRAME_CLOSE ws = websocket.websocket(s) print(ws.read(1)) s.seek(2) print(s.read(4)) # misc control frames -print(ws_read(b"\x89\x00\x81\x04ping", 4)) # FRAME_PING -print(ws_read(b"\x8a\x00\x81\x04pong", 4)) # FRAME_PONG +print(ws_read(b"\x89\x00\x81\x04ping", 4)) # FRAME_PING +print(ws_read(b"\x8a\x00\x81\x04pong", 4)) # FRAME_PONG # close method ws = websocket.websocket(uio.BytesIO()) @@ -51,8 +53,8 @@ ws.close() # ioctl ws = websocket.websocket(uio.BytesIO()) -print(ws.ioctl(8)) # GET_DATA_OPTS -print(ws.ioctl(9, 2)) # SET_DATA_OPTS +print(ws.ioctl(8)) # GET_DATA_OPTS +print(ws.ioctl(9, 2)) # SET_DATA_OPTS print(ws.ioctl(9)) try: ws.ioctl(-1) diff --git a/tests/feature_check/byteorder.py b/tests/feature_check/byteorder.py index d60f939568..c82a41a24b 100644 --- a/tests/feature_check/byteorder.py +++ b/tests/feature_check/byteorder.py @@ -1,2 +1,3 @@ import sys + print(sys.byteorder) diff --git a/tests/feature_check/coverage.py b/tests/feature_check/coverage.py index dcda53eae2..82647ee314 100644 --- a/tests/feature_check/coverage.py +++ b/tests/feature_check/coverage.py @@ -1,5 +1,5 @@ try: extra_coverage - print('coverage') + print("coverage") except NameError: - print('no') + print("no") diff --git a/tests/feature_check/float.py b/tests/feature_check/float.py index af93f59763..d6d2a99d24 100644 --- a/tests/feature_check/float.py +++ b/tests/feature_check/float.py @@ -5,9 +5,9 @@ try: except NameError: print(0) else: - if float('1.0000001') == float('1.0'): + if float("1.0000001") == float("1.0"): print(30) - elif float('1e300') == float('inf'): + elif float("1e300") == float("inf"): print(32) else: print(64) diff --git a/tests/feature_check/reverse_ops.py b/tests/feature_check/reverse_ops.py index 668748bc57..68eb91b44e 100644 --- a/tests/feature_check/reverse_ops.py +++ b/tests/feature_check/reverse_ops.py @@ -1,8 +1,8 @@ class Foo: - def __radd__(self, other): pass + try: 5 + Foo() except TypeError: diff --git a/tests/float/array_construct.py b/tests/float/array_construct.py index 938675835b..6b5c996312 100644 --- a/tests/float/array_construct.py +++ b/tests/float/array_construct.py @@ -6,5 +6,5 @@ except ImportError: print("SKIP") raise SystemExit -print(array('f', array('h', [1, 2]))) -print(array('d', array('f', [1, 2]))) +print(array("f", array("h", [1, 2]))) +print(array("d", array("f", [1, 2]))) diff --git a/tests/float/builtin_float_hash.py b/tests/float/builtin_float_hash.py index 7a7e374010..f77b1a1834 100644 --- a/tests/float/builtin_float_hash.py +++ b/tests/float/builtin_float_hash.py @@ -1,25 +1,9 @@ # test builtin hash function with float args # these should hash to an integer with a specific value -for val in ( - '0.0', - '-0.0', - '1.0', - '2.0', - '-12.0', - '12345.0', - ): +for val in ("0.0", "-0.0", "1.0", "2.0", "-12.0", "12345.0"): print(val, hash(float(val))) # just check that these values are hashable -for val in ( - '0.1', - '-0.1', - '10.3', - '0.4e3', - '1e16', - 'inf', - '-inf', - 'nan', - ): +for val in ("0.1", "-0.1", "10.3", "0.4e3", "1e16", "inf", "-inf", "nan"): print(val, type(hash(float(val)))) diff --git a/tests/float/builtin_float_pow.py b/tests/float/builtin_float_pow.py index 2de1b48176..98998bdc7c 100644 --- a/tests/float/builtin_float_pow.py +++ b/tests/float/builtin_float_pow.py @@ -6,6 +6,6 @@ print(pow(1.0, 1)) print(pow(2.0, 3.0)) print(pow(2.0, -4.0)) -print(pow(0.0, float('inf'))) -print(pow(0.0, float('-inf'))) -print(pow(0.0, float('nan'))) +print(pow(0.0, float("inf"))) +print(pow(0.0, float("-inf"))) +print(pow(0.0, float("nan"))) diff --git a/tests/float/builtin_float_round.py b/tests/float/builtin_float_round.py index 63cb39aa35..1153b8a2bf 100644 --- a/tests/float/builtin_float_round.py +++ b/tests/float/builtin_float_round.py @@ -2,8 +2,18 @@ # check basic cases tests = [ - [0.0], [1.0], [0.1], [-0.1], [123.4], [123.6], [-123.4], [-123.6], - [1.234567, 5], [1.23456, 1], [1.23456, 0], [1234.56, -2] + [0.0], + [1.0], + [0.1], + [-0.1], + [123.4], + [123.6], + [-123.4], + [-123.6], + [1.234567, 5], + [1.23456, 1], + [1.23456, 0], + [1234.56, -2], ] for t in tests: print(round(*t)) @@ -17,7 +27,7 @@ for i in range(-1, 3): print(round(1.47, i)) # test inf and nan -for val in (float('inf'), float('nan')): +for val in (float("inf"), float("nan")): try: round(val) except (ValueError, OverflowError) as e: diff --git a/tests/float/builtin_float_round_intbig.py b/tests/float/builtin_float_round_intbig.py index 2083e3ea3a..c8a338eefd 100644 --- a/tests/float/builtin_float_round_intbig.py +++ b/tests/float/builtin_float_round_intbig.py @@ -1,4 +1,4 @@ # test round() with floats that return large integers for x in (-1e25, 1e25): - print('%.3g' % round(x)) + print("%.3g" % round(x)) diff --git a/tests/float/bytearray_construct.py b/tests/float/bytearray_construct.py index e960d624ec..f84fa7be58 100644 --- a/tests/float/bytearray_construct.py +++ b/tests/float/bytearray_construct.py @@ -6,4 +6,4 @@ except ImportError: print("SKIP") raise SystemExit -print(bytearray(array('f', [1, 2.3]))) +print(bytearray(array("f", [1, 2.3]))) diff --git a/tests/float/bytes_construct.py b/tests/float/bytes_construct.py index 0e4482e436..c24263758e 100644 --- a/tests/float/bytes_construct.py +++ b/tests/float/bytes_construct.py @@ -6,4 +6,4 @@ except ImportError: print("SKIP") raise SystemExit -print(bytes(array('f', [1, 2.3]))) +print(bytes(array("f", [1, 2.3]))) diff --git a/tests/float/cmath_fun.py b/tests/float/cmath_fun.py index ae5921c304..26f6c227cf 100644 --- a/tests/float/cmath_fun.py +++ b/tests/float/cmath_fun.py @@ -11,29 +11,33 @@ print("%.5g" % e) print("%.5g" % pi) test_values_non_zero = [] -base_values = (0.0, 0.5, 1.2345, 10.) +base_values = (0.0, 0.5, 1.2345, 10.0) for r in base_values: for i in base_values: - if r != 0. or i != 0.: + if r != 0.0 or i != 0.0: test_values_non_zero.append(complex(r, i)) - if r != 0.: + if r != 0.0: test_values_non_zero.append(complex(-r, i)) - if i != 0.: + if i != 0.0: test_values_non_zero.append(complex(r, -i)) - if r != 0. and i != 0.: + if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) -test_values = [complex(0., 0.),] + test_values_non_zero +test_values = [complex(0.0, 0.0)] + test_values_non_zero print(test_values) functions = [ - ('phase', phase, test_values), - ('polar', polar, test_values), - ('rect', rect, ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (1, -1), (123., -456.))), - ('exp', exp, test_values), - ('log', log, test_values_non_zero), - ('sqrt', sqrt, test_values), - ('cos', cos, test_values), - ('sin', sin, test_values), + ("phase", phase, test_values), + ("polar", polar, test_values), + ( + "rect", + rect, + ((0, 0), (0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (-1, 1), (1, -1), (123.0, -456.0)), + ), + ("exp", exp, test_values), + ("log", log, test_values_non_zero), + ("sqrt", sqrt, test_values), + ("cos", cos, test_values), + ("sin", sin, test_values), ] for f_name, f, test_vals in functions: @@ -51,5 +55,5 @@ for f_name, f, test_vals in functions: # some test (eg cmath.sqrt(-0.5)) disagree with CPython with tiny real part real = ret.real if abs(real) < 1e15: - real = 0. + real = 0.0 print("complex(%.5g, %.5g)" % (real, ret.imag)) diff --git a/tests/float/cmath_fun_special.py b/tests/float/cmath_fun_special.py index 471fda8c0d..1d9abac6b4 100644 --- a/tests/float/cmath_fun_special.py +++ b/tests/float/cmath_fun_special.py @@ -2,27 +2,26 @@ try: from cmath import * + log10 except (ImportError, NameError): print("SKIP") raise SystemExit test_values_non_zero = [] -base_values = (0.0, 0.5, 1.2345, 10.) +base_values = (0.0, 0.5, 1.2345, 10.0) for r in base_values: for i in base_values: - if r != 0. or i != 0.: + if r != 0.0 or i != 0.0: test_values_non_zero.append(complex(r, i)) - if r != 0.: + if r != 0.0: test_values_non_zero.append(complex(-r, i)) - if i != 0.: + if i != 0.0: test_values_non_zero.append(complex(r, -i)) - if r != 0. and i != 0.: + if r != 0.0 and i != 0.0: test_values_non_zero.append(complex(-r, -i)) -functions = [ - ('log10', log10, test_values_non_zero), -] +functions = [("log10", log10, test_values_non_zero)] for f_name, f, test_vals in functions: print(f_name) diff --git a/tests/float/complex1.py b/tests/float/complex1.py index 479b4b3485..e6338551c5 100644 --- a/tests/float/complex1.py +++ b/tests/float/complex1.py @@ -27,18 +27,23 @@ print(1j * 2j) print(1j / 2) print((1j / 2j).real) print(1j / (1 + 2j)) -ans = 0j ** 0; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 0j ** 1; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 0j ** 0j; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 1j ** 2.5; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = 1j ** 2.5j; print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 0 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 1 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 0j ** 0j +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j ** 2.5 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j ** 2.5j +print("%.5g %.5g" % (ans.real, ans.imag)) # comparison print(1j == 1) print(1j == 1j) # comparison of nan is special -nan = float('nan') * 1j +nan = float("nan") * 1j print(nan == 1j) print(nan == nan) @@ -54,20 +59,22 @@ print(type(hash(1j))) print(1.2 + 3j) # negative base and fractional power should create a complex -ans = (-1) ** 2.3; print("%.5g %.5g" % (ans.real, ans.imag)) -ans = (-1.2) ** -3.4; print("%.5g %.5g" % (ans.real, ans.imag)) +ans = (-1) ** 2.3 +print("%.5g %.5g" % (ans.real, ans.imag)) +ans = (-1.2) ** -3.4 +print("%.5g %.5g" % (ans.real, ans.imag)) # check printing of inf/nan -print(float('nan') * 1j) -print(float('-nan') * 1j) -print(float('inf') * (1 + 1j)) -print(float('-inf') * (1 + 1j)) +print(float("nan") * 1j) +print(float("-nan") * 1j) +print(float("inf") * (1 + 1j)) +print(float("-inf") * (1 + 1j)) # can't assign to attributes try: (1j).imag = 0 except AttributeError: - print('AttributeError') + print("AttributeError") # can't convert rhs to complex try: @@ -93,11 +100,11 @@ try: except TypeError: print("TypeError") -#small int on LHS, complex on RHS, unsupported op +# small int on LHS, complex on RHS, unsupported op try: print(1 | 1j) except TypeError: - print('TypeError') + print("TypeError") # zero division try: diff --git a/tests/float/complex1_intbig.py b/tests/float/complex1_intbig.py index ed2390bbaf..864036b991 100644 --- a/tests/float/complex1_intbig.py +++ b/tests/float/complex1_intbig.py @@ -1,4 +1,5 @@ # test basic complex number functionality # convert bignum to complex on rhs -ans = 1j + (1 << 70); print("%.5g %.5g" % (ans.real, ans.imag)) +ans = 1j + (1 << 70) +print("%.5g %.5g" % (ans.real, ans.imag)) diff --git a/tests/float/float1.py b/tests/float/float1.py index 54807e5ac9..e51e96fd99 100644 --- a/tests/float/float1.py +++ b/tests/float/float1.py @@ -1,11 +1,11 @@ # test basic float capabilities # literals -print(.12) -print(1.) +print(0.12) +print(1.0) print(1.2) print(0e0) -print(0e+0) +print(0e0) print(0e-0) # float construction @@ -66,7 +66,7 @@ print(1.2 >= 3.4) print(1.2 >= -3.4) # comparison of nan is special -nan = float('nan') +nan = float("nan") print(nan == 1.2) print(nan == nan) @@ -106,7 +106,7 @@ except TypeError: try: print(1 | 1.0) except TypeError: - print('TypeError') + print("TypeError") # can't convert list to float try: diff --git a/tests/float/float2int_doubleprec_intbig.py b/tests/float/float2int_doubleprec_intbig.py index de2137d66c..24d30fe691 100644 --- a/tests/float/float2int_doubleprec_intbig.py +++ b/tests/float/float2int_doubleprec_intbig.py @@ -6,6 +6,7 @@ except: import struct import sys + maxsize_bits = 0 maxsize = sys.maxsize while maxsize: @@ -31,32 +32,33 @@ if ll_type is None: # This case occurs with time.time() values if ll_type != 0: - print(int(1418774543.)) - print("%d" % 1418774543.) + print(int(1418774543.0)) + print("%d" % 1418774543.0) if ll_type == 3: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) else: - print(int(1073741823.)) - print("%d" % 1073741823.) + print(int(1073741823.0)) + print("%d" % 1073741823.0) testpass = True -p2_rng = ((30,63,1024),(62,63,1024))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 1024), (62, 63, 1024))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2**%u was %u bits long' % (i, bitcnt)); + print("fail: 2**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) testpass = True -p10_rng = ((9,18,23),(18,18,23))[is_64bit][ll_type] -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +p10_rng = ((9, 18, 23), (18, 18, 23))[is_64bit][ll_type] +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10**%u was %u digits long' % (i, digcnt)); + print("fail: 10**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -64,37 +66,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.9999999999999981*2.**1023., 'large neg', False) - fp2int_test(1.9999999999999981*2.**1023., 'large pos', False) + fp2int_test(-1.9999999999999981 * 2.0 ** 1023.0, "large neg", False) + fp2int_test(1.9999999999999981 * 2.0 ** 1023.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float2int_fp30_intbig.py b/tests/float/float2int_fp30_intbig.py index fbb94a4ccc..da39800401 100644 --- a/tests/float/float2int_fp30_intbig.py +++ b/tests/float/float2int_fp30_intbig.py @@ -6,6 +6,7 @@ except: import struct import sys + maxsize_bits = 0 maxsize = sys.maxsize while maxsize: @@ -30,30 +31,31 @@ if ll_type is None: ll_type = 2 # basic conversion -print(int(14187744.)) -print("%d" % 14187744.) +print(int(14187744.0)) +print("%d" % 14187744.0) if ll_type == 2: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) testpass = True -p2_rng = ((30,63,127),(62,63,127))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 127), (62, 63, 127))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2.**%u was %u bits long' % (i, bitcnt)); + print("fail: 2.**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) # TODO why does 10**12 fail this test for single precision float? testpass = True p10_rng = 9 -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10.**%u was %u digits long' % (i, digcnt)); + print("fail: 10.**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -61,37 +63,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.999999879*2.**126., 'large neg', False) - fp2int_test(1.999999879*2.**126., 'large pos', False) + fp2int_test(-1.999999879 * 2.0 ** 126.0, "large neg", False) + fp2int_test(1.999999879 * 2.0 ** 126.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float2int_intbig.py b/tests/float/float2int_intbig.py index 3596d2f73d..30522d44ff 100644 --- a/tests/float/float2int_intbig.py +++ b/tests/float/float2int_intbig.py @@ -32,30 +32,31 @@ if ll_type is None: # basic conversion -print(int(14187745.)) -print("%d" % 14187745.) +print(int(14187745.0)) +print("%d" % 14187745.0) if ll_type == 2: - print(int(2.**100)) - print("%d" % 2.**100) + print(int(2.0 ** 100)) + print("%d" % 2.0 ** 100) testpass = True -p2_rng = ((30,63,127),(62,63,127))[is_64bit][ll_type] -for i in range(0,p2_rng): - bitcnt = len(bin(int(2.**i))) - 3; +p2_rng = ((30, 63, 127), (62, 63, 127))[is_64bit][ll_type] +for i in range(0, p2_rng): + bitcnt = len(bin(int(2.0 ** i))) - 3 if i != bitcnt: - print('fail: 2.**%u was %u bits long' % (i, bitcnt)); + print("fail: 2.**%u was %u bits long" % (i, bitcnt)) testpass = False -print("power of 2 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 2 test: %s" % (testpass and "passed" or "failed")) # TODO why does 10**12 fail this test for single precision float? testpass = True p10_rng = 9 if (ll_type == 0 and ~is_64bit) else 11 -for i in range(0,p10_rng): - digcnt = len(str(int(10.**i))) - 1; +for i in range(0, p10_rng): + digcnt = len(str(int(10.0 ** i))) - 1 if i != digcnt: - print('fail: 10.**%u was %u digits long' % (i, digcnt)); + print("fail: 10.**%u was %u digits long" % (i, digcnt)) testpass = False -print("power of 10 test: %s" % (testpass and 'passed' or 'failed')) +print("power of 10 test: %s" % (testpass and "passed" or "failed")) + def fp2int_test(num, name, should_fail): try: @@ -63,37 +64,38 @@ def fp2int_test(num, name, should_fail): passed = ~should_fail except: passed = should_fail - print('%s: %s' % (name, passed and 'passed' or 'failed')) + print("%s: %s" % (name, passed and "passed" or "failed")) + if ll_type != 2: if ll_type == 0: if is_64bit: - neg_bad_fp = -1.00000005*2.**62. - pos_bad_fp = 2.**62. - neg_good_fp = -2.**62. - pos_good_fp = 0.99999993*2.**62. + neg_bad_fp = -1.00000005 * 2.0 ** 62.0 + pos_bad_fp = 2.0 ** 62.0 + neg_good_fp = -(2.0 ** 62.0) + pos_good_fp = 0.99999993 * 2.0 ** 62.0 else: - neg_bad_fp = -1.00000005*2.**30. - pos_bad_fp = 2.**30. - neg_good_fp = -2.**30. - pos_good_fp = 0.9999999499*2.**30. + neg_bad_fp = -1.00000005 * 2.0 ** 30.0 + pos_bad_fp = 2.0 ** 30.0 + neg_good_fp = -(2.0 ** 30.0) + pos_good_fp = 0.9999999499 * 2.0 ** 30.0 else: - neg_bad_fp = -0.51*2.**64. - pos_bad_fp = 2.**63. - neg_good_fp = -2.**63. - pos_good_fp = 1.9999998*2.**62. + neg_bad_fp = -0.51 * 2.0 ** 64.0 + pos_bad_fp = 2.0 ** 63.0 + neg_good_fp = -(2.0 ** 63.0) + pos_good_fp = 1.9999998 * 2.0 ** 62.0 - fp2int_test(neg_bad_fp, 'neg bad', True) - fp2int_test(pos_bad_fp, 'pos bad', True) - fp2int_test(neg_good_fp, 'neg good', False) - fp2int_test(pos_good_fp, 'pos good', False) + fp2int_test(neg_bad_fp, "neg bad", True) + fp2int_test(pos_bad_fp, "pos bad", True) + fp2int_test(neg_good_fp, "neg good", False) + fp2int_test(pos_good_fp, "pos good", False) else: - fp2int_test(-1.999999879*2.**127., 'large neg', False) - fp2int_test(1.999999879*2.**127., 'large pos', False) + fp2int_test(-1.999999879 * 2.0 ** 127.0, "large neg", False) + fp2int_test(1.999999879 * 2.0 ** 127.0, "large pos", False) -fp2int_test(float('inf'), 'inf test', True) -fp2int_test(float('nan'), 'NaN test', True) +fp2int_test(float("inf"), "inf test", True) +fp2int_test(float("nan"), "NaN test", True) # test numbers < 1 (this used to fail; see issue #1044) -fp2int_test(0.0001, 'small num', False) -struct.pack('I', int(1/2)) +fp2int_test(0.0001, "small num", False) +struct.pack("I", int(1 / 2)) diff --git a/tests/float/float_array.py b/tests/float/float_array.py index 8c8edcff7c..04212c44f4 100644 --- a/tests/float/float_array.py +++ b/tests/float/float_array.py @@ -4,17 +4,19 @@ except ImportError: print("SKIP") raise SystemExit + def test(a): print(a) a.append(1.2) - print(len(a), '%.3f' % a[0]) + print(len(a), "%.3f" % a[0]) a.append(1) a.append(False) - print(len(a), '%.3f %.3f' % (a[1], a[2])) + print(len(a), "%.3f %.3f" % (a[1], a[2])) a[-1] = 3.45 - print('%.3f' % a[-1]) + print("%.3f" % a[-1]) -test(array('f')) -test(array('d')) -print('{:.4f}'.format(array('f', b'\xcc\xcc\xcc=')[0])) +test(array("f")) +test(array("d")) + +print("{:.4f}".format(array("f", b"\xcc\xcc\xcc=")[0])) diff --git a/tests/float/float_compare.py b/tests/float/float_compare.py index 105923ac73..c177aa7e81 100644 --- a/tests/float/float_compare.py +++ b/tests/float/float_compare.py @@ -1,8 +1,10 @@ # Extended float comparisons + class Foo: pass + foo = Foo() print(foo == 1.0) diff --git a/tests/float/float_divmod.py b/tests/float/float_divmod.py index 8e7cd435a5..ec83ce2d19 100644 --- a/tests/float/float_divmod.py +++ b/tests/float/float_divmod.py @@ -1,11 +1,13 @@ # test floating point floor divide and modulus # it has some tricky corner cases + def test(x, y): div, mod = divmod(x, y) - print('%.8f %.8f %.8f %.8f' % (x // y, x % y, div, mod)) + print("%.8f %.8f %.8f %.8f" % (x // y, x % y, div, mod)) print(div == x // y, mod == x % y, abs(div * y + mod - x) < 1e-15) + test(1.23456, 0.7) test(-1.23456, 0.7) test(1.23456, -0.7) diff --git a/tests/float/float_divmod_relaxed.py b/tests/float/float_divmod_relaxed.py index a9450fa2c4..ef5a6ad2e8 100644 --- a/tests/float/float_divmod_relaxed.py +++ b/tests/float/float_divmod_relaxed.py @@ -4,10 +4,12 @@ # pyboard has 32-bit floating point and gives different (but still # correct) answers for certain combinations of divmod arguments. + def test(x, y): div, mod = divmod(x, y) print(div == x // y, mod == x % y, abs(div * y + mod - x) < 1e-6) + test(1.23456, 0.7) test(-1.23456, 0.7) test(1.23456, -0.7) @@ -30,4 +32,4 @@ for i in range(25): try: divmod(1.0, 0) except ZeroDivisionError: - print('ZeroDivisionError') + print("ZeroDivisionError") diff --git a/tests/float/float_format.py b/tests/float/float_format.py index d43535cf2f..4c8a217567 100644 --- a/tests/float/float_format.py +++ b/tests/float/float_format.py @@ -2,18 +2,18 @@ # general rounding for val in (116, 1111, 1234, 5010, 11111): - print('%.0f' % val) - print('%.1f' % val) - print('%.3f' % val) + print("%.0f" % val) + print("%.1f" % val) + print("%.3f" % val) # make sure rounding is done at the correct precision for prec in range(8): - print(('%%.%df' % prec) % 6e-5) + print(("%%.%df" % prec) % 6e-5) # check certain cases that had a digit value of 10 render as a ":" character -print('%.2e' % float('9' * 51 + 'e-39')) -print('%.2e' % float('9' * 40 + 'e-21')) +print("%.2e" % float("9" * 51 + "e-39")) +print("%.2e" % float("9" * 40 + "e-21")) # check a case that would render negative digit values, eg ")" characters # the string is converted back to a float to check for no illegal characters -float('%.23e' % 1e-80) +float("%.23e" % 1e-80) diff --git a/tests/float/float_parse.py b/tests/float/float_parse.py index 4b026de1c8..bef1122ac0 100644 --- a/tests/float/float_parse.py +++ b/tests/float/float_parse.py @@ -1,32 +1,32 @@ # test parsing of floats -inf = float('inf') +inf = float("inf") # it shouldn't matter where the decimal point is if the exponent balances the value -print(float('1234') - float('0.1234e4')) -print(float('1.015625') - float('1015625e-6')) +print(float("1234") - float("0.1234e4")) +print(float("1.015625") - float("1015625e-6")) # very large integer part with a very negative exponent should cancel out -print('%.4e' % float('9' * 60 + 'e-60')) -print('%.4e' % float('9' * 60 + 'e-40')) +print("%.4e" % float("9" * 60 + "e-60")) +print("%.4e" % float("9" * 60 + "e-40")) # many fractional digits -print(float('.' + '9' * 70)) -print(float('.' + '9' * 70 + 'e20')) -print(float('.' + '9' * 70 + 'e-50') == float('1e-50')) +print(float("." + "9" * 70)) +print(float("." + "9" * 70 + "e20")) +print(float("." + "9" * 70 + "e-50") == float("1e-50")) # tiny fraction with large exponent -print(float('.' + '0' * 60 + '1e10') == float('1e-51')) -print(float('.' + '0' * 60 + '9e25') == float('9e-36')) -print(float('.' + '0' * 60 + '9e40') == float('9e-21')) +print(float("." + "0" * 60 + "1e10") == float("1e-51")) +print(float("." + "0" * 60 + "9e25") == float("9e-36")) +print(float("." + "0" * 60 + "9e40") == float("9e-21")) # ensure that accuracy is retained when value is close to a subnormal -print(float('1.00000000000000000000e-37')) -print(float('10.0000000000000000000e-38')) -print(float('100.000000000000000000e-39')) +print(float("1.00000000000000000000e-37")) +print(float("10.0000000000000000000e-38")) +print(float("100.000000000000000000e-39")) # very large exponent literal -print(float('1e4294967301')) -print(float('1e-4294967301')) -print(float('1e18446744073709551621')) -print(float('1e-18446744073709551621')) +print(float("1e4294967301")) +print(float("1e-4294967301")) +print(float("1e18446744073709551621")) +print(float("1e-18446744073709551621")) diff --git a/tests/float/float_parse_doubleprec.py b/tests/float/float_parse_doubleprec.py index dcc0dd5921..81fcadcee8 100644 --- a/tests/float/float_parse_doubleprec.py +++ b/tests/float/float_parse_doubleprec.py @@ -1,21 +1,21 @@ # test parsing of floats, requiring double-precision # very large integer part with a very negative exponent should cancel out -print(float('9' * 400 + 'e-100')) -print(float('9' * 400 + 'e-200')) -print(float('9' * 400 + 'e-400')) +print(float("9" * 400 + "e-100")) +print(float("9" * 400 + "e-200")) +print(float("9" * 400 + "e-400")) # many fractional digits -print(float('.' + '9' * 400)) -print(float('.' + '9' * 400 + 'e100')) -print(float('.' + '9' * 400 + 'e-100')) +print(float("." + "9" * 400)) +print(float("." + "9" * 400 + "e100")) +print(float("." + "9" * 400 + "e-100")) # tiny fraction with large exponent -print('%.14e' % float('.' + '0' * 400 + '9e100')) -print('%.14e' % float('.' + '0' * 400 + '9e200')) -print('%.14e' % float('.' + '0' * 400 + '9e400')) +print("%.14e" % float("." + "0" * 400 + "9e100")) +print("%.14e" % float("." + "0" * 400 + "9e200")) +print("%.14e" % float("." + "0" * 400 + "9e400")) # ensure that accuracy is retained when value is close to a subnormal -print(float('1.00000000000000000000e-307')) -print(float('10.0000000000000000000e-308')) -print(float('100.000000000000000000e-309')) +print(float("1.00000000000000000000e-307")) +print(float("10.0000000000000000000e-308")) +print(float("100.000000000000000000e-309")) diff --git a/tests/float/float_struct.py b/tests/float/float_struct.py index dd7a418ad5..18893af0e0 100644 --- a/tests/float/float_struct.py +++ b/tests/float/float_struct.py @@ -8,10 +8,10 @@ except ImportError: print("SKIP") raise SystemExit -i = 1. + 1/2 +i = 1.0 + 1 / 2 # TODO: it looks like '=' format modifier is not yet supported # for fmt in ('f', 'd', '>f', '>d', 'f', '>d', 'f", ">d", "' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + test("{:10.4}", 123.456) test("{:10.4e}", 123.456) @@ -25,17 +26,17 @@ test("{:06e}", float("-inf")) test("{:06e}", float("nan")) # The following fails right now -#test("{:10.1}", 0.0) +# test("{:10.1}", 0.0) print("%.0f" % (1.750000 % 0.08333333333)) # Below isn't compatible with single-precision float -#print("%.1f" % (1.750000 % 0.08333333333)) -#print("%.2f" % (1.750000 % 0.08333333333)) -#print("%.12f" % (1.750000 % 0.08333333333)) +# print("%.1f" % (1.750000 % 0.08333333333)) +# print("%.2f" % (1.750000 % 0.08333333333)) +# print("%.12f" % (1.750000 % 0.08333333333)) # tests for errors in format string try: - '{:10.1b}'.format(0.0) + "{:10.1b}".format(0.0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/float/string_format2.py b/tests/float/string_format2.py index 269023e7ff..7a36f4d2f9 100644 --- a/tests/float/string_format2.py +++ b/tests/float/string_format2.py @@ -3,15 +3,17 @@ full_tests = False + def test(fmt, *args): - print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg): - fmt = '{' + fmt = "{" if conv: - fmt += '!' + fmt += "!" fmt += conv - fmt += ':' + fmt += ":" if alignment: fmt += fill fmt += alignment @@ -19,88 +21,162 @@ def test_fmt(conv, fill, alignment, sign, prefix, width, precision, type, arg): fmt += prefix fmt += width if precision: - fmt += '.' + fmt += "." fmt += precision fmt += type - fmt += '}' - test(fmt, arg) - if fill == '0' and alignment == '=': - fmt = '{:' + fmt += "}" + test(fmt, arg) + if fill == "0" and alignment == "=": + fmt = "{:" fmt += sign fmt += prefix fmt += width if precision: - fmt += '.' + fmt += "." fmt += precision fmt += type - fmt += '}' + fmt += "}" test(fmt, arg) -eg_nums = (0.0, -0.0, 0.1, 1.234, 12.3459, 1.23456789, 123456789.0, -0.0, - -0.1, -1.234, -12.3459, 1e4, 1e-4, 1e5, 1e-5, 1e6, 1e-6, 1e10, - 1e37, -1e37, 1e-37, -1e-37, - 1.23456e8, 1.23456e7, 1.23456e6, 1.23456e5, 1.23456e4, 1.23456e3, 1.23456e2, 1.23456e1, 1.23456e0, - 1.23456e-1, 1.23456e-2, 1.23456e-3, 1.23456e-4, 1.23456e-5, 1.23456e-6, 1.23456e-7, 1.23456e-8, - -1.23456e8, -1.23456e7, -1.23456e6, -1.23456e5, -1.23456e4, -1.23456e3, -1.23456e2, -1.23456e1, -1.23456e0, - -1.23456e-1, -1.23456e-2, -1.23456e-3, -1.23456e-4, -1.23456e-5, -1.23456e-6, -1.23456e-7, -1.23456e-8) + +eg_nums = ( + 0.0, + -0.0, + 0.1, + 1.234, + 12.3459, + 1.23456789, + 123456789.0, + -0.0, + -0.1, + -1.234, + -12.3459, + 1e4, + 1e-4, + 1e5, + 1e-5, + 1e6, + 1e-6, + 1e10, + 1e37, + -1e37, + 1e-37, + -1e-37, + 1.23456e8, + 1.23456e7, + 1.23456e6, + 1.23456e5, + 1.23456e4, + 1.23456e3, + 1.23456e2, + 1.23456e1, + 1.23456e0, + 1.23456e-1, + 1.23456e-2, + 1.23456e-3, + 1.23456e-4, + 1.23456e-5, + 1.23456e-6, + 1.23456e-7, + 1.23456e-8, + -1.23456e8, + -1.23456e7, + -1.23456e6, + -1.23456e5, + -1.23456e4, + -1.23456e3, + -1.23456e2, + -1.23456e1, + -1.23456e0, + -1.23456e-1, + -1.23456e-2, + -1.23456e-3, + -1.23456e-4, + -1.23456e-5, + -1.23456e-6, + -1.23456e-7, + -1.23456e-8, +) if full_tests: - for type in ('e', 'E', 'g', 'G', 'n'): - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', '@', '0', ' '): - for sign in ('', '+', '-', ' '): - for prec in ('', '1', '3', '6'): + for type in ("e", "E", "g", "G", "n"): + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", "@", "0", " "): + for sign in ("", "+", "-", " "): + for prec in ("", "1", "3", "6"): for num in eg_nums: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) # Note: We use 1.23459 rather than 1.2345 because '{:3f}'.format(1.2345) # rounds differently than print("%.3f", 1.2345); -f_nums = (0.0, -0.0, 0.0001, 0.001, 0.01, 0.1, 1.0, 10.0, - 0.0012, 0.0123, 0.1234, 1.23459, 12.3456, - -0.0001, -0.001, -0.01, -0.1, -1.0, -10.0, - -0.0012, -0.0123, -0.1234, -1.23459, -12.3456) +f_nums = ( + 0.0, + -0.0, + 0.0001, + 0.001, + 0.01, + 0.1, + 1.0, + 10.0, + 0.0012, + 0.0123, + 0.1234, + 1.23459, + 12.3456, + -0.0001, + -0.001, + -0.01, + -0.1, + -1.0, + -10.0, + -0.0012, + -0.0123, + -0.1234, + -1.23459, + -12.3456, +) if full_tests: - for type in ('f', 'F'): - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', ' ', '0', '@'): - for sign in ('', '+', '-', ' '): + for type in ("f", "F"): + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", " ", "0", "@"): + for sign in ("", "+", "-", " "): # An empty precision defaults to 6, but when uPy is # configured to use a float, we can only use a # precision of 6 with numbers less than 10 and still # get results that compare to CPython (which uses # long doubles). - for prec in ('1', '2', '3'): + for prec in ("1", "2", "3"): for num in f_nums: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) for num in int_nums2: - test_fmt('', fill, alignment, sign, '', width, '', type, num) + test_fmt("", fill, alignment, sign, "", width, "", type, num) pct_nums1 = (0.1, 0.58, 0.99, -0.1, -0.58, -0.99) pct_nums2 = (True, False, 1, 0, -1) if full_tests: - type = '%' - for width in ('', '4', '6', '8', '10'): - for alignment in ('', '<', '>', '=', '^'): - for fill in ('', ' ', '0', '@'): - for sign in ('', '+', '-', ' '): + type = "%" + for width in ("", "4", "6", "8", "10"): + for alignment in ("", "<", ">", "=", "^"): + for fill in ("", " ", "0", "@"): + for sign in ("", "+", "-", " "): # An empty precision defaults to 6, but when uPy is # configured to use a float, we can only use a # precision of 6 with numbers less than 10 and still # get results that compare to CPython (which uses # long doubles). - for prec in ('1', '2', '3'): + for prec in ("1", "2", "3"): for num in pct_nums1: - test_fmt('', fill, alignment, sign, '', width, prec, type, num) + test_fmt("", fill, alignment, sign, "", width, prec, type, num) for num in pct_nums2: - test_fmt('', fill, alignment, sign, '', width, '', type, num) + test_fmt("", fill, alignment, sign, "", width, "", type, num) else: for num in pct_nums1: - test_fmt('', '', '', '', '', '', '1', '%', num) + test_fmt("", "", "", "", "", "", "1", "%", num) # We don't currently test a type of '' with floats (see the detailed comment # in objstr.c) diff --git a/tests/float/string_format_fp30.py b/tests/float/string_format_fp30.py index 77b2a52885..5f0b213daa 100644 --- a/tests/float/string_format_fp30.py +++ b/tests/float/string_format_fp30.py @@ -1,11 +1,12 @@ def test(fmt, *args): - print('{:8s}'.format(fmt) + '>' + fmt.format(*args) + '<') + print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<") + test("{:10.4}", 123.456) test("{:10.4e}", 123.456) test("{:10.4e}", -123.456) -#test("{:10.4f}", 123.456) -#test("{:10.4f}", -123.456) +# test("{:10.4f}", 123.456) +# test("{:10.4f}", -123.456) test("{:10.4g}", 123.456) test("{:10.4g}", -123.456) test("{:10.4n}", 123.456) @@ -15,8 +16,8 @@ test("{:g}", 300) test("{:10.4E}", 123.456) test("{:10.4E}", -123.456) -#test("{:10.4F}", 123.456) -#test("{:10.4F}", -123.456) +# test("{:10.4F}", 123.456) +# test("{:10.4F}", -123.456) test("{:10.4G}", 123.456) test("{:10.4G}", -123.456) @@ -25,17 +26,17 @@ test("{:06e}", float("-inf")) test("{:06e}", float("nan")) # The following fails right now -#test("{:10.1}", 0.0) +# test("{:10.1}", 0.0) print("%.0f" % (1.750000 % 0.08333333333)) # Below isn't compatible with single-precision float -#print("%.1f" % (1.750000 % 0.08333333333)) -#print("%.2f" % (1.750000 % 0.08333333333)) -#print("%.12f" % (1.750000 % 0.08333333333)) +# print("%.1f" % (1.750000 % 0.08333333333)) +# print("%.2f" % (1.750000 % 0.08333333333)) +# print("%.12f" % (1.750000 % 0.08333333333)) # tests for errors in format string try: - '{:10.1b}'.format(0.0) + "{:10.1b}".format(0.0) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/float/string_format_modulo.py b/tests/float/string_format_modulo.py index aea534247c..0944615381 100644 --- a/tests/float/string_format_modulo.py +++ b/tests/float/string_format_modulo.py @@ -7,9 +7,9 @@ print("%u" % 1.0) # these 3 have different behaviour in Python 3.x versions # uPy raises a TypeError, following Python 3.5 (earlier versions don't) -#print("%x" % 18.0) -#print("%o" % 18.0) -#print("%X" % 18.0) +# print("%x" % 18.0) +# print("%o" % 18.0) +# print("%X" % 18.0) print("%e" % 1.23456) print("%E" % 1.23456) @@ -22,28 +22,28 @@ print("%06e" % float("inf")) print("%06e" % float("-inf")) print("%06e" % float("nan")) -print("%02.3d" % 123) # prec > width -print("%+f %+f" % (1.23, -1.23)) # float sign -print("% f % f" % (1.23, -1.23)) # float space sign -print("%0f" % -1.23) # negative number with 0 padding +print("%02.3d" % 123) # prec > width +print("%+f %+f" % (1.23, -1.23)) # float sign +print("% f % f" % (1.23, -1.23)) # float space sign +print("%0f" % -1.23) # negative number with 0 padding # numbers with large negative exponents -print('%f' % 1e-10) -print('%f' % 1e-20) -print('%f' % 1e-50) -print('%f' % 1e-100) -print('%f' % 1e-300) +print("%f" % 1e-10) +print("%f" % 1e-20) +print("%f" % 1e-50) +print("%f" % 1e-100) +print("%f" % 1e-300) # large decimal precision should be truncated and not overflow buffer # the output depends on the FP calculation so only first 2 digits are printed # (the 'g' with small e are printed using 'f' style, so need to be checked) -print(('%.40f' % 1e-300)[:2]) -print(('%.40g' % 1e-1)[:2]) -print(('%.40g' % 1e-2)[:2]) -print(('%.40g' % 1e-3)[:2]) -print(('%.40g' % 1e-4)[:2]) +print(("%.40f" % 1e-300)[:2]) +print(("%.40g" % 1e-1)[:2]) +print(("%.40g" % 1e-2)[:2]) +print(("%.40g" % 1e-3)[:2]) +print(("%.40g" % 1e-4)[:2]) -print("%.0g" % 1) # 0 precision 'g' +print("%.0g" % 1) # 0 precision 'g' -print('%.1e' % 9.99) # round up with positive exponent -print('%.1e' % 0.999) # round up with negative exponent +print("%.1e" % 9.99) # round up with positive exponent +print("%.1e" % 0.999) # round up with negative exponent diff --git a/tests/float/string_format_modulo2.py b/tests/float/string_format_modulo2.py index f6b1ae537d..b22021c5d0 100644 --- a/tests/float/string_format_modulo2.py +++ b/tests/float/string_format_modulo2.py @@ -1,24 +1,26 @@ # test formatting floats with large precision, that it doesn't overflow the buffer + def test(num, num_str): - if num == float('inf') or num == 0.0 and num_str != '0.0': + if num == float("inf") or num == 0.0 and num_str != "0.0": # skip numbers that overflow or underflow the FP precision return - for kind in ('e', 'f', 'g'): + for kind in ("e", "f", "g"): # check precision either side of the size of the buffer (32 bytes) for prec in range(23, 36, 2): - fmt = '%.' + '%d' % prec + kind + fmt = "%." + "%d" % prec + kind s = fmt % num check = abs(float(s) - num) if num > 1: check /= num if check > 1e-6: - print('FAIL', num_str, fmt, s, len(s), check) + print("FAIL", num_str, fmt, s, len(s), check) + # check pure zero -test(0.0, '0.0') +test(0.0, "0.0") # check some powers of 10, making sure to include exponents with 3 digits for e in range(-8, 8): num = pow(10, e) - test(num, '1e%d' % e) + test(num, "1e%d" % e) diff --git a/tests/float/string_format_modulo2_intbig.py b/tests/float/string_format_modulo2_intbig.py index 9992ba65d9..8110bc7f62 100644 --- a/tests/float/string_format_modulo2_intbig.py +++ b/tests/float/string_format_modulo2_intbig.py @@ -1,21 +1,23 @@ # test formatting floats with large precision, that it doesn't overflow the buffer + def test(num, num_str): - if num == float('inf') or num == 0.0 and num_str != '0.0': + if num == float("inf") or num == 0.0 and num_str != "0.0": # skip numbers that overflow or underflow the FP precision return - for kind in ('e', 'f', 'g'): + for kind in ("e", "f", "g"): # check precision either side of the size of the buffer (32 bytes) for prec in range(23, 36, 2): - fmt = '%.' + '%d' % prec + kind + fmt = "%." + "%d" % prec + kind s = fmt % num check = abs(float(s) - num) if num > 1: check /= num if check > 1e-6: - print('FAIL', num_str, fmt, s, len(s), check) + print("FAIL", num_str, fmt, s, len(s), check) + # check most powers of 10, making sure to include exponents with 3 digits for e in range(-101, 102): num = pow(10, e) - test(num, '1e%d' % e) + test(num, "1e%d" % e) diff --git a/tests/float/string_format_modulo3.py b/tests/float/string_format_modulo3.py index 5d26f25751..f9d9c43cdf 100644 --- a/tests/float/string_format_modulo3.py +++ b/tests/float/string_format_modulo3.py @@ -1,3 +1,3 @@ # uPy and CPython outputs differ for the following -print("%.1g" % -9.9) # round up 'g' with '-' sign -print("%.2g" % 99.9) # round up +print("%.1g" % -9.9) # round up 'g' with '-' sign +print("%.2g" % 99.9) # round up diff --git a/tests/float/true_value.py b/tests/float/true_value.py index df415f0031..4c8d2e5c82 100644 --- a/tests/float/true_value.py +++ b/tests/float/true_value.py @@ -3,5 +3,5 @@ if not 0.0: print("float 0") -if not 0+0j: +if not 0 + 0j: print("complex 0") diff --git a/tests/import/builtin_import.py b/tests/import/builtin_import.py index 088f631fcd..5258da8916 100644 --- a/tests/import/builtin_import.py +++ b/tests/import/builtin_import.py @@ -1,16 +1,16 @@ # test calling builtin import function # basic test -__import__('builtins') +__import__("builtins") # first arg should be a string try: __import__(1) except TypeError: - print('TypeError') + print("TypeError") # level argument should be non-negative try: - __import__('xyz', None, None, None, -1) + __import__("xyz", None, None, None, -1) except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/import/gen_context.py b/tests/import/gen_context.py index 02f1531467..b7567cf02d 100644 --- a/tests/import/gen_context.py +++ b/tests/import/gen_context.py @@ -2,8 +2,10 @@ import gen_context2 GLOBAL = "GLOBAL" + def gen(): print(GLOBAL) yield 1 + gen_context2.call(gen()) diff --git a/tests/import/import1a.py b/tests/import/import1a.py index 16b2d4d30f..9d7d72ff77 100644 --- a/tests/import/import1a.py +++ b/tests/import/import1a.py @@ -1,2 +1,3 @@ import import1b + print(import1b.var) diff --git a/tests/import/import1b.py b/tests/import/import1b.py index be74eca094..8c9d15a71f 100644 --- a/tests/import/import1b.py +++ b/tests/import/import1b.py @@ -1,4 +1,5 @@ var = 123 + def throw(): raise ValueError diff --git a/tests/import/import2a.py b/tests/import/import2a.py index def6aeb6aa..8fb4905250 100644 --- a/tests/import/import2a.py +++ b/tests/import/import2a.py @@ -1,5 +1,7 @@ from import1b import var + print(var) from import1b import var as var2 + print(var2) diff --git a/tests/import/import3a.py b/tests/import/import3a.py index 2e9d41f71d..2fadd8a52b 100644 --- a/tests/import/import3a.py +++ b/tests/import/import3a.py @@ -1,2 +1,3 @@ from import1b import * + print(var) diff --git a/tests/import/import_file.py b/tests/import/import_file.py index cb9a88a706..90ec4e41e7 100644 --- a/tests/import/import_file.py +++ b/tests/import/import_file.py @@ -1,2 +1,3 @@ import import1b + print(import1b.__file__) diff --git a/tests/import/import_pkg1.py b/tests/import/import_pkg1.py index fe6e4473e3..5c1b2ef4c7 100644 --- a/tests/import/import_pkg1.py +++ b/tests/import/import_pkg1.py @@ -12,5 +12,6 @@ print(pkg_.mod is pkg.mod) # import using "as" import pkg.mod as mm + print(mm is pkg.mod) print(mm.foo()) diff --git a/tests/import/import_pkg3.py b/tests/import/import_pkg3.py index 0ee885b220..ec46979062 100644 --- a/tests/import/import_pkg3.py +++ b/tests/import/import_pkg3.py @@ -3,4 +3,5 @@ from pkg import mod print(mod.foo()) import pkg.mod + print(mod is pkg.mod) diff --git a/tests/import/mpy_invalid.py b/tests/import/mpy_invalid.py index b9dd99a440..188fb16127 100644 --- a/tests/import/mpy_invalid.py +++ b/tests/import/mpy_invalid.py @@ -5,6 +5,7 @@ import sys, uio try: uio.IOBase import uos + uos.mount except (ImportError, AttributeError): print("SKIP") @@ -15,8 +16,10 @@ class UserFile(uio.IOBase): def __init__(self, data): self.data = data self.pos = 0 + def read(self): return self.data + def readinto(self, buf): n = 0 while n < len(buf) and self.pos < len(self.data): @@ -24,6 +27,7 @@ class UserFile(uio.IOBase): n += 1 self.pos += 1 return n + def ioctl(self, req, arg): return 0 @@ -31,37 +35,41 @@ class UserFile(uio.IOBase): class UserFS: def __init__(self, files): self.files = files + def mount(self, readonly, mksfs): pass + def umount(self): pass + def stat(self, path): if path in self.files: return (32768, 0, 0, 0, 0, 0, 0, 0, 0, 0) raise OSError + def open(self, path, mode): return UserFile(self.files[path]) # these are the test .mpy files user_files = { - '/mod0.mpy': b'', # empty file - '/mod1.mpy': b'M', # too short header - '/mod2.mpy': b'M\x00\x00\x00', # bad version + "/mod0.mpy": b"", # empty file + "/mod1.mpy": b"M", # too short header + "/mod2.mpy": b"M\x00\x00\x00", # bad version } # create and mount a user filesystem -uos.mount(UserFS(user_files), '/userfs') -sys.path.append('/userfs') +uos.mount(UserFS(user_files), "/userfs") +sys.path.append("/userfs") # import .mpy files from the user filesystem for i in range(len(user_files)): - mod = 'mod%u' % i + mod = "mod%u" % i try: __import__(mod) except Exception as e: print(mod, type(e).__name__, e) # unmount and undo path addition -uos.umount('/userfs') +uos.umount("/userfs") sys.path.pop() diff --git a/tests/import/pkg3/mod2.py b/tests/import/pkg3/mod2.py index 67f43bad52..37721faaf3 100644 --- a/tests/import/pkg3/mod2.py +++ b/tests/import/pkg3/mod2.py @@ -1,5 +1,6 @@ print("mod2 __name__:", __name__) print("in mod2") + def foo(): print("mod2.foo()") diff --git a/tests/import/pkg6/__init__.py b/tests/import/pkg6/__init__.py index 923531c1b9..5215da2ec4 100644 --- a/tests/import/pkg6/__init__.py +++ b/tests/import/pkg6/__init__.py @@ -1,2 +1,3 @@ from .x import * -print('init') + +print("init") diff --git a/tests/import/pkg6/x/__init__.py b/tests/import/pkg6/x/__init__.py index 6b8b84d0ee..80817917da 100644 --- a/tests/import/pkg6/x/__init__.py +++ b/tests/import/pkg6/x/__init__.py @@ -1,2 +1,3 @@ from .y import * -print('x') + +print("x") diff --git a/tests/import/pkg6/x/y.py b/tests/import/pkg6/x/y.py index e8d863c6cd..0abc82404d 100644 --- a/tests/import/pkg6/x/y.py +++ b/tests/import/pkg6/x/y.py @@ -1 +1 @@ -print('y') +print("y") diff --git a/tests/import/pkg7/mod1.py b/tests/import/pkg7/mod1.py index 6b574114d1..0a5eb15052 100644 --- a/tests/import/pkg7/mod1.py +++ b/tests/import/pkg7/mod1.py @@ -1,2 +1,2 @@ -print('mod1') -foo = 'mod1.foo' +print("mod1") +foo = "mod1.foo" diff --git a/tests/import/pkg7/mod2.py b/tests/import/pkg7/mod2.py index 039a5d1749..657a6fb523 100644 --- a/tests/import/pkg7/mod2.py +++ b/tests/import/pkg7/mod2.py @@ -1,2 +1,2 @@ -print('mod2') -bar = 'mod2.bar' +print("mod2") +bar = "mod2.bar" diff --git a/tests/import/pkg7/subpkg1/subpkg2/mod3.py b/tests/import/pkg7/subpkg1/subpkg2/mod3.py index c73e2081f0..0aa916d208 100644 --- a/tests/import/pkg7/subpkg1/subpkg2/mod3.py +++ b/tests/import/pkg7/subpkg1/subpkg2/mod3.py @@ -1,5 +1,6 @@ from ... import mod1 from ...mod2 import bar + print(mod1.foo) print(bar) @@ -7,4 +8,4 @@ print(bar) try: from .... import mod1 except ValueError: - print('ValueError') + print("ValueError") diff --git a/tests/import/pkg8/mod.py b/tests/import/pkg8/mod.py index b98f02ce6e..3d3d53a162 100644 --- a/tests/import/pkg8/mod.py +++ b/tests/import/pkg8/mod.py @@ -1 +1 @@ -print('foo') +print("foo") diff --git a/tests/import/try_module.py b/tests/import/try_module.py index 03a9db15b5..7c97df28b3 100644 --- a/tests/import/try_module.py +++ b/tests/import/try_module.py @@ -2,8 +2,10 @@ # its namespace stick and namespace of current module not coming back. import import1b + def func1(): - print('func1') + print("func1") + def func2(): try: @@ -12,4 +14,5 @@ def func2(): pass func1() + func2() diff --git a/tests/inlineasm/asmargs.py b/tests/inlineasm/asmargs.py index 047d9ed420..3b03f15103 100644 --- a/tests/inlineasm/asmargs.py +++ b/tests/inlineasm/asmargs.py @@ -1,29 +1,44 @@ # test passing arguments + @micropython.asm_thumb def arg0(): mov(r0, 1) + + print(arg0()) + @micropython.asm_thumb def arg1(r0): add(r0, r0, 1) + + print(arg1(1)) + @micropython.asm_thumb def arg2(r0, r1): add(r0, r0, r1) + + print(arg2(1, 2)) + @micropython.asm_thumb def arg3(r0, r1, r2): add(r0, r0, r1) add(r0, r0, r2) + + print(arg3(1, 2, 3)) + @micropython.asm_thumb def arg4(r0, r1, r2, r3): add(r0, r0, r1) add(r0, r0, r2) add(r0, r0, r3) + + print(arg4(1, 2, 3, 4)) diff --git a/tests/inlineasm/asmbcc.py b/tests/inlineasm/asmbcc.py index 540fa6591f..08967d48c7 100644 --- a/tests/inlineasm/asmbcc.py +++ b/tests/inlineasm/asmbcc.py @@ -1,6 +1,7 @@ # test bcc instructions # at the moment only tests beq, narrow and wide versions + @micropython.asm_thumb def f(r0): mov(r1, r0) @@ -21,6 +22,7 @@ def f(r0): label(end) + print(f(0)) print(f(1)) print(f(2)) diff --git a/tests/inlineasm/asmbitops.py b/tests/inlineasm/asmbitops.py index 8cf92b301f..d1c8a98235 100644 --- a/tests/inlineasm/asmbitops.py +++ b/tests/inlineasm/asmbitops.py @@ -2,12 +2,15 @@ def clz(r0): clz(r0, r0) -print(clz(0xf0)) + +print(clz(0xF0)) print(clz(0x8000)) + @micropython.asm_thumb def rbit(r0): rbit(r0, r0) -print(hex(rbit(0xf0))) + +print(hex(rbit(0xF0))) print(hex(rbit(0x8000))) diff --git a/tests/inlineasm/asmblbx.py b/tests/inlineasm/asmblbx.py index d08c0ed6b3..43585dddcc 100644 --- a/tests/inlineasm/asmblbx.py +++ b/tests/inlineasm/asmblbx.py @@ -1,5 +1,6 @@ # test bl and bx instructions + @micropython.asm_thumb def f(r0): # jump over the internal functions @@ -17,5 +18,6 @@ def f(r0): bl(func1) bl(func2) + print(f(0)) print(f(1)) diff --git a/tests/inlineasm/asmconst.py b/tests/inlineasm/asmconst.py index 299a25093c..8412dd2c72 100644 --- a/tests/inlineasm/asmconst.py +++ b/tests/inlineasm/asmconst.py @@ -1,8 +1,11 @@ # test constants in assembler + @micropython.asm_thumb def c1(): - movwt(r0, 0xffffffff) - movwt(r1, 0xf0000000) + movwt(r0, 0xFFFFFFFF) + movwt(r1, 0xF0000000) sub(r0, r0, r1) + + print(hex(c1())) diff --git a/tests/inlineasm/asmdiv.py b/tests/inlineasm/asmdiv.py index b97d566eb5..c278463846 100644 --- a/tests/inlineasm/asmdiv.py +++ b/tests/inlineasm/asmdiv.py @@ -2,15 +2,17 @@ def sdiv(r0, r1): sdiv(r0, r0, r1) + @micropython.asm_thumb def udiv(r0, r1): udiv(r0, r0, r1) + print(sdiv(1234, 3)) print(sdiv(-1234, 3)) print(sdiv(1234, -3)) print(sdiv(-1234, -3)) print(udiv(1234, 3)) -print(udiv(0xffffffff, 0x7fffffff)) -print(udiv(0xffffffff, 0xffffffff)) +print(udiv(0xFFFFFFFF, 0x7FFFFFFF)) +print(udiv(0xFFFFFFFF, 0xFFFFFFFF)) diff --git a/tests/inlineasm/asmfpaddsub.py b/tests/inlineasm/asmfpaddsub.py index 2bdfccf0e0..f69c89cdc6 100644 --- a/tests/inlineasm/asmfpaddsub.py +++ b/tests/inlineasm/asmfpaddsub.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # r0 = r0+r1-r2 +@micropython.asm_thumb # r0 = r0+r1-r2 def add_sub(r0, r1, r2): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -11,4 +11,5 @@ def add_sub(r0, r1, r2): vcvt_s32_f32(s31, s0) vmov(r0, s31) + print(add_sub(100, 20, 30)) diff --git a/tests/inlineasm/asmfpcmp.py b/tests/inlineasm/asmfpcmp.py index d4fa1f2410..47fd99a347 100644 --- a/tests/inlineasm/asmfpcmp.py +++ b/tests/inlineasm/asmfpcmp.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # test vcmp, vmrs +@micropython.asm_thumb # test vcmp, vmrs def f(r0, r1): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -9,6 +9,7 @@ def f(r0, r1): mov(r1, 28) lsr(r0, r1) -print(f(0,1)) -print(f(1,1)) -print(f(1,0)) + +print(f(0, 1)) +print(f(1, 1)) +print(f(1, 0)) diff --git a/tests/inlineasm/asmfpldrstr.py b/tests/inlineasm/asmfpldrstr.py index 4c480671f9..c65f8a798b 100644 --- a/tests/inlineasm/asmfpldrstr.py +++ b/tests/inlineasm/asmfpldrstr.py @@ -1,11 +1,14 @@ import array -@micropython.asm_thumb # test vldr, vstr + + +@micropython.asm_thumb # test vldr, vstr def arrayadd(r0): vldr(s0, [r0, 0]) vldr(s1, [r0, 4]) vadd(s2, s0, s1) vstr(s2, [r0, 8]) + z = array.array("f", [2, 4, 10]) arrayadd(z) print(z[2]) diff --git a/tests/inlineasm/asmfpmuldiv.py b/tests/inlineasm/asmfpmuldiv.py index 043a28e229..930ddd053c 100644 --- a/tests/inlineasm/asmfpmuldiv.py +++ b/tests/inlineasm/asmfpmuldiv.py @@ -1,4 +1,4 @@ -@micropython.asm_thumb # r0 = (int)(r0*r1/r2) +@micropython.asm_thumb # r0 = (int)(r0*r1/r2) def muldiv(r0, r1, r2): vmov(s0, r0) vcvt_f32_s32(s0, s0) @@ -11,4 +11,5 @@ def muldiv(r0, r1, r2): vcvt_s32_f32(s31, s8) vmov(r0, s31) + print(muldiv(100, 10, 50)) diff --git a/tests/inlineasm/asmfpsqrt.py b/tests/inlineasm/asmfpsqrt.py index 7b7d52e238..519fde4fcc 100644 --- a/tests/inlineasm/asmfpsqrt.py +++ b/tests/inlineasm/asmfpsqrt.py @@ -1,5 +1,5 @@ # test vsqrt, vneg -@micropython.asm_thumb # r0 = -(int)(sqrt(r0)*r1) +@micropython.asm_thumb # r0 = -(int)(sqrt(r0)*r1) def sqrt_test(r0, r1): vmov(s1, r0) vcvt_f32_s32(s1, s1) @@ -11,4 +11,5 @@ def sqrt_test(r0, r1): vcvt_s32_f32(s31, s7) vmov(r0, s31) + print(sqrt_test(256, 10)) diff --git a/tests/inlineasm/asmit.py b/tests/inlineasm/asmit.py index 57bfcc7f9a..640258e7c8 100644 --- a/tests/inlineasm/asmit.py +++ b/tests/inlineasm/asmit.py @@ -1,16 +1,22 @@ # test it instruction + @micropython.asm_thumb def f(r0, r1): cmp(r0, r1) it(eq) mov(r0, 100) + + print(f(0, 0), f(1, 2)) + @micropython.asm_thumb def g(r0, r1): cmp(r0, r1) ite(eq) mov(r0, 100) mov(r0, 200) + + print(g(0, 0), g(0, 1)) diff --git a/tests/inlineasm/asmpushpop.py b/tests/inlineasm/asmpushpop.py index c9005434ba..74e729dfa2 100644 --- a/tests/inlineasm/asmpushpop.py +++ b/tests/inlineasm/asmpushpop.py @@ -5,4 +5,5 @@ def f(r0, r1, r2): pop({r0}) pop({r1, r2}) + print(f(0, 1, 2)) diff --git a/tests/inlineasm/asmrettype.py b/tests/inlineasm/asmrettype.py index f1918696ee..95068795df 100644 --- a/tests/inlineasm/asmrettype.py +++ b/tests/inlineasm/asmrettype.py @@ -1,21 +1,33 @@ # test return type of inline asm + @micropython.asm_thumb def ret_obj(r0) -> object: pass + + ret_obj(print)(1) + @micropython.asm_thumb def ret_bool(r0) -> bool: pass + + print(ret_bool(0), ret_bool(1)) + @micropython.asm_thumb def ret_int(r0) -> int: lsl(r0, r0, 29) + + print(ret_int(0), hex(ret_int(1)), hex(ret_int(2)), hex(ret_int(4))) + @micropython.asm_thumb def ret_uint(r0) -> uint: lsl(r0, r0, 29) + + print(ret_uint(0), hex(ret_uint(1)), hex(ret_uint(2)), hex(ret_uint(4))) diff --git a/tests/inlineasm/asmshift.py b/tests/inlineasm/asmshift.py index 0df2187347..ba4c21b3f2 100644 --- a/tests/inlineasm/asmshift.py +++ b/tests/inlineasm/asmshift.py @@ -1,29 +1,46 @@ @micropython.asm_thumb def lsl1(r0): lsl(r0, r0, 1) + + print(hex(lsl1(0x123))) + @micropython.asm_thumb def lsl23(r0): lsl(r0, r0, 23) + + print(hex(lsl23(1))) + @micropython.asm_thumb def lsr1(r0): lsr(r0, r0, 1) + + print(hex(lsr1(0x123))) + @micropython.asm_thumb def lsr31(r0): lsr(r0, r0, 31) + + print(hex(lsr31(0x80000000))) + @micropython.asm_thumb def asr1(r0): asr(r0, r0, 1) + + print(hex(asr1(0x123))) + @micropython.asm_thumb def asr31(r0): asr(r0, r0, 31) + + print(hex(asr31(0x80000000))) diff --git a/tests/inlineasm/asmspecialregs.py b/tests/inlineasm/asmspecialregs.py index 2d3b0e396f..053ae29a4d 100644 --- a/tests/inlineasm/asmspecialregs.py +++ b/tests/inlineasm/asmspecialregs.py @@ -2,9 +2,11 @@ def getIPSR(): mrs(r0, IPSR) + @micropython.asm_thumb def getBASEPRI(): mrs(r0, BASEPRI) + print(getBASEPRI()) print(getIPSR()) diff --git a/tests/inlineasm/asmsum.py b/tests/inlineasm/asmsum.py index 07e71c7384..f465b25afd 100644 --- a/tests/inlineasm/asmsum.py +++ b/tests/inlineasm/asmsum.py @@ -22,6 +22,7 @@ def asm_sum_words(r0, r1): mov(r0, r2) + @micropython.asm_thumb def asm_sum_bytes(r0, r1): @@ -46,12 +47,13 @@ def asm_sum_bytes(r0, r1): mov(r0, r2) + import array -b = array.array('l', (100, 200, 300, 400)) +b = array.array("l", (100, 200, 300, 400)) n = asm_sum_words(len(b), b) print(b, n) -b = array.array('b', (10, 20, 30, 40, 50, 60, 70, 80)) +b = array.array("b", (10, 20, 30, 40, 50, 60, 70, 80)) n = asm_sum_bytes(len(b), b) print(b, n) diff --git a/tests/io/argv.py b/tests/io/argv.py index a13f2cad21..53254da119 100644 --- a/tests/io/argv.py +++ b/tests/io/argv.py @@ -1,2 +1,3 @@ import sys + print(sys.argv) diff --git a/tests/io/buffered_writer.py b/tests/io/buffered_writer.py index c2cedb9912..64e5fa1ee7 100644 --- a/tests/io/buffered_writer.py +++ b/tests/io/buffered_writer.py @@ -4,7 +4,7 @@ try: io.BytesIO io.BufferedWriter except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit bts = io.BytesIO() diff --git a/tests/io/builtin_print_file.py b/tests/io/builtin_print_file.py index d9b8e2a960..822356a6cc 100644 --- a/tests/io/builtin_print_file.py +++ b/tests/io/builtin_print_file.py @@ -5,13 +5,13 @@ import sys try: sys.stdout except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit print(file=sys.stdout) -print('test', file=sys.stdout) +print("test", file=sys.stdout) try: print(file=1) -except (AttributeError, OSError): # CPython and uPy differ in error message - print('Error') +except (AttributeError, OSError): # CPython and uPy differ in error message + print("Error") diff --git a/tests/io/file1.py b/tests/io/file1.py index af4176b64e..2a46c9c63e 100644 --- a/tests/io/file1.py +++ b/tests/io/file1.py @@ -4,43 +4,43 @@ print(f.readline()) print(f.read()) f = open("io/data/file1") print(f.readlines()) -f = open("io/data/file1","r") +f = open("io/data/file1", "r") print(f.readlines()) -f = open("io/data/file1","rb") +f = open("io/data/file1", "rb") print(f.readlines()) -f = open("io/data/file1",mode="r") +f = open("io/data/file1", mode="r") print(f.readlines()) -f = open("io/data/file1",mode="rb") +f = open("io/data/file1", mode="rb") print(f.readlines()) # write() error -f = open('io/data/file1', 'r') +f = open("io/data/file1", "r") try: - f.write('x') + f.write("x") except OSError: - print('OSError') + print("OSError") f.close() # read(n) error on binary file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.read(1) except OSError: - print('OSError') + print("OSError") f.close() # read(n) error on text file -f = open('io/data/file1', 'at') +f = open("io/data/file1", "at") try: f.read(1) except OSError: - print('OSError') + print("OSError") f.close() # read() w/o args error -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.read() except OSError: - print('OSError') + print("OSError") f.close() diff --git a/tests/io/file_readinto.py b/tests/io/file_readinto.py index cbefc6e040..1f3702a217 100644 --- a/tests/io/file_readinto.py +++ b/tests/io/file_readinto.py @@ -7,8 +7,8 @@ print(f.readinto(b)) print(b) # readinto() on writable file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.readinto(bytearray(4)) except OSError: - print('OSError') + print("OSError") diff --git a/tests/io/file_readline.py b/tests/io/file_readline.py index 25e76597b1..86d010eaf6 100644 --- a/tests/io/file_readline.py +++ b/tests/io/file_readline.py @@ -6,9 +6,9 @@ print(f.readline(5)) print(f.readline()) # readline() on writable file -f = open('io/data/file1', 'ab') +f = open("io/data/file1", "ab") try: f.readline() except OSError: - print('OSError') + print("OSError") f.close() diff --git a/tests/io/file_seek.py b/tests/io/file_seek.py index 10fb1fd06f..2fe57692c6 100644 --- a/tests/io/file_seek.py +++ b/tests/io/file_seek.py @@ -25,10 +25,10 @@ print(f.tell()) f.close() # seek closed file -f = open('io/data/file1', 'r') +f = open("io/data/file1", "r") f.close() try: f.seek(1) except (OSError, ValueError): # CPy raises ValueError, uPy raises OSError - print('OSError or ValueError') + print("OSError or ValueError") diff --git a/tests/io/file_with.py b/tests/io/file_with.py index ee1e702422..899c0f9287 100644 --- a/tests/io/file_with.py +++ b/tests/io/file_with.py @@ -15,7 +15,7 @@ except: # Regression test: test that exception in with initialization properly # thrown and doesn't crash. try: - with open('__non_existent', 'r'): + with open("__non_existent", "r"): pass except OSError: print("OSError") diff --git a/tests/io/iobase.py b/tests/io/iobase.py index 6f554b00f0..667e629858 100644 --- a/tests/io/iobase.py +++ b/tests/io/iobase.py @@ -6,14 +6,15 @@ except: try: io.IOBase except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit class MyIO(io.IOBase): def write(self, buf): # CPython and uPy pass in different types for buf (str vs bytearray) - print('write', len(buf)) + print("write", len(buf)) return len(buf) -print('test', file=MyIO()) + +print("test", file=MyIO()) diff --git a/tests/io/resource_stream.py b/tests/io/resource_stream.py index 37d985bf16..5656205b69 100644 --- a/tests/io/resource_stream.py +++ b/tests/io/resource_stream.py @@ -4,7 +4,7 @@ import sys try: uio.resource_stream except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit buf = uio.resource_stream("data", "file2") diff --git a/tests/io/stringio1.py b/tests/io/stringio1.py index 9f7c1e44ef..6d84917547 100644 --- a/tests/io/stringio1.py +++ b/tests/io/stringio1.py @@ -4,7 +4,7 @@ except ImportError: import io a = io.StringIO() -print('io.StringIO' in repr(a)) +print("io.StringIO" in repr(a)) print(a.getvalue()) print(a.read()) @@ -35,7 +35,7 @@ print(a.read()) a = io.StringIO() a.close() -for f in [a.read, a.getvalue, lambda:a.write("")]: +for f in [a.read, a.getvalue, lambda: a.write("")]: # CPython throws for operations on closed I/O, MicroPython makes # the underlying string empty unless MICROPY_CPYTHON_COMPAT defined try: diff --git a/tests/io/write_ext.py b/tests/io/write_ext.py index 5a6eaa35cf..18cd75ddb6 100644 --- a/tests/io/write_ext.py +++ b/tests/io/write_ext.py @@ -5,7 +5,7 @@ import uio try: uio.BytesIO except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit buf = uio.BytesIO() diff --git a/tests/jni/list.py b/tests/jni/list.py index d58181d0ba..7630a48e89 100644 --- a/tests/jni/list.py +++ b/tests/jni/list.py @@ -1,4 +1,5 @@ import jni + try: ArrayList = jni.cls("java/util/ArrayList") except: diff --git a/tests/jni/object.py b/tests/jni/object.py index aa67615ec8..8fbdb39d39 100644 --- a/tests/jni/object.py +++ b/tests/jni/object.py @@ -1,4 +1,5 @@ import jni + try: Integer = jni.cls("java/lang/Integer") except: diff --git a/tests/jni/system_out.py b/tests/jni/system_out.py index 86c4b9e112..c34d7011f7 100644 --- a/tests/jni/system_out.py +++ b/tests/jni/system_out.py @@ -1,5 +1,6 @@ try: import jni + System = jni.cls("java/lang/System") except: print("SKIP") diff --git a/tests/micropython/const.py b/tests/micropython/const.py index 660a095f2c..1faf22be9a 100644 --- a/tests/micropython/const.py +++ b/tests/micropython/const.py @@ -7,9 +7,11 @@ Y = const(X + 456) print(X, Y + 1) + def f(): print(X, Y + 1) + f() _X = const(12) @@ -17,9 +19,11 @@ _Y = const(_X + 34) print(_X, _Y) + class A: Z = const(1) _Z = const(2) print(Z, _Z) -print(hasattr(A, 'Z'), hasattr(A, '_Z')) + +print(hasattr(A, "Z"), hasattr(A, "_Z")) diff --git a/tests/micropython/const2.py b/tests/micropython/const2.py index 60085a1e04..ed4720122e 100644 --- a/tests/micropython/const2.py +++ b/tests/micropython/const2.py @@ -8,27 +8,37 @@ Z = const(3) # import that uses a constant import micropython as X -print(globals()['X']) + +print(globals()["X"]) # function name that matches a constant def X(): - print('function X', X) -globals()['X']() + print("function X", X) + + +globals()["X"]() # arguments that match a constant def f(X, *Y, **Z): pass + + f(1) # class name that matches a constant class X: def f(self): - print('class X', X) -globals()['X']().f() + print("class X", X) + + +globals()["X"]().f() # constant within a class class A: C1 = const(4) + def X(self): - print('method X', Y, C1, self.C1) + print("method X", Y, C1, self.C1) + + A().X() diff --git a/tests/micropython/const_error.py b/tests/micropython/const_error.py index 6d3d135b56..311cfb4d5e 100644 --- a/tests/micropython/const_error.py +++ b/tests/micropython/const_error.py @@ -2,12 +2,14 @@ from micropython import const + def test_syntax(code): try: exec(code) except SyntaxError: print("SyntaxError") + # argument not a constant test_syntax("a = const(x)") diff --git a/tests/micropython/const_intbig.py b/tests/micropython/const_intbig.py index e749026526..27990c8c20 100644 --- a/tests/micropython/const_intbig.py +++ b/tests/micropython/const_intbig.py @@ -3,8 +3,8 @@ from micropython import const # check we can make consts from bignums -Z1 = const(0xffffffff) -Z2 = const(0xffffffffffffffff) +Z1 = const(0xFFFFFFFF) +Z2 = const(0xFFFFFFFFFFFFFFFF) print(hex(Z1), hex(Z2)) # check arithmetic with bignum diff --git a/tests/micropython/decorator.py b/tests/micropython/decorator.py index bf688968a0..2e7cf17776 100644 --- a/tests/micropython/decorator.py +++ b/tests/micropython/decorator.py @@ -1,7 +1,9 @@ # test micropython-specific decorators + @micropython.bytecode def f(): - return 'bytecode' + return "bytecode" + print(f()) diff --git a/tests/micropython/decorator_error.py b/tests/micropython/decorator_error.py index c7da3119f4..94772ac1e5 100644 --- a/tests/micropython/decorator_error.py +++ b/tests/micropython/decorator_error.py @@ -1,11 +1,13 @@ # test syntax errors for uPy-specific decorators + def test_syntax(code): try: exec(code) except SyntaxError: print("SyntaxError") + # invalid micropython decorators test_syntax("@micropython.a\ndef f(): pass") test_syntax("@micropython.a.b\ndef f(): pass") diff --git a/tests/micropython/emg_exc.py b/tests/micropython/emg_exc.py index 4a9fa18bc1..bca4d2d9fb 100644 --- a/tests/micropython/emg_exc.py +++ b/tests/micropython/emg_exc.py @@ -2,6 +2,7 @@ import micropython import sys + try: import uio except ImportError: @@ -14,6 +15,7 @@ try: except AttributeError: pass + def f(): micropython.heap_lock() try: @@ -31,4 +33,5 @@ def f(): else: print(l) + f() diff --git a/tests/micropython/extreme_exc.py b/tests/micropython/extreme_exc.py index b9db964068..dae5b15186 100644 --- a/tests/micropython/extreme_exc.py +++ b/tests/micropython/extreme_exc.py @@ -5,8 +5,13 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on the heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit @@ -17,11 +22,78 @@ try: except AttributeError: pass + def main(): # create an exception with many args while heap is locked # should revert to empty tuple for args micropython.heap_lock() - e = Exception(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0) + e = Exception( + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + ) micropython.heap_unlock() print(repr(e)) @@ -29,9 +101,12 @@ def main(): # should use emergency exception buffer and truncate the message def f(): pass + micropython.heap_lock() try: - f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1) + f( + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 + ) except Exception as er: e = er micropython.heap_unlock() @@ -46,7 +121,9 @@ def main(): except MemoryError: break try: - f(abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1) + f( + abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz=1 + ) except Exception as er: e = er lst[0] = None @@ -57,6 +134,7 @@ def main(): # should use emergency exception and be unable to resize traceback array def g(): g() + micropython.heap_lock() try: g() @@ -67,13 +145,15 @@ def main(): # create an exception on the heap with some traceback on the heap, but then # raise it with the heap locked so it can't allocate any more traceback - exc = Exception('my exception') + exc = Exception("my exception") try: raise exc except: pass + def h(e): raise e + micropython.heap_lock() try: h(exc) @@ -82,4 +162,5 @@ def main(): micropython.heap_unlock() print(repr(e)) + main() diff --git a/tests/micropython/heap_lock.py b/tests/micropython/heap_lock.py index ca3f5806a8..8558935374 100644 --- a/tests/micropython/heap_lock.py +++ b/tests/micropython/heap_lock.py @@ -11,13 +11,13 @@ micropython.heap_lock() try: print([]) except MemoryError: - print('MemoryError') + print("MemoryError") # expansion of a heap block try: l.extend(l2) except MemoryError: - print('MemoryError') + print("MemoryError") micropython.heap_unlock() diff --git a/tests/micropython/heapalloc.py b/tests/micropython/heapalloc.py index f74bb92c85..99f157105d 100644 --- a/tests/micropython/heapalloc.py +++ b/tests/micropython/heapalloc.py @@ -5,18 +5,26 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit + def f1(a): print(a) + def f2(a, b=2): print(a, b) + def f3(a, b, c, d): x1 = x2 = a x3 = x4 = b @@ -24,19 +32,22 @@ def f3(a, b, c, d): x7 = x8 = d print(x1, x3, x5, x7, x2 + x4 + x6 + x8) + global_var = 1 + def test(): global global_var, global_exc - global_var = 2 # set an existing global variable + global_var = 2 # set an existing global variable for i in range(2): # for loop - f1(i) # function call - f1(i * 2 + 1) # binary operation with small ints - f1(a=i) # keyword arguments - f2(i) # default arg (second one) - f2(i, i) # 2 args + f1(i) # function call + f1(i * 2 + 1) # binary operation with small ints + f1(a=i) # keyword arguments + f2(i) # default arg (second one) + f2(i, i) # 2 args f3(1, 2, 3, 4) # function with lots of local state + # call test() with heap allocation disabled micropython.heap_lock() test() diff --git a/tests/micropython/heapalloc_bytesio2.py b/tests/micropython/heapalloc_bytesio2.py index cd76f58077..3b9f141270 100644 --- a/tests/micropython/heapalloc_bytesio2.py +++ b/tests/micropython/heapalloc_bytesio2.py @@ -3,6 +3,7 @@ try: import uio import micropython + micropython.mem_total except (ImportError, AttributeError): print("SKIP") diff --git a/tests/micropython/heapalloc_exc_raise.py b/tests/micropython/heapalloc_exc_raise.py index fb63a84bf3..99810e0075 100644 --- a/tests/micropython/heapalloc_exc_raise.py +++ b/tests/micropython/heapalloc_exc_raise.py @@ -4,6 +4,7 @@ import micropython e = ValueError("error") + def func(): micropython.heap_lock() try: @@ -19,5 +20,6 @@ def func(): print(e2) micropython.heap_unlock() + func() print("ok") diff --git a/tests/micropython/heapalloc_inst_call.py b/tests/micropython/heapalloc_inst_call.py index 3cc497b73a..14d8826bf0 100644 --- a/tests/micropython/heapalloc_inst_call.py +++ b/tests/micropython/heapalloc_inst_call.py @@ -2,22 +2,27 @@ # doesn't require heap allocation. import micropython + class Foo0: def __call__(self): print("__call__") + class Foo1: def __call__(self, a): print("__call__", a) + class Foo2: def __call__(self, a, b): print("__call__", a, b) + class Foo3: def __call__(self, a, b, c): print("__call__", a, b, c) + f0 = Foo0() f1 = Foo1() f2 = Foo2() diff --git a/tests/micropython/heapalloc_iter.py b/tests/micropython/heapalloc_iter.py index 163e172111..f80a099e94 100644 --- a/tests/micropython/heapalloc_iter.py +++ b/tests/micropython/heapalloc_iter.py @@ -9,7 +9,8 @@ except (NameError, ImportError): try: from micropython import heap_lock, heap_unlock except (ImportError, AttributeError): - heap_lock = heap_unlock = lambda:0 + heap_lock = heap_unlock = lambda: 0 + def do_iter(l): heap_lock() @@ -17,16 +18,18 @@ def do_iter(l): print(i) heap_unlock() + def gen_func(): yield 1 yield 2 + # pre-create collections to iterate over -ba = bytearray(b'123') -ar = array.array('H', (123, 456)) +ba = bytearray(b"123") +ar = array.array("H", (123, 456)) t = (1, 2, 3) l = [1, 2] -d = {1:2} +d = {1: 2} s = set((1,)) fs = frozenset((1,)) g1 = (100 + x for x in range(2)) @@ -34,7 +37,7 @@ g2 = gen_func() # test containment (both success and failure) with the heap locked heap_lock() -print(49 in b'123', 255 in b'123') +print(49 in b"123", 255 in b"123") print(1 in t, -1 in t) print(1 in l, -1 in l) print(1 in d, -1 in d) @@ -42,7 +45,7 @@ print(1 in s, -1 in s) heap_unlock() # test unpacking with the heap locked -unp0 = unp1 = unp2 = None # preallocate slots for globals +unp0 = unp1 = unp2 = None # preallocate slots for globals heap_lock() unp0, unp1, unp2 = t print(unp0, unp1, unp2) @@ -58,7 +61,7 @@ print(sum(t)) heap_unlock() # test iterating over collections with the heap locked -do_iter(b'123') +do_iter(b"123") do_iter(ba) do_iter(ar) do_iter(t) diff --git a/tests/micropython/heapalloc_super.py b/tests/micropython/heapalloc_super.py index a8c23393e4..51afae3d83 100644 --- a/tests/micropython/heapalloc_super.py +++ b/tests/micropython/heapalloc_super.py @@ -4,21 +4,30 @@ import micropython # Check for stackless build, which can't call functions without # allocating a frame on heap. try: - def stackless(): pass - micropython.heap_lock(); stackless(); micropython.heap_unlock() + + def stackless(): + pass + + micropython.heap_lock() + stackless() + micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit + class A: def foo(self): - print('A foo') + print("A foo") return 42 + + class B(A): def foo(self): - print('B foo') + print("B foo") print(super().foo()) + b = B() micropython.heap_lock() diff --git a/tests/micropython/heapalloc_traceback.py b/tests/micropython/heapalloc_traceback.py index 813dea4b21..eabd09388b 100644 --- a/tests/micropython/heapalloc_traceback.py +++ b/tests/micropython/heapalloc_traceback.py @@ -2,6 +2,7 @@ import micropython import sys + try: import uio except ImportError: @@ -15,6 +16,7 @@ try: except: pass + def test(): micropython.heap_lock() global global_exc @@ -22,9 +24,10 @@ def test(): try: raise global_exc except StopIteration: - print('StopIteration') + print("StopIteration") micropython.heap_unlock() + # call test() with heap allocation disabled test() diff --git a/tests/micropython/kbd_intr.py b/tests/micropython/kbd_intr.py index 879c9a229f..81977aaa52 100644 --- a/tests/micropython/kbd_intr.py +++ b/tests/micropython/kbd_intr.py @@ -5,7 +5,7 @@ import micropython try: micropython.kbd_intr except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit # just check we can actually call it diff --git a/tests/micropython/meminfo.py b/tests/micropython/meminfo.py index 698bbbd21c..9df341fbb8 100644 --- a/tests/micropython/meminfo.py +++ b/tests/micropython/meminfo.py @@ -3,8 +3,8 @@ import micropython # these functions are not always available -if not hasattr(micropython, 'mem_info'): - print('SKIP') +if not hasattr(micropython, "mem_info"): + print("SKIP") else: micropython.mem_info() micropython.mem_info(1) diff --git a/tests/micropython/memstats.py b/tests/micropython/memstats.py index 78e4d24736..dee3a4ce2f 100644 --- a/tests/micropython/memstats.py +++ b/tests/micropython/memstats.py @@ -3,8 +3,8 @@ import micropython # these functions are not always available -if not hasattr(micropython, 'mem_total'): - print('SKIP') +if not hasattr(micropython, "mem_total"): + print("SKIP") else: t = micropython.mem_total() c = micropython.mem_current() diff --git a/tests/micropython/native_closure.py b/tests/micropython/native_closure.py index 6c0592e52d..07014e90da 100644 --- a/tests/micropython/native_closure.py +++ b/tests/micropython/native_closure.py @@ -4,11 +4,15 @@ @micropython.native def f(): x = 1 + @micropython.native def g(): nonlocal x return x + return g + + print(f()()) # closing over an argument @@ -18,15 +22,22 @@ def f(x): def g(): nonlocal x return x + return g + + print(f(2)()) # closing over an argument and a normal local @micropython.native def f(x): y = 2 * x + @micropython.native def g(z): return x + y + z + return g + + print(f(2)(3)) diff --git a/tests/micropython/native_const_intbig.py b/tests/micropython/native_const_intbig.py index 611b39d8fe..69bc1d2163 100644 --- a/tests/micropython/native_const_intbig.py +++ b/tests/micropython/native_const_intbig.py @@ -1,7 +1,9 @@ # check loading constants + @micropython.native def f(): return 123456789012345678901234567890 + print(f()) diff --git a/tests/micropython/native_misc.py b/tests/micropython/native_misc.py index 0cd521de6c..7c5415375e 100644 --- a/tests/micropython/native_misc.py +++ b/tests/micropython/native_misc.py @@ -4,10 +4,13 @@ @micropython.native def native_test(x): print(1, [], x) + + native_test(2) # check that GC doesn't collect the native function import gc + gc.collect() native_test(3) @@ -15,17 +18,23 @@ native_test(3) @micropython.native def f(a, b): print(a + b) + + f(1, 2) # native with 3 args @micropython.native def f(a, b, c): print(a + b + c) + + f(1, 2, 3) # check not operator @micropython.native def f(a): print(not a) + + f(False) f(True) diff --git a/tests/micropython/opt_level.py b/tests/micropython/opt_level.py index 5a10047f04..3213dc003d 100644 --- a/tests/micropython/opt_level.py +++ b/tests/micropython/opt_level.py @@ -8,12 +8,12 @@ print(micropython.opt_level()) # check that the optimisation levels actually differ micropython.opt_level(0) -exec('print(__debug__)') +exec("print(__debug__)") micropython.opt_level(1) -exec('print(__debug__)') -exec('assert 0') +exec("print(__debug__)") +exec("assert 0") # check that level 3 doesn't store line numbers # the expected output is that any line is printed as "line 1" micropython.opt_level(3) -exec('try:\n xyz\nexcept NameError as er:\n import sys\n sys.print_exception(er)') +exec("try:\n xyz\nexcept NameError as er:\n import sys\n sys.print_exception(er)") diff --git a/tests/micropython/schedule.py b/tests/micropython/schedule.py index 74f90cb2de..6a91459ea3 100644 --- a/tests/micropython/schedule.py +++ b/tests/micropython/schedule.py @@ -5,16 +5,18 @@ import micropython try: micropython.schedule except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit # Basic test of scheduling a function. + def callback(arg): global done print(arg) done = True + done = False micropython.schedule(callback, 1) while not done: @@ -23,20 +25,23 @@ while not done: # Test that callbacks can be scheduled from within a callback, but # that they don't execute until the outer callback is finished. + def callback_inner(arg): global done - print('inner') + print("inner") done += 1 + def callback_outer(arg): global done micropython.schedule(callback_inner, 0) # need a loop so that the VM can check for pending events for i in range(2): pass - print('outer') + print("outer") done += 1 + done = 0 micropython.schedule(callback_outer, 0) while done != 2: @@ -45,15 +50,17 @@ while done != 2: # Test that scheduling too many callbacks leads to an exception. To do this we # must schedule from within a callback to guarantee that the scheduler is locked. + def callback(arg): global done try: for i in range(100): - micropython.schedule(lambda x:x, None) + micropython.schedule(lambda x: x, None) except RuntimeError: - print('RuntimeError') + print("RuntimeError") done = True + done = False micropython.schedule(callback, None) while not done: diff --git a/tests/micropython/stack_use.py b/tests/micropython/stack_use.py index bc714755a1..266885d9d1 100644 --- a/tests/micropython/stack_use.py +++ b/tests/micropython/stack_use.py @@ -1,7 +1,7 @@ # tests stack_use function in micropython module import micropython -if not hasattr(micropython, 'stack_use'): - print('SKIP') +if not hasattr(micropython, "stack_use"): + print("SKIP") else: - print(type(micropython.stack_use())) # output varies + print(type(micropython.stack_use())) # output varies diff --git a/tests/micropython/viper_addr.py b/tests/micropython/viper_addr.py index cd953ce07d..a696b06628 100644 --- a/tests/micropython/viper_addr.py +++ b/tests/micropython/viper_addr.py @@ -1,29 +1,32 @@ # test passing addresses to viper -@micropython.viper -def get_addr(x:ptr) -> ptr: - return x @micropython.viper -def memset(dest:ptr8, c:int, n:int): +def get_addr(x: ptr) -> ptr: + return x + + +@micropython.viper +def memset(dest: ptr8, c: int, n: int): for i in range(n): dest[i] = c + # create array and get its address -ar = bytearray('0000') +ar = bytearray("0000") addr = get_addr(ar) print(type(ar)) print(type(addr)) print(ar) # pass array as an object -memset(ar, ord('1'), len(ar)) +memset(ar, ord("1"), len(ar)) print(ar) # pass direct pointer to array buffer -memset(addr, ord('2'), len(ar)) +memset(addr, ord("2"), len(ar)) print(ar) # pass direct pointer to array buffer, with offset -memset(addr + 2, ord('3'), len(ar) - 2) +memset(addr + 2, ord("3"), len(ar) - 2) print(ar) diff --git a/tests/micropython/viper_args.py b/tests/micropython/viper_args.py index 2aebe1b048..223026b963 100644 --- a/tests/micropython/viper_args.py +++ b/tests/micropython/viper_args.py @@ -1,28 +1,43 @@ # test calling viper functions with different number of args + @micropython.viper def f0(): print(0) + + f0() + @micropython.viper -def f1(x1:int): +def f1(x1: int): print(x1) + + f1(1) + @micropython.viper -def f2(x1:int, x2:int): +def f2(x1: int, x2: int): print(x1, x2) + + f2(1, 2) -@micropython.viper -def f3(x1:int, x2:int, x3:int): - print(x1, x2, x3) -f3(1, 2, 3) @micropython.viper -def f4(x1:int, x2:int, x3:int, x4:int): +def f3(x1: int, x2: int, x3: int): + print(x1, x2, x3) + + +f3(1, 2, 3) + + +@micropython.viper +def f4(x1: int, x2: int, x3: int, x4: int): print(x1, x2, x3, x4) + + f4(1, 2, 3, 4) # only up to 4 arguments currently supported @@ -31,6 +46,8 @@ f4(1, 2, 3, 4) @micropython.viper def f(*x, **y): pass + + @micropython.viper def f(*): pass diff --git a/tests/micropython/viper_binop_arith.py b/tests/micropython/viper_binop_arith.py index 4d711f1a9f..2691404b7b 100644 --- a/tests/micropython/viper_binop_arith.py +++ b/tests/micropython/viper_binop_arith.py @@ -1,27 +1,36 @@ # test arithmetic operators + @micropython.viper -def add(x:int, y:int): +def add(x: int, y: int): print(x + y) print(y + x) + + add(1, 2) add(42, 3) add(-1, 2) add(-42, -3) + @micropython.viper -def sub(x:int, y:int): +def sub(x: int, y: int): print(x - y) print(y - x) + + sub(1, 2) sub(42, 3) sub(-1, 2) sub(-42, -3) + @micropython.viper -def mul(x:int, y:int): +def mul(x: int, y: int): print(x * y) print(y * x) + + mul(0, 1) mul(1, -1) mul(1, 2) @@ -29,41 +38,56 @@ mul(8, 3) mul(-3, 4) mul(-9, -6) + @micropython.viper -def shl(x:int, y:int): +def shl(x: int, y: int): print(x << y) + + shl(1, 0) shl(1, 3) shl(1, 30) shl(42, 10) shl(-42, 10) + @micropython.viper -def shr(x:int, y:int): +def shr(x: int, y: int): print(x >> y) + + shr(1, 0) shr(1, 3) shr(42, 2) shr(-42, 2) -@micropython.viper -def and_(x:int, y:int): - print(x & y, y & x) -and_(1, 0) -and_(1, 3) -and_(0xf0, 0x3f) -and_(-42, 6) @micropython.viper -def or_(x:int, y:int): +def and_(x: int, y: int): + print(x & y, y & x) + + +and_(1, 0) +and_(1, 3) +and_(0xF0, 0x3F) +and_(-42, 6) + + +@micropython.viper +def or_(x: int, y: int): print(x | y, y | x) + + or_(1, 0) or_(1, 2) or_(-42, 5) + @micropython.viper -def xor(x:int, y:int): +def xor(x: int, y: int): print(x ^ y, y ^ x) + + xor(1, 0) xor(1, 2) xor(-42, 5) diff --git a/tests/micropython/viper_binop_comp.py b/tests/micropython/viper_binop_comp.py index dcf91ed89d..a4c0809c85 100644 --- a/tests/micropython/viper_binop_comp.py +++ b/tests/micropython/viper_binop_comp.py @@ -1,6 +1,6 @@ # test comparison operators @micropython.viper -def f(x:int, y:int): +def f(x: int, y: int): if x < y: print(x, "<", y) if x > y: @@ -14,6 +14,7 @@ def f(x:int, y:int): if x != y: print(x, "!=", y) + f(1, 1) f(2, 1) f(1, 2) diff --git a/tests/micropython/viper_binop_comp_imm.py b/tests/micropython/viper_binop_comp_imm.py index c7c0408959..daab8fcfb5 100644 --- a/tests/micropython/viper_binop_comp_imm.py +++ b/tests/micropython/viper_binop_comp_imm.py @@ -3,6 +3,7 @@ def f(a: int): print(a == -1, a == -255, a == -256, a == -257) + f(-1) f(-255) f(-256) diff --git a/tests/micropython/viper_binop_divmod.py b/tests/micropython/viper_binop_divmod.py index 822424982a..4b74b527d3 100644 --- a/tests/micropython/viper_binop_divmod.py +++ b/tests/micropython/viper_binop_divmod.py @@ -1,16 +1,20 @@ # test floor-division and modulo operators -@micropython.viper -def div(x:int, y:int) -> int: - return x // y @micropython.viper -def mod(x:int, y:int) -> int: +def div(x: int, y: int) -> int: + return x // y + + +@micropython.viper +def mod(x: int, y: int) -> int: return x % y + def dm(x, y): print(div(x, y), mod(x, y)) + for x in (-6, 6): for y in range(-7, 8): if y == 0: diff --git a/tests/micropython/viper_binop_multi_comp.py b/tests/micropython/viper_binop_multi_comp.py index 8065db291b..997c397d4c 100644 --- a/tests/micropython/viper_binop_multi_comp.py +++ b/tests/micropython/viper_binop_multi_comp.py @@ -1,6 +1,6 @@ # test multi comparison operators @micropython.viper -def f(x:int, y:int): +def f(x: int, y: int): if 0 < x < y: print(x, "<", y) if 3 > x > y: @@ -14,6 +14,7 @@ def f(x:int, y:int): if 2 == x != y: print(x, "!=", y) + f(1, 1) f(2, 1) f(1, 2) diff --git a/tests/micropython/viper_cond.py b/tests/micropython/viper_cond.py index a168afce95..d31a5f3cf8 100644 --- a/tests/micropython/viper_cond.py +++ b/tests/micropython/viper_cond.py @@ -6,6 +6,8 @@ def f(): pass else: print("not x", x) + + f() # using True as a conditional @@ -14,6 +16,8 @@ def f(): x = True if x: print("x", x) + + f() # using an int as a conditional @@ -22,4 +26,6 @@ def g(): y = 1 if y: print("y", y) + + g() diff --git a/tests/micropython/viper_error.py b/tests/micropython/viper_error.py index 8472572854..fa136197d7 100644 --- a/tests/micropython/viper_error.py +++ b/tests/micropython/viper_error.py @@ -1,11 +1,13 @@ # test syntax and type errors specific to viper code generation + def test(code): try: exec(code) except (SyntaxError, ViperTypeError, NotImplementedError) as e: print(repr(e)) + # viper: annotations must be identifiers test("@micropython.viper\ndef f(a:1): pass") test("@micropython.viper\ndef f() -> 1: pass") @@ -17,30 +19,36 @@ test("@micropython.viper\ndef f(x:unknown_type): pass") test("@micropython.viper\ndef f(a, b, c, d, e): pass") # local used before type known -test(""" +test( + """ @micropython.viper def f(): print(x) x = 1 -""") +""" +) # type mismatch storing to local -test(""" +test( + """ @micropython.viper def f(): x = 1 y = [] x = y -""") +""" +) # can't implicitly convert type to bool -test(""" +test( + """ @micropython.viper def f(): x = ptr(0) if x: pass -""") +""" +) # incorrect return type test("@micropython.viper\ndef f() -> int: return []") diff --git a/tests/micropython/viper_import.py b/tests/micropython/viper_import.py index 9878007444..3df23e17a7 100644 --- a/tests/micropython/viper_import.py +++ b/tests/micropython/viper_import.py @@ -1,10 +1,15 @@ # test import within viper function + @micropython.viper def f(): import micropython + print(micropython.const(1)) from micropython import const + print(const(2)) + + f() diff --git a/tests/micropython/viper_misc.py b/tests/micropython/viper_misc.py index 021e03f2ca..41389c751d 100644 --- a/tests/micropython/viper_misc.py +++ b/tests/micropython/viper_misc.py @@ -2,61 +2,79 @@ import micropython # viper function taking and returning ints @micropython.viper -def viper_int(x:int, y:int) -> int: +def viper_int(x: int, y: int) -> int: return x + y + 3 + + print(viper_int(1, 2)) # viper function taking and returning objects @micropython.viper -def viper_object(x:object, y:object) -> object: +def viper_object(x: object, y: object) -> object: return x + y + + print(viper_object(1, 2)) # return None as non-object (should return 0) @micropython.viper def viper_ret_none() -> int: return None + + print(viper_ret_none()) # return Ellipsis as object @micropython.viper def viper_ret_ellipsis() -> object: return ... + + print(viper_ret_ellipsis()) # 3 args @micropython.viper -def viper_3args(a:int, b:int, c:int) -> int: +def viper_3args(a: int, b: int, c: int) -> int: return a + b + c + + print(viper_3args(1, 2, 3)) # 4 args @micropython.viper -def viper_4args(a:int, b:int, c:int, d:int) -> int: +def viper_4args(a: int, b: int, c: int, d: int) -> int: return a + b + c + d + + # viper call with 4 args not yet supported -#print(viper_4args(1, 2, 3, 4)) +# print(viper_4args(1, 2, 3, 4)) # a local (should have automatic type int) @micropython.viper -def viper_local(x:int) -> int: +def viper_local(x: int) -> int: y = 4 return x + y + + print(viper_local(3)) # without type annotation, types should default to object @micropython.viper def viper_no_annotation(x, y): return x * y + + print(viper_no_annotation(4, 5)) # a for loop @micropython.viper -def viper_for(a:int, b:int) -> int: +def viper_for(a: int, b: int) -> int: total = 0 for x in range(a, b): total += x return total + + print(viper_for(10, 10000)) # accessing a global @@ -65,42 +83,56 @@ def viper_access_global(): global gl gl = 1 return gl + + print(viper_access_global(), gl) # calling print with object and int types @micropython.viper -def viper_print(x, y:int): +def viper_print(x, y: int): print(x, y + 1) + + viper_print(1, 2) # convert constants to objects in tuple @micropython.viper def viper_tuple_consts(x): return (x, 1, False, True) + + print(viper_tuple_consts(0)) # making a tuple from an object and an int @micropython.viper -def viper_tuple(x, y:int): +def viper_tuple(x, y: int): return (x, y + 1) + + print(viper_tuple(1, 2)) # making a list from an object and an int @micropython.viper -def viper_list(x, y:int): +def viper_list(x, y: int): return [x, y + 1] + + print(viper_list(1, 2)) # making a set from an object and an int @micropython.viper -def viper_set(x, y:int): +def viper_set(x, y: int): return {x, y + 1} + + print(sorted(list(viper_set(1, 2)))) # raising an exception @micropython.viper -def viper_raise(x:int): +def viper_raise(x: int): raise OSError(x) + + try: viper_raise(1) except OSError as e: @@ -110,7 +142,10 @@ except OSError as e: @micropython.viper def viper_gc() -> int: return 1 + + print(viper_gc()) import gc + gc.collect() print(viper_gc()) diff --git a/tests/micropython/viper_misc_intbig.py b/tests/micropython/viper_misc_intbig.py index e036435c7a..055c08d8e5 100644 --- a/tests/micropython/viper_misc_intbig.py +++ b/tests/micropython/viper_misc_intbig.py @@ -4,5 +4,8 @@ import micropython @micropython.viper def viper_uint() -> uint: return uint(-1) + + import sys + print(viper_uint() == (sys.maxsize << 1 | 1)) diff --git a/tests/micropython/viper_ptr16_load.py b/tests/micropython/viper_ptr16_load.py index 0b865eb9e7..30c85d0669 100644 --- a/tests/micropython/viper_ptr16_load.py +++ b/tests/micropython/viper_ptr16_load.py @@ -1,21 +1,25 @@ # test loading from ptr16 type # only works on little endian machines + @micropython.viper -def get(src:ptr16) -> int: +def get(src: ptr16) -> int: return src[0] -@micropython.viper -def get1(src:ptr16) -> int: - return src[1] @micropython.viper -def memadd(src:ptr16, n:int) -> int: +def get1(src: ptr16) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr16, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr16(src_in) @@ -25,7 +29,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'1234') + +b = bytearray(b"1234") print(b) print(get(b), get1(b)) print(memadd(b, 2)) diff --git a/tests/micropython/viper_ptr16_store.py b/tests/micropython/viper_ptr16_store.py index 5a5f25d170..3ca5a027c0 100644 --- a/tests/micropython/viper_ptr16_store.py +++ b/tests/micropython/viper_ptr16_store.py @@ -1,25 +1,30 @@ # test ptr16 type + @micropython.viper -def set(dest:ptr16, val:int): +def set(dest: ptr16, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr16, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr16, val:int, n:int): +def set1(dest: ptr16, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr16, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr16(dest_in) n = int(len(dest_in)) >> 1 for i in range(n): dest[i] = val + b = bytearray(4) print(b) diff --git a/tests/micropython/viper_ptr32_load.py b/tests/micropython/viper_ptr32_load.py index 4d8b3846de..b0b90bcaf5 100644 --- a/tests/micropython/viper_ptr32_load.py +++ b/tests/micropython/viper_ptr32_load.py @@ -1,20 +1,24 @@ # test loading from ptr32 type + @micropython.viper -def get(src:ptr32) -> int: +def get(src: ptr32) -> int: return src[0] -@micropython.viper -def get1(src:ptr32) -> int: - return src[1] @micropython.viper -def memadd(src:ptr32, n:int) -> int: +def get1(src: ptr32) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr32, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr32(src_in) @@ -24,7 +28,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'\x12\x12\x12\x12\x34\x34\x34\x34') + +b = bytearray(b"\x12\x12\x12\x12\x34\x34\x34\x34") print(b) print(hex(get(b)), hex(get1(b))) print(hex(memadd(b, 2))) diff --git a/tests/micropython/viper_ptr32_store.py b/tests/micropython/viper_ptr32_store.py index 973086e4ad..ff0c371ab8 100644 --- a/tests/micropython/viper_ptr32_store.py +++ b/tests/micropython/viper_ptr32_store.py @@ -1,25 +1,30 @@ # test store to ptr32 type + @micropython.viper -def set(dest:ptr32, val:int): +def set(dest: ptr32, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr32, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr32, val:int, n:int): +def set1(dest: ptr32, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr32, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr32(dest_in) n = int(len(dest_in)) >> 2 for i in range(n): dest[i] = val + b = bytearray(8) print(b) diff --git a/tests/micropython/viper_ptr8_load.py b/tests/micropython/viper_ptr8_load.py index 0ccf8a1d76..d871bfb689 100644 --- a/tests/micropython/viper_ptr8_load.py +++ b/tests/micropython/viper_ptr8_load.py @@ -1,20 +1,24 @@ # test loading from ptr8 type + @micropython.viper -def get(src:ptr8) -> int: +def get(src: ptr8) -> int: return src[0] -@micropython.viper -def get1(src:ptr8) -> int: - return src[1] @micropython.viper -def memadd(src:ptr8, n:int) -> int: +def get1(src: ptr8) -> int: + return src[1] + + +@micropython.viper +def memadd(src: ptr8, n: int) -> int: sum = 0 for i in range(n): sum += src[i] return sum + @micropython.viper def memadd2(src_in) -> int: src = ptr8(src_in) @@ -24,7 +28,8 @@ def memadd2(src_in) -> int: sum += src[i] return sum -b = bytearray(b'1234') + +b = bytearray(b"1234") print(b) print(get(b), get1(b)) print(memadd(b, 4)) diff --git a/tests/micropython/viper_ptr8_store.py b/tests/micropython/viper_ptr8_store.py index 5a8622eb10..baa9e2c6d4 100644 --- a/tests/micropython/viper_ptr8_store.py +++ b/tests/micropython/viper_ptr8_store.py @@ -1,25 +1,30 @@ # test ptr8 type + @micropython.viper -def set(dest:ptr8, val:int): +def set(dest: ptr8, val: int): dest[0] = val -@micropython.viper -def set1(dest:ptr8, val:int): - dest[1] = val @micropython.viper -def memset(dest:ptr8, val:int, n:int): +def set1(dest: ptr8, val: int): + dest[1] = val + + +@micropython.viper +def memset(dest: ptr8, val: int, n: int): for i in range(n): dest[i] = val + @micropython.viper -def memset2(dest_in, val:int): +def memset2(dest_in, val: int): dest = ptr8(dest_in) n = int(len(dest_in)) for i in range(n): dest[i] = val + b = bytearray(4) print(b) diff --git a/tests/micropython/viper_subscr.py b/tests/micropython/viper_subscr.py index 2198ed7313..bcaabd3fb4 100644 --- a/tests/micropython/viper_subscr.py +++ b/tests/micropython/viper_subscr.py @@ -1,15 +1,18 @@ # test standard Python subscr using viper types + @micropython.viper -def get(dest, i:int): +def get(dest, i: int): i += 1 return dest[i] + @micropython.viper -def set(dest, i:int, val:int): +def set(dest, i: int, val: int): i += 1 dest[i] = val + 1 + ar = [i for i in range(3)] for i in range(len(ar)): diff --git a/tests/misc/features.py b/tests/misc/features.py index de75cb46d4..419d8795f9 100644 --- a/tests/misc/features.py +++ b/tests/misc/features.py @@ -1,159 +1,199 @@ # mad.py # Alf Clement 27-Mar-2014 # -zero=0 -three=3 +zero = 0 +three = 3 print("1") print("2") print(three) print("{}".format(4)) -five=25//5 +five = 25 // 5 print(int(five)) -j=0 +j = 0 for i in range(4): - j += i + j += i print(j) -print(3+4) +print(3 + 4) try: - a=4//zero + a = 4 // zero except: - print(8) + print(8) print("xxxxxxxxx".count("x")) + + def ten(): - return 10 + return 10 + + print(ten()) -a=[] +a = [] for i in range(13): - a.append(i) + a.append(i) print(a[11]) print(a[-1]) -str="0123456789" -print(str[1]+str[3]) +str = "0123456789" +print(str[1] + str[3]) + + def p(s): - print(s) + print(s) + + p("14") p(15) + + class A: - def __init__(self): - self.a=16 - def print(self): - print(self.a) - def set(self,b): - self.a=b -a=A() + def __init__(self): + self.a = 16 + + def print(self): + print(self.a) + + def set(self, b): + self.a = b + + +a = A() a.print() a.set(17) a.print() -b=A() +b = A() b.set(a.a + 1) b.print() for i in range(20): - pass + pass print(i) if 20 > 30: - a="1" + a = "1" else: - a="2" + a = "2" if 0 < 4: - print(a+"0") + print(a + "0") else: - print(a+"1") -a=[20,21,22,23,24] + print(a + "1") +a = [20, 21, 22, 23, 24] for i in a: - if i < 21: - continue - if i > 21: - break - print(i) -b=[a,a,a] + if i < 21: + continue + if i > 21: + break + print(i) +b = [a, a, a] print(b[1][2]) -print(161//7) -a=24 +print(161 // 7) +a = 24 while True: - try: - def gcheck(): - global a - print(a) - gcheck() - class c25(): - x=25 - x=c25() - print(x.x) - raise - except: - print(26) - print(27+zero) - break + try: + + def gcheck(): + global a + print(a) + + gcheck() + + class c25: + x = 25 + + x = c25() + print(x.x) + raise + except: + print(26) + print(27 + zero) + break print(28) -k=29 +k = 29 + + def f(): - global k - k = yield k + global k + k = yield k + + print(next(f())) while True: - k+= 1 - if k < 30: - continue - break + k += 1 + if k < 30: + continue + break print(k) -for i in [1,2,3]: - class A(): - def __init__(self, c): - self.a = i+10*c - b = A(3) - print(b.a) +for i in [1, 2, 3]: + + class A: + def __init__(self, c): + self.a = i + 10 * c + + b = A(3) + print(b.a) print(34) -p=0 +p = 0 for i in range(35, -1, -1): - print(i) - p = p + 1 - if p > 0: - break -p=36 + print(i) + p = p + 1 + if p > 0: + break +p = 36 while p == 36: - print(p) - p=37 + print(p) + p = 37 print(p) for i in [38]: - print(i) -print(int(exec("def foo(): return 38") == None)+foo()) + print(i) +print(int(exec("def foo(): return 38") == None) + foo()) d = {} exec("def bar(): return 40", d) print(d["bar"]()) + + def fib2(n): - result = [] - a, b = 0, 1 - while a < n: - result.append(a) - a, b = b, a+b - return result -print(fib2(100)[-2]-14) -Answer={} -Answer["ForAll"]=42 + result = [] + a, b = 0, 1 + while a < n: + result.append(a) + a, b = b, a + b + return result + + +print(fib2(100)[-2] - 14) +Answer = {} +Answer["ForAll"] = 42 print(Answer["ForAll"]) i = 43 + + def f(i=i): print(i) + + i = 44 f() print(i) while True: - try: - if None != True: - print(45) - break - else: - print(0) - except: - print(0) + try: + if None != True: + print(45) + break + else: + print(0) + except: + print(0) print(46) -print(46+1) +print(46 + 1) + + def u(p): - if p > 3: - return 3*p - else: - return u(2*p)-3*u(p) + if p > 3: + return 3 * p + else: + return u(2 * p) - 3 * u(p) + + print(u(16)) + + def u49(): - return 49 + return 49 + + print(u49()) diff --git a/tests/misc/non_compliant.py b/tests/misc/non_compliant.py index 9a746a8b05..f745c30e8e 100644 --- a/tests/misc/non_compliant.py +++ b/tests/misc/non_compliant.py @@ -9,137 +9,147 @@ except ImportError: # when super can't find self try: - exec('def f(): super()') + exec("def f(): super()") except SyntaxError: - print('SyntaxError') + print("SyntaxError") # store to exception attribute is not allowed try: ValueError().x = 0 except AttributeError: - print('AttributeError') + print("AttributeError") # array deletion not implemented try: - a = array.array('b', (1, 2, 3)) + a = array.array("b", (1, 2, 3)) del a[1] except TypeError: - print('TypeError') + print("TypeError") # slice with step!=1 not implemented try: - a = array.array('b', (1, 2, 3)) + a = array.array("b", (1, 2, 3)) print(a[3:2:2]) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # containment, looking for integer not implemented try: - print(1 in array.array('B', b'12')) + print(1 in array.array("B", b"12")) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # uPy raises TypeError, shold be ValueError try: - '%c' % b'\x01\x02' + "%c" % b"\x01\x02" except (TypeError, ValueError): - print('TypeError, ValueError') + print("TypeError, ValueError") # attributes/subscr not implemented try: - print('{a[0]}'.format(a=[1, 2])) + print("{a[0]}".format(a=[1, 2])) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str(...) with keywords not implemented try: - str(b'abc', encoding='utf8') + str(b"abc", encoding="utf8") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str.rsplit(None, n) not implemented try: - 'a a a'.rsplit(None, 1) + "a a a".rsplit(None, 1) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str.endswith(s, start) not implemented try: - 'abc'.endswith('c', 1) + "abc".endswith("c", 1) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # str subscr with step!=1 not implemented try: - print('abc'[1:2:3]) + print("abc"[1:2:3]) except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # bytes(...) with keywords not implemented try: - bytes('abc', encoding='utf8') + bytes("abc", encoding="utf8") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # bytes subscr with step!=1 not implemented try: - b'123'[0:3:2] + b"123"[0:3:2] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # tuple load with step!=1 not implemented try: ()[2:3:4] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # list store with step!=1 not implemented try: [][2:3:4] = [] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # list delete with step!=1 not implemented try: del [][2:3:4] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # array slice assignment with unsupported RHS try: bytearray(4)[0:1] = [1, 2] except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") # can't assign attributes to a function def f(): pass + + try: f.x = 1 except AttributeError: - print('AttributeError') + print("AttributeError") # can't call a function type (ie make new instances of a function) try: type(f)() except TypeError: - print('TypeError') + print("TypeError") # test when object explicitly listed at not-last position in parent tuple # this is not compliant with CPython because of illegal MRO class A: def foo(self): - print('A.foo') + print("A.foo") + + class B(object, A): pass + + B().foo() # can't assign property (or other special accessors) to already-subclassed class class A: pass + + class B(A): pass + + try: A.bar = property() except AttributeError: - print('AttributeError') + print("AttributeError") diff --git a/tests/misc/non_compliant_lexer.py b/tests/misc/non_compliant_lexer.py index 7e50d2836c..e1c21f3d71 100644 --- a/tests/misc/non_compliant_lexer.py +++ b/tests/misc/non_compliant_lexer.py @@ -1,31 +1,33 @@ # lexer tests for things that are not implemented, or have non-compliant behaviour + def test(code): try: exec(code) - print('no Error') + print("no Error") except SyntaxError: - print('SyntaxError') + print("SyntaxError") except NotImplementedError: - print('NotImplementedError') + print("NotImplementedError") + # uPy requires spaces between literal numbers and keywords, CPy doesn't try: - eval('1and 0') + eval("1and 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1or 0') + eval("1or 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1if 1else 0') + eval("1if 1else 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") try: - eval('1if 0else 0') + eval("1if 0else 0") except SyntaxError: - print('SyntaxError') + print("SyntaxError") # unicode name escapes are not implemented test('"\\N{LATIN SMALL LETTER A}"') diff --git a/tests/misc/print_exception.py b/tests/misc/print_exception.py index f120fe1e18..11ed320f60 100644 --- a/tests/misc/print_exception.py +++ b/tests/misc/print_exception.py @@ -1,4 +1,5 @@ import sys + try: try: import uio as io @@ -8,12 +9,14 @@ except ImportError: print("SKIP") raise SystemExit -if hasattr(sys, 'print_exception'): +if hasattr(sys, "print_exception"): print_exception = sys.print_exception else: import traceback + print_exception = lambda e, f: traceback.print_exception(None, e, sys.exc_info()[2], file=f) + def print_exc(e): buf = io.StringIO() print_exception(e, buf) @@ -29,36 +32,43 @@ def print_exc(e): elif not l.startswith(" "): print(l) + # basic exception message try: - 1/0 + 1 / 0 except Exception as e: - print('caught') + print("caught") print_exc(e) # exception message with more than 1 source-code line def f(): g() + + def g(): - 2/0 + 2 / 0 + + try: f() except Exception as e: - print('caught') + print("caught") print_exc(e) # Here we have a function with lots of bytecode generated for a single source-line, and # there is an error right at the end of the bytecode. It should report the correct line. def f(): - f([1, 2], [1, 2], [1, 2], {1:1, 1:1, 1:1, 1:1, 1:1, 1:1, 1:X}) + f([1, 2], [1, 2], [1, 2], {1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: 1, 1: X}) return 1 + + try: f() except Exception as e: print_exc(e) # Test non-stream object passed as output object, only valid for uPy -if hasattr(sys, 'print_exception'): +if hasattr(sys, "print_exception"): try: sys.print_exception(Exception, 1) had_exception = False diff --git a/tests/misc/rge_sm.py b/tests/misc/rge_sm.py index 5bbf9d48b5..f3bb4189f7 100644 --- a/tests/misc/rge_sm.py +++ b/tests/misc/rge_sm.py @@ -3,30 +3,31 @@ import math + class RungeKutta(object): def __init__(self, functions, initConditions, t0, dh, save=True): - self.Trajectory, self.save = [[t0] + initConditions], save - self.functions = [lambda *args: 1.0] + list(functions) - self.N, self.dh = len(self.functions), dh - self.coeff = [1.0/6.0, 2.0/6.0, 2.0/6.0, 1.0/6.0] - self.InArgCoeff = [0.0, 0.5, 0.5, 1.0] + self.Trajectory, self.save = [[t0] + initConditions], save + self.functions = [lambda *args: 1.0] + list(functions) + self.N, self.dh = len(self.functions), dh + self.coeff = [1.0 / 6.0, 2.0 / 6.0, 2.0 / 6.0, 1.0 / 6.0] + self.InArgCoeff = [0.0, 0.5, 0.5, 1.0] def iterate(self): - step = self.Trajectory[-1][:] - istep, iac = step[:], self.InArgCoeff + step = self.Trajectory[-1][:] + istep, iac = step[:], self.InArgCoeff k, ktmp = self.N * [0.0], self.N * [0.0] for ic, c in enumerate(self.coeff): for if_, f in enumerate(self.functions): - arguments = [ (x + k[i]*iac[ic]) for i, x in enumerate(istep)] + arguments = [(x + k[i] * iac[ic]) for i, x in enumerate(istep)] try: feval = f(*arguments) except OverflowError: return False - if abs(feval) > 1e2: # stop integrating + if abs(feval) > 1e2: # stop integrating return False - ktmp[if_] = self.dh * feval + ktmp[if_] = self.dh * feval k = ktmp[:] - step = [s + c*k[ik] for ik,s in enumerate(step)] + step = [s + c * k[ik] for ik, s in enumerate(step)] if self.save: self.Trajectory += [step] else: @@ -46,23 +47,45 @@ class RungeKutta(object): def series(self): return zip(*self.Trajectory) + # 1-loop RGES for the main parameters of the SM # couplings are: g1, g2, g3 of U(1), SU(2), SU(3); yt (top Yukawa), lambda (Higgs quartic) # see arxiv.org/abs/0812.4950, eqs 10-15 sysSM = ( - lambda *a: 41.0 / 96.0 / math.pi**2 * a[1]**3, # g1 - lambda *a: -19.0 / 96.0 / math.pi**2 * a[2]**3, # g2 - lambda *a: -42.0 / 96.0 / math.pi**2 * a[3]**3, # g3 - lambda *a: 1.0 / 16.0 / math.pi**2 * (9.0 / 2.0 * a[4]**3 - 8.0 * a[3]**2 * a[4] - 9.0 / 4.0 * a[2]**2 * a[4] - 17.0 / 12.0 * a[1]**2 * a[4]), # yt - lambda *a: 1.0 / 16.0 / math.pi**2 * (24.0 * a[5]**2 + 12.0 * a[4]**2 * a[5] - 9.0 * a[5] * (a[2]**2 + 1.0 / 3.0 * a[1]**2) - 6.0 * a[4]**4 + 9.0 / 8.0 * a[2]**4 + 3.0 / 8.0 * a[1]**4 + 3.0 / 4.0 * a[2]**2 * a[1]**2), # lambda + lambda *a: 41.0 / 96.0 / math.pi ** 2 * a[1] ** 3, # g1 + lambda *a: -19.0 / 96.0 / math.pi ** 2 * a[2] ** 3, # g2 + lambda *a: -42.0 / 96.0 / math.pi ** 2 * a[3] ** 3, # g3 + lambda *a: 1.0 + / 16.0 + / math.pi ** 2 + * ( + 9.0 / 2.0 * a[4] ** 3 + - 8.0 * a[3] ** 2 * a[4] + - 9.0 / 4.0 * a[2] ** 2 * a[4] + - 17.0 / 12.0 * a[1] ** 2 * a[4] + ), # yt + lambda *a: 1.0 + / 16.0 + / math.pi ** 2 + * ( + 24.0 * a[5] ** 2 + + 12.0 * a[4] ** 2 * a[5] + - 9.0 * a[5] * (a[2] ** 2 + 1.0 / 3.0 * a[1] ** 2) + - 6.0 * a[4] ** 4 + + 9.0 / 8.0 * a[2] ** 4 + + 3.0 / 8.0 * a[1] ** 4 + + 3.0 / 4.0 * a[2] ** 2 * a[1] ** 2 + ), # lambda ) + def drange(start, stop, step): r = start while r < stop: yield r r += step + def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): tstart = 0.0 for i in drange(0, range, 0.1 * range): @@ -82,10 +105,10 @@ def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): p2 = rk.Trajectory[2 * l] x1, y1 = trajPlot(p1) x2, y2 = trajPlot(p2) - dx = -0.5 * (y2 - y1) # orthogonal to line + dx = -0.5 * (y2 - y1) # orthogonal to line dy = 0.5 * (x2 - x1) # orthogonal to line - #l = math.sqrt(dx*dx + dy*dy) - #if abs(l) > 1e-3: + # l = math.sqrt(dx*dx + dy*dy) + # if abs(l) > 1e-3: # l = 0.1 / l # dx *= l # dy *= l @@ -94,6 +117,7 @@ def phaseDiagram(system, trajStart, trajPlot, h=0.1, tend=1.0, range=1.0): print(x1 - dx, y1 - dy) print() + def singleTraj(system, trajStart, h=0.02, tend=1.0): tstart = 0.0 @@ -106,9 +130,12 @@ def singleTraj(system, trajStart, h=0.02, tend=1.0): for i in range(len(rk.Trajectory)): tr = rk.Trajectory[i] - print(' '.join(["{:.4f}".format(t) for t in tr])) + print(" ".join(["{:.4f}".format(t) for t in tr])) -#phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17)) + +# phaseDiagram(sysSM, (lambda i, j: [0.354, 0.654, 1.278, 0.8 + 0.2 * i, 0.1 + 0.1 * j]), (lambda a: (a[4], a[5])), h=0.1, tend=math.log(10**17)) # initial conditions at M_Z -singleTraj(sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10**17)) # true values +singleTraj( + sysSM, [0.354, 0.654, 1.278, 0.983, 0.131], h=0.5, tend=math.log(10 ** 17) +) # true values diff --git a/tests/misc/sys_exc_info.py b/tests/misc/sys_exc_info.py index bf9438e462..d7e8a2d943 100644 --- a/tests/misc/sys_exc_info.py +++ b/tests/misc/sys_exc_info.py @@ -1,15 +1,18 @@ import sys + try: sys.exc_info except: print("SKIP") raise SystemExit + def f(): print(sys.exc_info()[0:2]) + try: - raise ValueError('value', 123) + raise ValueError("value", 123) except: print(sys.exc_info()[0:2]) f() diff --git a/tests/net_hosted/accept_nonblock.py b/tests/net_hosted/accept_nonblock.py index 56f3288e28..941965e178 100644 --- a/tests/net_hosted/accept_nonblock.py +++ b/tests/net_hosted/accept_nonblock.py @@ -6,11 +6,11 @@ except: import socket s = socket.socket() -s.bind(socket.getaddrinfo('127.0.0.1', 8123)[0][-1]) +s.bind(socket.getaddrinfo("127.0.0.1", 8123)[0][-1]) s.setblocking(False) s.listen(1) try: s.accept() except OSError as er: - print(er.args[0] == 11) # 11 is EAGAIN + print(er.args[0] == 11) # 11 is EAGAIN s.close() diff --git a/tests/net_hosted/accept_timeout.py b/tests/net_hosted/accept_timeout.py index 44b3b8c7cd..ff989110ae 100644 --- a/tests/net_hosted/accept_timeout.py +++ b/tests/net_hosted/accept_timeout.py @@ -8,15 +8,15 @@ except: try: socket.socket.settimeout except AttributeError: - print('SKIP') + print("SKIP") raise SystemExit s = socket.socket() -s.bind(socket.getaddrinfo('127.0.0.1', 8123)[0][-1]) +s.bind(socket.getaddrinfo("127.0.0.1", 8123)[0][-1]) s.settimeout(1) s.listen(1) try: s.accept() except OSError as er: - print(er.args[0] in (110, 'timed out')) # 110 is ETIMEDOUT; CPython uses a string + print(er.args[0] in (110, "timed out")) # 110 is ETIMEDOUT; CPython uses a string s.close() diff --git a/tests/net_hosted/connect_nonblock.py b/tests/net_hosted/connect_nonblock.py index 6479978bea..3a3eaa2ba0 100644 --- a/tests/net_hosted/connect_nonblock.py +++ b/tests/net_hosted/connect_nonblock.py @@ -12,9 +12,9 @@ def test(peer_addr): try: s.connect(peer_addr) except OSError as er: - print(er.args[0] == 115) # 115 is EINPROGRESS + print(er.args[0] == 115) # 115 is EINPROGRESS s.close() if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 80)[0][-1]) + test(socket.getaddrinfo("micropython.org", 80)[0][-1]) diff --git a/tests/net_hosted/connect_poll.py b/tests/net_hosted/connect_poll.py index ece6aa0da9..90f9b7138e 100644 --- a/tests/net_hosted/connect_poll.py +++ b/tests/net_hosted/connect_poll.py @@ -29,4 +29,4 @@ def test(peer_addr): if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 80)[0][-1]) + test(socket.getaddrinfo("micropython.org", 80)[0][-1]) diff --git a/tests/net_hosted/ssl_getpeercert.py b/tests/net_hosted/ssl_getpeercert.py index e265c830d0..dee5fcfd89 100644 --- a/tests/net_hosted/ssl_getpeercert.py +++ b/tests/net_hosted/ssl_getpeercert.py @@ -18,4 +18,4 @@ def test(peer_addr): if __name__ == "__main__": - test(socket.getaddrinfo('micropython.org', 443)[0][-1]) + test(socket.getaddrinfo("micropython.org", 443)[0][-1]) diff --git a/tests/net_inet/test_tls_sites.py b/tests/net_inet/test_tls_sites.py index bf8071d087..7fdafab99a 100644 --- a/tests/net_inet/test_tls_sites.py +++ b/tests/net_inet/test_tls_sites.py @@ -6,6 +6,7 @@ try: import ussl as ssl except: import ssl + # CPython only supports server_hostname with SSLContext ssl = ssl.SSLContext() @@ -24,9 +25,9 @@ def test_one(site, opts): else: s = ssl.wrap_socket(s) - s.write(b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, 'latin')) + s.write(b"GET / HTTP/1.0\r\nHost: %s\r\n\r\n" % bytes(site, "latin")) resp = s.read(4096) -# print(resp) + # print(resp) finally: s.close() @@ -37,7 +38,7 @@ SITES = [ "www.google.com", "api.telegram.org", {"host": "api.pushbullet.com", "sni": True}, -# "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", + # "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", {"host": "w9rybpfril.execute-api.ap-southeast-2.amazonaws.com", "sni": True}, ] diff --git a/tests/pyb/adc.py b/tests/pyb/adc.py index 0bd9b9d53a..fff5a3019e 100644 --- a/tests/pyb/adc.py +++ b/tests/pyb/adc.py @@ -1,8 +1,8 @@ from pyb import ADC, Timer -adct = ADC(16) # Temperature 930 -> 20C +adct = ADC(16) # Temperature 930 -> 20C print(adct) -adcv = ADC(17) # Voltage 1500 -> 3.3V +adcv = ADC(17) # Voltage 1500 -> 3.3V print(adcv) # read single sample; 2.5V-5V is pass range @@ -13,7 +13,7 @@ assert val > 1000 and val < 2000 tim = Timer(5, freq=500) # read into bytearray -buf = bytearray(b'\xff' * 50) +buf = bytearray(b"\xff" * 50) adcv.read_timed(buf, tim) print(len(buf)) for i in buf: @@ -21,21 +21,22 @@ for i in buf: # read into arrays with different element sizes import array -arv = array.array('h', 25 * [0x7fff]) + +arv = array.array("h", 25 * [0x7FFF]) adcv.read_timed(arv, tim) print(len(arv)) for i in arv: assert i > 1000 and i < 2000 -arv = array.array('i', 30 * [-1]) +arv = array.array("i", 30 * [-1]) adcv.read_timed(arv, tim) print(len(arv)) for i in arv: assert i > 1000 and i < 2000 # Test read_timed_multi -arv = bytearray(b'\xff'*50) -art = bytearray(b'\xff'*50) +arv = bytearray(b"\xff" * 50) +art = bytearray(b"\xff" * 50) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 60 and i < 125 @@ -43,8 +44,8 @@ for i in arv: for i in art: assert i > 15 and i < 200 -arv = array.array('i', 25 * [-1]) -art = array.array('i', 25 * [-1]) +arv = array.array("i", 25 * [-1]) +art = array.array("i", 25 * [-1]) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 1000 and i < 2000 @@ -52,8 +53,8 @@ for i in arv: for i in art: assert i > 50 and i < 2000 -arv = array.array('h', 25 * [0x7fff]) -art = array.array('h', 25 * [0x7fff]) +arv = array.array("h", 25 * [0x7FFF]) +art = array.array("h", 25 * [0x7FFF]) ADC.read_timed_multi((adcv, adct), (arv, art), tim) for i in arv: assert i > 1000 and i < 2000 diff --git a/tests/pyb/can.py b/tests/pyb/can.py index 8a08ea9a65..7d27318d86 100644 --- a/tests/pyb/can.py +++ b/tests/pyb/can.py @@ -1,7 +1,7 @@ try: from pyb import CAN except ImportError: - print('SKIP') + print("SKIP") raise SystemExit from array import array @@ -40,23 +40,23 @@ print(can.info()) # Catch all filter can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) -can.send('abcd', 123, timeout=5000) +can.send("abcd", 123, timeout=5000) print(can.any(0), can.info()) print(can.recv(0)) -can.send('abcd', -1, timeout=5000) +can.send("abcd", -1, timeout=5000) print(can.recv(0)) -can.send('abcd', 0x7FF + 1, timeout=5000) +can.send("abcd", 0x7FF + 1, timeout=5000) print(can.recv(0)) # Test too long message try: - can.send('abcdefghi', 0x7FF, timeout=5000) + can.send("abcdefghi", 0x7FF, timeout=5000) except ValueError: - print('passed') + print("passed") else: - print('failed') + print("failed") # Test that recv can work without allocating memory on the heap @@ -66,22 +66,22 @@ l2 = None micropython.heap_lock() -can.send('', 42) +can.send("", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('1234', 42) +can.send("1234", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('01234567', 42) +can.send("01234567", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) -can.send('abc', 42) +can.send("abc", 42) l2 = can.recv(0, l) assert l is l2 print(l, len(l[3]), buf) @@ -89,65 +89,65 @@ print(l, len(l[3]), buf) micropython.heap_unlock() # Test that recv can work with different arrays behind the memoryview -can.send('abc', 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array('B', range(8)))])[3])) -can.send('def', 1) -print(bytes(can.recv(0, [0, 0, 0, memoryview(array('b', range(8)))])[3])) +can.send("abc", 1) +print(bytes(can.recv(0, [0, 0, 0, memoryview(array("B", range(8)))])[3])) +can.send("def", 1) +print(bytes(can.recv(0, [0, 0, 0, memoryview(array("b", range(8)))])[3])) # Test for non-list passed as second arg to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, 1) except TypeError: - print('TypeError') + print("TypeError") # Test for too-short-list passed as second arg to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0]) except ValueError: - print('ValueError') + print("ValueError") # Test for non-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0, 0]) except TypeError: - print('TypeError') + print("TypeError") # Test for read-only-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: can.recv(0, [0, 0, 0, memoryview(bytes(8))]) except ValueError: - print('ValueError') + print("ValueError") # Test for bad-typecode-memoryview passed as 4th element to recv -can.send('abc', 1) +can.send("abc", 1) try: - can.recv(0, [0, 0, 0, memoryview(array('i', range(8)))]) + can.recv(0, [0, 0, 0, memoryview(array("i", range(8)))]) except ValueError: - print('ValueError') + print("ValueError") del can # Testing extended IDs -can = CAN(1, CAN.LOOPBACK, extframe = True) +can = CAN(1, CAN.LOOPBACK, extframe=True) # Catch all filter can.setfilter(0, CAN.MASK32, 0, (0, 0)) print(can) try: - can.send('abcde', 0x7FF + 1, timeout=5000) + can.send("abcde", 0x7FF + 1, timeout=5000) except ValueError: - print('failed') + print("failed") else: r = can.recv(0) - if r[0] == 0x7FF+1 and r[3] == b'abcde': - print('passed') + if r[0] == 0x7FF + 1 and r[3] == b"abcde": + print("passed") else: - print('failed, wrong data received') + print("failed, wrong data received") # Test filters for n in [0, 8, 16, 24]: @@ -159,7 +159,7 @@ for n in [0, 8, 16, 24]: can.clearfilter(0) can.setfilter(0, pyb.CAN.MASK32, 0, (filter_id, filter_mask)) - can.send('ok', id_ok, timeout=3) + can.send("ok", id_ok, timeout=3) if can.any(0): msg = can.recv(0) print((hex(filter_id), hex(filter_mask), hex(msg[0]), msg[3])) @@ -175,57 +175,62 @@ del can can = CAN(1, CAN.LOOPBACK) can.setfilter(0, CAN.LIST16, 0, (1, 2, 3, 4)) can.setfilter(1, CAN.LIST16, 1, (5, 6, 7, 8)) + + def cb0(bus, reason): - print('cb0') + print("cb0") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb1(bus, reason): - print('cb1') + print("cb1") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb0a(bus, reason): - print('cb0a') + print("cb0a") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") + def cb1a(bus, reason): - print('cb1a') + print("cb1a") if reason == 0: - print('pending') + print("pending") if reason == 1: - print('full') + print("full") if reason == 2: - print('overflow') + print("overflow") can.rxcallback(0, cb0) can.rxcallback(1, cb1) -can.send('11111111',1, timeout=5000) -can.send('22222222',2, timeout=5000) -can.send('33333333',3, timeout=5000) +can.send("11111111", 1, timeout=5000) +can.send("22222222", 2, timeout=5000) +can.send("33333333", 3, timeout=5000) can.rxcallback(0, cb0a) -can.send('44444444',4, timeout=5000) +can.send("44444444", 4, timeout=5000) -can.send('55555555',5, timeout=5000) -can.send('66666666',6, timeout=5000) -can.send('77777777',7, timeout=5000) +can.send("55555555", 5, timeout=5000) +can.send("66666666", 6, timeout=5000) +can.send("77777777", 7, timeout=5000) can.rxcallback(1, cb1a) -can.send('88888888',8, timeout=5000) +can.send("88888888", 8, timeout=5000) print(can.recv(0)) print(can.recv(0)) @@ -234,8 +239,8 @@ print(can.recv(1)) print(can.recv(1)) print(can.recv(1)) -can.send('11111111',1, timeout=5000) -can.send('55555555',5, timeout=5000) +can.send("11111111", 1, timeout=5000) +can.send("55555555", 5, timeout=5000) print(can.recv(0)) print(can.recv(1)) @@ -249,7 +254,7 @@ can.setfilter(0, CAN.MASK16, 0, (0, 0, 0, 0)) while can.any(0): can.recv(0) -can.send('abcde', 1, timeout=0) +can.send("abcde", 1, timeout=0) print(can.any(0)) while not can.any(0): pass @@ -257,15 +262,15 @@ while not can.any(0): print(can.recv(0)) try: - can.send('abcde', 2, timeout=0) - can.send('abcde', 3, timeout=0) - can.send('abcde', 4, timeout=0) - can.send('abcde', 5, timeout=0) + can.send("abcde", 2, timeout=0) + can.send("abcde", 3, timeout=0) + can.send("abcde", 4, timeout=0) + can.send("abcde", 5, timeout=0) except OSError as e: - if str(e) == '16': - print('passed') + if str(e) == "16": + print("passed") else: - print('failed') + print("failed") pyb.delay(500) while can.any(0): @@ -273,7 +278,7 @@ while can.any(0): # Testing rtr messages bus1 = CAN(1, CAN.LOOPBACK) -bus2 = CAN(2, CAN.LOOPBACK, extframe = True) +bus2 = CAN(2, CAN.LOOPBACK, extframe=True) while bus1.any(0): bus1.recv(0) while bus2.any(0): @@ -286,24 +291,24 @@ bus2.setfilter(1, CAN.LIST32, 0, (3, 4), rtr=(True, False)) bus2.setfilter(2, CAN.MASK32, 0, (16, 16), rtr=(False,)) bus2.setfilter(2, CAN.MASK32, 0, (32, 32), rtr=(True,)) -bus1.send('',1,rtr=True) +bus1.send("", 1, rtr=True) print(bus1.any(0)) -bus1.send('',5,rtr=True) +bus1.send("", 5, rtr=True) print(bus1.recv(0)) -bus1.send('',6,rtr=True) +bus1.send("", 6, rtr=True) print(bus1.recv(0)) -bus1.send('',7,rtr=True) +bus1.send("", 7, rtr=True) print(bus1.recv(0)) -bus1.send('',16,rtr=True) +bus1.send("", 16, rtr=True) print(bus1.any(0)) -bus1.send('',32,rtr=True) +bus1.send("", 32, rtr=True) print(bus1.recv(0)) -bus2.send('',1,rtr=True) +bus2.send("", 1, rtr=True) print(bus2.recv(0)) -bus2.send('',2,rtr=True) +bus2.send("", 2, rtr=True) print(bus2.recv(0)) -bus2.send('',3,rtr=True) +bus2.send("", 3, rtr=True) print(bus2.recv(0)) -bus2.send('',4,rtr=True) +bus2.send("", 4, rtr=True) print(bus2.any(0)) diff --git a/tests/pyb/dac.py b/tests/pyb/dac.py index ca68ec7098..506cf272b3 100644 --- a/tests/pyb/dac.py +++ b/tests/pyb/dac.py @@ -1,7 +1,7 @@ import pyb -if not hasattr(pyb, 'DAC'): - print('SKIP') +if not hasattr(pyb, "DAC"): + print("SKIP") raise SystemExit dac = pyb.DAC(1) diff --git a/tests/pyb/extint.py b/tests/pyb/extint.py index ae98ccd5a0..927b2bceba 100644 --- a/tests/pyb/extint.py +++ b/tests/pyb/extint.py @@ -1,7 +1,7 @@ import pyb # test basic functionality -ext = pyb.ExtInt('Y1', pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l:print('line:', l)) +ext = pyb.ExtInt("Y1", pyb.ExtInt.IRQ_RISING, pyb.Pin.PULL_DOWN, lambda l: print("line:", l)) ext.disable() ext.enable() print(ext.line()) diff --git a/tests/pyb/irq.py b/tests/pyb/irq.py index 42d276568e..04e70a7b79 100644 --- a/tests/pyb/irq.py +++ b/tests/pyb/irq.py @@ -1,10 +1,11 @@ import pyb + def test_irq(): # test basic disable/enable i1 = pyb.disable_irq() print(i1) - pyb.enable_irq() # by default should enable IRQ + pyb.enable_irq() # by default should enable IRQ # check that interrupts are enabled by waiting for ticks pyb.delay(10) @@ -19,4 +20,5 @@ def test_irq(): # check that interrupts are enabled by waiting for ticks pyb.delay(10) + test_irq() diff --git a/tests/pyb/modtime.py b/tests/pyb/modtime.py index d45440a63c..1f5b5f32fe 100644 --- a/tests/pyb/modtime.py +++ b/tests/pyb/modtime.py @@ -2,12 +2,14 @@ import time DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + def is_leap(year): return (year % 4) == 0 + def test(): seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday + wday = 5 # Jan 1, 2000 was a Saturday for year in range(2000, 2034): print("Testing %d" % year) yday = 1 @@ -19,41 +21,56 @@ def test(): for day in range(1, DAYS_PER_MONTH[month] + 1): secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) if secs != seconds: - print("mktime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "mktime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) tuple = time.localtime(seconds) secs = time.mktime(tuple) if secs != seconds: - print("localtime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "localtime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) return seconds += 86400 if yday != tuple[7]: - print("locatime for %d-%02d-%02d got yday %d, expecting %d" % (year, month, day, tuple[7], yday)) + print( + "locatime for %d-%02d-%02d got yday %d, expecting %d" + % (year, month, day, tuple[7], yday) + ) return if wday != tuple[6]: - print("locatime for %d-%02d-%02d got wday %d, expecting %d" % (year, month, day, tuple[6], wday)) + print( + "locatime for %d-%02d-%02d got wday %d, expecting %d" + % (year, month, day, tuple[6], wday) + ) return yday += 1 wday = (wday + 1) % 7 + def spot_test(seconds, expected_time): actual_time = time.localtime(seconds) for i in range(len(actual_time)): if actual_time[i] != expected_time[i]: - print("time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time) + print( + "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time + ) return print("time.localtime(", seconds, ") returned", actual_time, "(pass)") test() -spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1)) -spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1)) -spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1)) -spot_test( 60, (2000, 1, 1, 0, 1, 0, 5, 1)) -spot_test( 3599, (2000, 1, 1, 0, 59, 59, 5, 1)) -spot_test( 3600, (2000, 1, 1, 1, 0, 0, 5, 1)) -spot_test( -1, (1999, 12, 31, 23, 59, 59, 4, 365)) -spot_test( 447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) -spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) -spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) -spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) -spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) +spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1)) +spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1)) +spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1)) +spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1)) +spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1)) +spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1)) +spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365)) +spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) +spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) +spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) +spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) +spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) diff --git a/tests/pyb/pin.py b/tests/pyb/pin.py index 9b37883438..c5a4443321 100644 --- a/tests/pyb/pin.py +++ b/tests/pyb/pin.py @@ -1,14 +1,14 @@ from pyb import Pin -p = Pin('Y1', Pin.IN) +p = Pin("Y1", Pin.IN) print(p) print(p.name()) print(p.pin()) print(p.port()) -p = Pin('Y1', Pin.IN, Pin.PULL_UP) -p = Pin('Y1', Pin.IN, pull=Pin.PULL_UP) -p = Pin('Y1', mode=Pin.IN, pull=Pin.PULL_UP) +p = Pin("Y1", Pin.IN, Pin.PULL_UP) +p = Pin("Y1", Pin.IN, pull=Pin.PULL_UP) +p = Pin("Y1", mode=Pin.IN, pull=Pin.PULL_UP) print(p) print(p.value()) diff --git a/tests/pyb/pyb1.py b/tests/pyb/pyb1.py index 443722ca85..e9626ecf4e 100644 --- a/tests/pyb/pyb1.py +++ b/tests/pyb/pyb1.py @@ -10,7 +10,7 @@ pyb.delay(1) start = pyb.millis() pyb.delay(17) -print((pyb.millis() - start) // 5) # should print 3 +print((pyb.millis() - start) // 5) # should print 3 # test udelay @@ -20,7 +20,7 @@ pyb.udelay(1) start = pyb.millis() pyb.udelay(17000) -print((pyb.millis() - start) // 5) # should print 3 +print((pyb.millis() - start) // 5) # should print 3 # other diff --git a/tests/pyb/pyb_f405.py b/tests/pyb/pyb_f405.py index 2f161ae099..6ca943dcea 100644 --- a/tests/pyb/pyb_f405.py +++ b/tests/pyb/pyb_f405.py @@ -2,8 +2,8 @@ import os, pyb -if not 'STM32F405' in os.uname().machine: - print('SKIP') +if not "STM32F405" in os.uname().machine: + print("SKIP") raise SystemExit print(pyb.freq()) diff --git a/tests/pyb/pyb_f411.py b/tests/pyb/pyb_f411.py index 50de302823..58d5fa2d41 100644 --- a/tests/pyb/pyb_f411.py +++ b/tests/pyb/pyb_f411.py @@ -2,8 +2,8 @@ import os, pyb -if not 'STM32F411' in os.uname().machine: - print('SKIP') +if not "STM32F411" in os.uname().machine: + print("SKIP") raise SystemExit print(pyb.freq()) diff --git a/tests/pyb/rtc.py b/tests/pyb/rtc.py index 844526b4b9..41b52f260d 100644 --- a/tests/pyb/rtc.py +++ b/tests/pyb/rtc.py @@ -10,10 +10,12 @@ rtc.datetime((2014, 1, 1, 1, 0, 0, 0, 0)) pyb.delay(1002) print(rtc.datetime()[:7]) + def set_and_print(datetime): rtc.datetime(datetime) print(rtc.datetime()[:7]) + # make sure that setting works correctly set_and_print((2000, 1, 1, 1, 0, 0, 0, 0)) set_and_print((2000, 1, 31, 1, 0, 0, 0, 0)) @@ -34,10 +36,12 @@ set_and_print((2099, 12, 31, 7, 23, 59, 59, 0)) # save existing calibration value: cal_tmp = rtc.calibration() + def set_and_print_calib(cal): rtc.calibration(cal) print(rtc.calibration()) + set_and_print_calib(512) set_and_print_calib(511) set_and_print_calib(345) @@ -56,12 +60,13 @@ def set_and_print_wakeup(ms): try: rtc.wakeup(ms) wucksel = stm.mem32[stm.RTC + stm.RTC_CR] & 7 - wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xffff + wut = stm.mem32[stm.RTC + stm.RTC_WUTR] & 0xFFFF except ValueError: wucksel = -1 wut = -1 print((wucksel, wut)) + set_and_print_wakeup(0) set_and_print_wakeup(1) set_and_print_wakeup(4000) @@ -72,8 +77,8 @@ set_and_print_wakeup(16000) set_and_print_wakeup(16001) set_and_print_wakeup(32000) set_and_print_wakeup(32001) -set_and_print_wakeup(0x10000*1000) -set_and_print_wakeup(0x10001*1000) -set_and_print_wakeup(0x1ffff*1000) -set_and_print_wakeup(0x20000*1000) -set_and_print_wakeup(0x20001*1000) # exception +set_and_print_wakeup(0x10000 * 1000) +set_and_print_wakeup(0x10001 * 1000) +set_and_print_wakeup(0x1FFFF * 1000) +set_and_print_wakeup(0x20000 * 1000) +set_and_print_wakeup(0x20001 * 1000) # exception diff --git a/tests/pyb/timer_callback.py b/tests/pyb/timer_callback.py index 864dd479ed..51242fba4b 100644 --- a/tests/pyb/timer_callback.py +++ b/tests/pyb/timer_callback.py @@ -8,19 +8,24 @@ def cb1(t): print("cb1") t.callback(None) + # callback function that disables the timer when called def cb2(t): print("cb2") t.deinit() + # callback where cb4 closes over cb3.y def cb3(x): y = x + def cb4(t): print("cb4", y) t.callback(None) + return cb4 + # create a timer with a callback, using callback(None) to stop tim = Timer(1, freq=100, callback=cb1) pyb.delay(5) diff --git a/tests/pyb/uart.py b/tests/pyb/uart.py index 838dd9cfc6..afa7b8b340 100644 --- a/tests/pyb/uart.py +++ b/tests/pyb/uart.py @@ -17,8 +17,8 @@ uart.init(2400) print(uart) print(uart.any()) -print(uart.write('123')) -print(uart.write(b'abcd')) +print(uart.write("123")) +print(uart.write(b"abcd")) print(uart.writechar(1)) # make sure this method exists @@ -26,7 +26,7 @@ uart.sendbreak() # non-blocking mode uart = UART(1, 9600, timeout=0) -print(uart.write(b'1')) -print(uart.write(b'abcd')) +print(uart.write(b"1")) +print(uart.write(b"abcd")) print(uart.writechar(1)) print(uart.read(100)) diff --git a/tests/pybnative/for.py b/tests/pybnative/for.py index 309c6c14fd..50177a9ba4 100644 --- a/tests/pybnative/for.py +++ b/tests/pybnative/for.py @@ -1,15 +1,19 @@ import pyb + @micropython.native def f1(n): for i in range(n): print(i) + f1(4) + @micropython.native def f2(r): for i in r: print(i) + f2(range(4)) diff --git a/tests/pybnative/while.py b/tests/pybnative/while.py index 3ea7221ea7..0f397dd377 100644 --- a/tests/pybnative/while.py +++ b/tests/pybnative/while.py @@ -1,5 +1,6 @@ import pyb + @micropython.native def f(led, n, d): led.off() @@ -11,5 +12,6 @@ def f(led, n, d): i += 1 led.off() + f(pyb.LED(1), 2, 150) f(pyb.LED(2), 4, 50) diff --git a/tests/run-tests-exp.py b/tests/run-tests-exp.py index 3af8feae7c..34c6f650f8 100644 --- a/tests/run-tests-exp.py +++ b/tests/run-tests-exp.py @@ -9,12 +9,9 @@ import sys import uos as os -tests = [ - "basics", "micropython", "float", "import", "io", - " misc", "unicode", "extmod", "unix" -] +tests = ["basics", "micropython", "float", "import", "io", " misc", "unicode", "extmod", "unix"] -if sys.platform == 'win32': +if sys.platform == "win32": MICROPYTHON = "micropython.exe" else: MICROPYTHON = "micropython" @@ -26,13 +23,14 @@ def should_skip(test): if test.startswith("viper"): return True + test_count = 0 passed_count = 0 skip_count = 0 for suite in tests: - #print("Running in: %s" % suite) - if sys.platform == 'win32': + # print("Running in: %s" % suite) + if sys.platform == "win32": # dir /b prints only contained filenames, one on a line # http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/dir.mspx r = os.system("dir /b %s/*.py >tests.lst" % suite) @@ -44,7 +42,7 @@ for suite in tests: testcases = f.readlines() testcases = [l[:-1] for l in testcases] assert testcases, "No tests found in dir '%s', which is implausible" % suite - #print(testcases) + # print(testcases) for t in testcases: if t == "native_check.py": continue @@ -65,7 +63,7 @@ for suite in tests: pass if exp is not None: - #print("run " + qtest) + # print("run " + qtest) r = os.system(MICROPYTHON + " %s >.tst.out" % qtest) if r == 0: f = open(".tst.out") diff --git a/tests/skip_if.py b/tests/skip_if.py index a8f50c4656..1ca1794ede 100644 --- a/tests/skip_if.py +++ b/tests/skip_if.py @@ -6,18 +6,23 @@ # This must be on one line so its skipped when built into tests. """This file provides helpers to detect particular running conditions and skip the test when appropriate.""" + def skip(): print("SKIP") raise SystemExit + def always(): skip() + def no_reversed(): import builtins + if "reversed" not in dir(builtins): skip() + def no_bigint(): try: # We have to use variables because 1 << 40 causes an exception on parse and @@ -27,28 +32,35 @@ def no_bigint(): except OverflowError: skip() + def board_in(*board): try: import test_env except ImportError: + class Env: def __init__(self, board): self.board = board + test_env = Env("unknown") if test_env.board in board: skip() + def board_not_in(*board): try: import test_env except ImportError: + class Env: def __init__(self, board): self.board = board + test_env = Env("unknown") if test_env.board not in board: skip() + def no_cpython_compat(): try: from collections import namedtuple @@ -59,13 +71,14 @@ def no_cpython_compat(): except TypeError: skip() + def no_slice_assign(): try: memoryview except: skip() - b1 = bytearray(b'1234') - b2 = bytearray(b'5678') + b1 = bytearray(b"1234") + b2 = bytearray(b"5678") m1 = memoryview(b1) m2 = memoryview(b2) try: @@ -78,6 +91,7 @@ def no_reverse_ops(): class Foo: def __radd__(self, other): pass + try: 5 + Foo() except TypeError: diff --git a/tests/stress/dict_copy.py b/tests/stress/dict_copy.py index 36db9bb7e8..73d3a5b51d 100644 --- a/tests/stress/dict_copy.py +++ b/tests/stress/dict_copy.py @@ -1,6 +1,6 @@ # copying a large dictionary -a = {i:2*i for i in range(1000)} +a = {i: 2 * i for i in range(1000)} b = a.copy() for i in range(1000): print(i, b[i]) diff --git a/tests/stress/gc_trace.py b/tests/stress/gc_trace.py index 72dc7b6276..f952ad36a6 100644 --- a/tests/stress/gc_trace.py +++ b/tests/stress/gc_trace.py @@ -12,6 +12,8 @@ gc.collect() print(lst) # test a deep object -lst = [[[[[(i, j, k, l)] for i in range(3)] for j in range(3)] for k in range(3)] for l in range(3)] +lst = [ + [[[[(i, j, k, l)] for i in range(3)] for j in range(3)] for k in range(3)] for l in range(3) +] gc.collect() print(lst) diff --git a/tests/stress/recursion.py b/tests/stress/recursion.py index 227f48396a..c2d831bb82 100644 --- a/tests/stress/recursion.py +++ b/tests/stress/recursion.py @@ -1,6 +1,7 @@ def foo(): foo() + try: foo() except RuntimeError: diff --git a/tests/stress/recursive_gen.py b/tests/stress/recursive_gen.py index 0e0d3914ee..8c21397658 100644 --- a/tests/stress/recursive_gen.py +++ b/tests/stress/recursive_gen.py @@ -3,16 +3,20 @@ # simple "yield from" recursion def gen(): yield from gen() + + try: list(gen()) except RuntimeError: - print('RuntimeError') + print("RuntimeError") # recursion via an iterator over a generator def gen2(): for x in gen2(): yield x + + try: next(gen2()) except RuntimeError: - print('RuntimeError') + print("RuntimeError") diff --git a/tests/thread/mutate_bytearray.py b/tests/thread/mutate_bytearray.py index 5015c3f9cf..9b52e0c016 100644 --- a/tests/thread/mutate_bytearray.py +++ b/tests/thread/mutate_bytearray.py @@ -25,10 +25,11 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 -n_repeat = 4 # use 40 for more stressful test (uses more heap) +n_repeat = 4 # use 40 for more stressful test (uses more heap) # spawn threads for i in range(n_thread): diff --git a/tests/thread/mutate_dict.py b/tests/thread/mutate_dict.py index 563fce39de..0840dcafba 100644 --- a/tests/thread/mutate_dict.py +++ b/tests/thread/mutate_dict.py @@ -7,7 +7,7 @@ import _thread # the shared dict -di = {'a':'A', 'b':'B', 'c':'C', 'd':'D'} +di = {"a": "A", "b": "B", "c": "C", "d": "D"} # main thread function def th(n, lo, hi): @@ -28,6 +28,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/mutate_instance.py b/tests/thread/mutate_instance.py index 2ecfbe1092..8ba91cbde3 100644 --- a/tests/thread/mutate_instance.py +++ b/tests/thread/mutate_instance.py @@ -9,25 +9,28 @@ import _thread # the shared user class and instance class User: def __init__(self): - self.a = 'A' - self.b = 'B' - self.c = 'C' + self.a = "A" + self.b = "B" + self.c = "C" + + user = User() # main thread function def th(n, lo, hi): for repeat in range(n): for i in range(lo, hi): - setattr(user, 'attr_%u' % i, repeat + i) - assert getattr(user, 'attr_%u' % i) == repeat + i + setattr(user, "attr_%u" % i, repeat + i) + assert getattr(user, "attr_%u" % i) == repeat + i with lock: global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_repeat = 30 -n_range = 50 # 300 for stressful test (uses more heap) +n_range = 50 # 300 for stressful test (uses more heap) n_thread = 4 n_finished = 0 @@ -42,4 +45,4 @@ while n_finished < n_thread: # check user instance has correct contents print(user.a, user.b, user.c) for i in range(n_thread * n_range): - assert getattr(user, 'attr_%u' % i) == n_repeat - 1 + i + assert getattr(user, "attr_%u" % i) == n_repeat - 1 + i diff --git a/tests/thread/mutate_list.py b/tests/thread/mutate_list.py index d70e8a8a38..8ce15c0852 100644 --- a/tests/thread/mutate_list.py +++ b/tests/thread/mutate_list.py @@ -29,6 +29,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/mutate_set.py b/tests/thread/mutate_set.py index c4529f3562..61169b8aa9 100644 --- a/tests/thread/mutate_set.py +++ b/tests/thread/mutate_set.py @@ -23,6 +23,7 @@ def th(n, lo, hi): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/stress_aes.py b/tests/thread/stress_aes.py index ebf7af371b..3191192a4d 100644 --- a/tests/thread/stress_aes.py +++ b/tests/thread/stress_aes.py @@ -19,49 +19,295 @@ # discrete arithmetic routines, mostly from a precomputed table # non-linear, invertible, substitution box -aes_s_box_table = bytes(( - 0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76, - 0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0, - 0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15, - 0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75, - 0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84, - 0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf, - 0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8, - 0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2, - 0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73, - 0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb, - 0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79, - 0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08, - 0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a, - 0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e, - 0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf, - 0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16, -)) +aes_s_box_table = bytes( + ( + 0x63, + 0x7C, + 0x77, + 0x7B, + 0xF2, + 0x6B, + 0x6F, + 0xC5, + 0x30, + 0x01, + 0x67, + 0x2B, + 0xFE, + 0xD7, + 0xAB, + 0x76, + 0xCA, + 0x82, + 0xC9, + 0x7D, + 0xFA, + 0x59, + 0x47, + 0xF0, + 0xAD, + 0xD4, + 0xA2, + 0xAF, + 0x9C, + 0xA4, + 0x72, + 0xC0, + 0xB7, + 0xFD, + 0x93, + 0x26, + 0x36, + 0x3F, + 0xF7, + 0xCC, + 0x34, + 0xA5, + 0xE5, + 0xF1, + 0x71, + 0xD8, + 0x31, + 0x15, + 0x04, + 0xC7, + 0x23, + 0xC3, + 0x18, + 0x96, + 0x05, + 0x9A, + 0x07, + 0x12, + 0x80, + 0xE2, + 0xEB, + 0x27, + 0xB2, + 0x75, + 0x09, + 0x83, + 0x2C, + 0x1A, + 0x1B, + 0x6E, + 0x5A, + 0xA0, + 0x52, + 0x3B, + 0xD6, + 0xB3, + 0x29, + 0xE3, + 0x2F, + 0x84, + 0x53, + 0xD1, + 0x00, + 0xED, + 0x20, + 0xFC, + 0xB1, + 0x5B, + 0x6A, + 0xCB, + 0xBE, + 0x39, + 0x4A, + 0x4C, + 0x58, + 0xCF, + 0xD0, + 0xEF, + 0xAA, + 0xFB, + 0x43, + 0x4D, + 0x33, + 0x85, + 0x45, + 0xF9, + 0x02, + 0x7F, + 0x50, + 0x3C, + 0x9F, + 0xA8, + 0x51, + 0xA3, + 0x40, + 0x8F, + 0x92, + 0x9D, + 0x38, + 0xF5, + 0xBC, + 0xB6, + 0xDA, + 0x21, + 0x10, + 0xFF, + 0xF3, + 0xD2, + 0xCD, + 0x0C, + 0x13, + 0xEC, + 0x5F, + 0x97, + 0x44, + 0x17, + 0xC4, + 0xA7, + 0x7E, + 0x3D, + 0x64, + 0x5D, + 0x19, + 0x73, + 0x60, + 0x81, + 0x4F, + 0xDC, + 0x22, + 0x2A, + 0x90, + 0x88, + 0x46, + 0xEE, + 0xB8, + 0x14, + 0xDE, + 0x5E, + 0x0B, + 0xDB, + 0xE0, + 0x32, + 0x3A, + 0x0A, + 0x49, + 0x06, + 0x24, + 0x5C, + 0xC2, + 0xD3, + 0xAC, + 0x62, + 0x91, + 0x95, + 0xE4, + 0x79, + 0xE7, + 0xC8, + 0x37, + 0x6D, + 0x8D, + 0xD5, + 0x4E, + 0xA9, + 0x6C, + 0x56, + 0xF4, + 0xEA, + 0x65, + 0x7A, + 0xAE, + 0x08, + 0xBA, + 0x78, + 0x25, + 0x2E, + 0x1C, + 0xA6, + 0xB4, + 0xC6, + 0xE8, + 0xDD, + 0x74, + 0x1F, + 0x4B, + 0xBD, + 0x8B, + 0x8A, + 0x70, + 0x3E, + 0xB5, + 0x66, + 0x48, + 0x03, + 0xF6, + 0x0E, + 0x61, + 0x35, + 0x57, + 0xB9, + 0x86, + 0xC1, + 0x1D, + 0x9E, + 0xE1, + 0xF8, + 0x98, + 0x11, + 0x69, + 0xD9, + 0x8E, + 0x94, + 0x9B, + 0x1E, + 0x87, + 0xE9, + 0xCE, + 0x55, + 0x28, + 0xDF, + 0x8C, + 0xA1, + 0x89, + 0x0D, + 0xBF, + 0xE6, + 0x42, + 0x68, + 0x41, + 0x99, + 0x2D, + 0x0F, + 0xB0, + 0x54, + 0xBB, + 0x16, + ) +) # multiplication of polynomials modulo x^8 + x^4 + x^3 + x + 1 = 0x11b def aes_gf8_mul_2(x): if x & 0x80: - return (x << 1) ^ 0x11b + return (x << 1) ^ 0x11B else: return x << 1 + def aes_gf8_mul_3(x): return x ^ aes_gf8_mul_2(x) + # non-linear, invertible, substitution box def aes_s_box(a): - return aes_s_box_table[a & 0xff] + return aes_s_box_table[a & 0xFF] + # return 0x02^(a-1) in GF(2^8) def aes_r_con(a): ans = 1 while a > 1: - ans <<= 1; + ans <<= 1 if ans & 0x100: - ans ^= 0x11b + ans ^= 0x11B a -= 1 return ans + ################################################################## # basic AES algorithm; see FIPS-197 # @@ -81,6 +327,7 @@ def aes_add_round_key(state, w): for i in range(16): state[i] ^= w[i] + # combined sub_bytes, shift_rows, mix_columns, add_round_key # all inputs must be size 16 def aes_sb_sr_mc_ark(state, w, w_idx, temp): @@ -90,7 +337,7 @@ def aes_sb_sr_mc_ark(state, w, w_idx, temp): x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]] x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]] x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]] - temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx] + temp[temp_idx] = aes_gf8_mul_2(x0) ^ aes_gf8_mul_3(x1) ^ x2 ^ x3 ^ w[w_idx] temp[temp_idx + 1] = x0 ^ aes_gf8_mul_2(x1) ^ aes_gf8_mul_3(x2) ^ x3 ^ w[w_idx + 1] temp[temp_idx + 2] = x0 ^ x1 ^ aes_gf8_mul_2(x2) ^ aes_gf8_mul_3(x3) ^ w[w_idx + 2] temp[temp_idx + 3] = aes_gf8_mul_3(x0) ^ x1 ^ x2 ^ aes_gf8_mul_2(x3) ^ w[w_idx + 3] @@ -99,6 +346,7 @@ def aes_sb_sr_mc_ark(state, w, w_idx, temp): for i in range(16): state[i] = temp[i] + # combined sub_bytes, shift_rows, add_round_key # all inputs must be size 16 def aes_sb_sr_ark(state, w, w_idx, temp): @@ -108,7 +356,7 @@ def aes_sb_sr_ark(state, w, w_idx, temp): x1 = aes_s_box_table[state[1 + ((i + 1) & 3) * 4]] x2 = aes_s_box_table[state[2 + ((i + 2) & 3) * 4]] x3 = aes_s_box_table[state[3 + ((i + 3) & 3) * 4]] - temp[temp_idx] = x0 ^ w[w_idx] + temp[temp_idx] = x0 ^ w[w_idx] temp[temp_idx + 1] = x1 ^ w[w_idx + 1] temp[temp_idx + 2] = x2 ^ w[w_idx + 2] temp[temp_idx + 3] = x3 ^ w[w_idx + 3] @@ -117,6 +365,7 @@ def aes_sb_sr_ark(state, w, w_idx, temp): for i in range(16): state[i] = temp[i] + # take state as input and change it to the next state in the sequence # state and temp have size 16, w has size 16 * (Nr + 1), Nr >= 1 def aes_state(state, w, temp, nr): @@ -127,6 +376,7 @@ def aes_state(state, w, temp, nr): w_idx += 16 aes_sb_sr_ark(state, w, w_idx, temp) + # expand 'key' to 'w' for use with aes_state # key has size 4 * Nk, w has size 16 * (Nr + 1), temp has size 16 def aes_key_expansion(key, w, temp, nk, nr): @@ -150,9 +400,11 @@ def aes_key_expansion(key, w, temp, nk, nr): for j in range(4): w[w_idx + j] = w[w_idx + j - 4 * nk] ^ t[t_idx + j] + ################################################################## # simple use of AES algorithm, using output feedback (OFB) mode + class AES: def __init__(self, keysize): if keysize == 128: @@ -178,7 +430,7 @@ class AES: def set_iv(self, iv): for i in range(16): self.state[i] = iv[i] - self.state_pos = 16; + self.state_pos = 16 def get_some_state(self, n_needed): if self.state_pos >= 16: @@ -200,6 +452,7 @@ class AES: idx += ln self.state_pos += n + ################################################################## # test code @@ -209,6 +462,7 @@ except ImportError: import time import _thread + class LockedCounter: def __init__(self): self.lock = _thread.allocate_lock() @@ -219,8 +473,10 @@ class LockedCounter: self.value += val self.lock.release() + count = LockedCounter() + def thread_entry(): global count @@ -249,7 +505,8 @@ def thread_entry(): count.add(1) -if __name__ == '__main__': + +if __name__ == "__main__": n_thread = 20 for i in range(n_thread): _thread.start_new_thread(thread_entry, ()) diff --git a/tests/thread/stress_create.py b/tests/thread/stress_create.py index 2399746cca..eda768fa7b 100644 --- a/tests/thread/stress_create.py +++ b/tests/thread/stress_create.py @@ -6,9 +6,11 @@ except ImportError: import time import _thread + def thread_entry(n): pass + thread_num = 0 while thread_num < 500: try: @@ -19,4 +21,4 @@ while thread_num < 500: # wait for the last threads to terminate time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/stress_heap.py b/tests/thread/stress_heap.py index 206cf1a860..41dfa5f376 100644 --- a/tests/thread/stress_heap.py +++ b/tests/thread/stress_heap.py @@ -11,9 +11,11 @@ except ImportError: import time import _thread + def last(l): return l[-1] + def thread_entry(n): # allocate a bytearray and fill it data = bytearray(i for i in range(256)) @@ -35,6 +37,7 @@ def thread_entry(n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 10 n_finished = 0 diff --git a/tests/thread/stress_recurse.py b/tests/thread/stress_recurse.py index 8edee246ad..b7a1288211 100644 --- a/tests/thread/stress_recurse.py +++ b/tests/thread/stress_recurse.py @@ -6,17 +6,20 @@ import _thread + def foo(): foo() + def thread_entry(): try: foo() except RuntimeError: - print('RuntimeError') + print("RuntimeError") global finished finished = True + finished = False _thread.start_new_thread(thread_entry, ()) @@ -24,4 +27,4 @@ _thread.start_new_thread(thread_entry, ()) # busy wait for thread to finish while not finished: pass -print('done') +print("done") diff --git a/tests/thread/thread_exc1.py b/tests/thread/thread_exc1.py index e00a16bd26..3c3a1e8be9 100644 --- a/tests/thread/thread_exc1.py +++ b/tests/thread/thread_exc1.py @@ -6,9 +6,11 @@ import _thread + def foo(): raise ValueError + def thread_entry(): try: foo() @@ -18,6 +20,7 @@ def thread_entry(): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 @@ -29,4 +32,4 @@ for i in range(n_thread): # busy wait for threads to finish while n_finished < n_thread: pass -print('done') +print("done") diff --git a/tests/thread/thread_exc2.py b/tests/thread/thread_exc2.py index 35cb324412..2863e1dec1 100644 --- a/tests/thread/thread_exc2.py +++ b/tests/thread/thread_exc2.py @@ -2,9 +2,11 @@ import utime import _thread + def thread_entry(): raise ValueError + _thread.start_new_thread(thread_entry, ()) utime.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_exit1.py b/tests/thread/thread_exit1.py index ad7b01d89b..6179716d14 100644 --- a/tests/thread/thread_exit1.py +++ b/tests/thread/thread_exit1.py @@ -10,12 +10,14 @@ except ImportError: import time import _thread + def thread_entry(): _thread.exit() + _thread.start_new_thread(thread_entry, ()) _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_exit2.py b/tests/thread/thread_exit2.py index 6bff8a1736..ba9852b5c2 100644 --- a/tests/thread/thread_exit2.py +++ b/tests/thread/thread_exit2.py @@ -10,12 +10,14 @@ except ImportError: import time import _thread + def thread_entry(): raise SystemExit + _thread.start_new_thread(thread_entry, ()) _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_gc1.py b/tests/thread/thread_gc1.py index 2ea1891615..4e4faeaf89 100644 --- a/tests/thread/thread_gc1.py +++ b/tests/thread/thread_gc1.py @@ -7,6 +7,7 @@ import gc import _thread + def thread_entry(n): # allocate a bytearray and fill it data = bytearray(i for i in range(256)) @@ -23,6 +24,7 @@ def thread_entry(n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 diff --git a/tests/thread/thread_ident1.py b/tests/thread/thread_ident1.py index 9a6f89ff5f..1ba342e2b6 100644 --- a/tests/thread/thread_ident1.py +++ b/tests/thread/thread_ident1.py @@ -6,18 +6,20 @@ import _thread + def thread_entry(): tid = _thread.get_ident() - print('thread', type(tid) == int, tid != 0, tid != tid_main) + print("thread", type(tid) == int, tid != 0, tid != tid_main) global finished finished = True + tid_main = _thread.get_ident() -print('main', type(tid_main) == int, tid_main != 0) +print("main", type(tid_main) == int, tid_main != 0) finished = False _thread.start_new_thread(thread_entry, ()) while not finished: pass -print('done') +print("done") diff --git a/tests/thread/thread_lock1.py b/tests/thread/thread_lock1.py index c2d7c9d1ed..e7066402ca 100644 --- a/tests/thread/thread_lock1.py +++ b/tests/thread/thread_lock1.py @@ -38,11 +38,11 @@ try: print(lock.locked()) raise KeyError except KeyError: - print('KeyError') + print("KeyError") print(lock.locked()) # test that we can't release an unlocked lock try: lock.release() except RuntimeError: - print('RuntimeError') + print("RuntimeError") diff --git a/tests/thread/thread_lock2.py b/tests/thread/thread_lock2.py index 4ef912dff5..c43b4b18d1 100644 --- a/tests/thread/thread_lock2.py +++ b/tests/thread/thread_lock2.py @@ -12,15 +12,17 @@ import _thread lock = _thread.allocate_lock() + def thread_entry(): lock.acquire() - print('have it') + print("have it") lock.release() + # spawn the threads for i in range(4): _thread.start_new_thread(thread_entry, ()) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_lock3.py b/tests/thread/thread_lock3.py index 35808d99cb..32d0c54b59 100644 --- a/tests/thread/thread_lock3.py +++ b/tests/thread/thread_lock3.py @@ -10,16 +10,18 @@ lock = _thread.allocate_lock() n_thread = 10 n_finished = 0 + def thread_entry(idx): global n_finished while True: with lock: if n_finished == idx: break - print('my turn:', idx) + print("my turn:", idx) with lock: n_finished += 1 + # spawn threads for i in range(n_thread): _thread.start_new_thread(thread_entry, (i,)) diff --git a/tests/thread/thread_lock4.py b/tests/thread/thread_lock4.py index 440f3e90c6..7637d10b96 100644 --- a/tests/thread/thread_lock4.py +++ b/tests/thread/thread_lock4.py @@ -10,12 +10,14 @@ except ImportError: import time import _thread + def fac(n): x = 1 for i in range(1, n + 1): x *= i return x + def thread_entry(): while True: with jobs_lock: @@ -27,6 +29,7 @@ def thread_entry(): with output_lock: output.append((arg, ans)) + # create a list of jobs jobs = [(fac, i) for i in range(20, 80)] jobs_lock = _thread.allocate_lock() diff --git a/tests/thread/thread_qstr1.py b/tests/thread/thread_qstr1.py index dccfb7f517..2099f94bdb 100644 --- a/tests/thread/thread_qstr1.py +++ b/tests/thread/thread_qstr1.py @@ -15,6 +15,7 @@ def check(s, val): assert type(s) == str assert int(s) == val + # main thread function def th(base, n): for i in range(n): @@ -25,10 +26,11 @@ def th(base, n): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 -n_qstr_per_thread = 100 # make 1000 for a more stressful test (uses more heap) +n_qstr_per_thread = 100 # make 1000 for a more stressful test (uses more heap) # spawn threads for i in range(n_thread): @@ -38,4 +40,4 @@ for i in range(n_thread): while n_finished < n_thread: time.sleep(1) -print('pass') +print("pass") diff --git a/tests/thread/thread_shared1.py b/tests/thread/thread_shared1.py index de339ad7f8..87f8b51e26 100644 --- a/tests/thread/thread_shared1.py +++ b/tests/thread/thread_shared1.py @@ -6,9 +6,11 @@ import _thread + def foo(i): pass + def thread_entry(n, tup): for i in tup: foo(i) @@ -16,6 +18,7 @@ def thread_entry(n, tup): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 2 n_finished = 0 diff --git a/tests/thread/thread_shared2.py b/tests/thread/thread_shared2.py index 2c749e6883..dbe18f9875 100644 --- a/tests/thread/thread_shared2.py +++ b/tests/thread/thread_shared2.py @@ -7,9 +7,11 @@ import _thread + def foo(lst, i): lst[i] += 1 + def thread_entry(n, lst, idx): for i in range(n): foo(lst, idx) @@ -17,6 +19,7 @@ def thread_entry(n, lst, idx): global n_finished n_finished += 1 + lock = _thread.allocate_lock() n_thread = 2 n_finished = 0 diff --git a/tests/thread/thread_sleep1.py b/tests/thread/thread_sleep1.py index d5aa99f977..d81d537399 100644 --- a/tests/thread/thread_sleep1.py +++ b/tests/thread/thread_sleep1.py @@ -6,9 +6,11 @@ try: import utime + sleep_ms = utime.sleep_ms except ImportError: import time + sleep_ms = lambda t: time.sleep(t / 1000) import _thread @@ -17,6 +19,7 @@ lock = _thread.allocate_lock() n_thread = 4 n_finished = 0 + def thread_entry(t): global n_finished sleep_ms(t) @@ -24,10 +27,11 @@ def thread_entry(t): with lock: n_finished += 1 + for i in range(n_thread): _thread.start_new_thread(thread_entry, (10 * i,)) # wait for threads to finish while n_finished < n_thread: sleep_ms(100) -print('done', n_thread) +print("done", n_thread) diff --git a/tests/thread/thread_stacksize1.py b/tests/thread/thread_stacksize1.py index e7189fafbc..0c6e7a92cd 100644 --- a/tests/thread/thread_stacksize1.py +++ b/tests/thread/thread_stacksize1.py @@ -8,20 +8,23 @@ import sys import _thread # different implementations have different minimum sizes -if sys.implementation.name == 'micropython': +if sys.implementation.name == "micropython": sz = 2 * 1024 else: sz = 32 * 1024 + def foo(): pass + def thread_entry(): foo() with lock: global n_finished n_finished += 1 + # reset stack size to default _thread.stack_size() @@ -46,4 +49,4 @@ _thread.stack_size() # busy wait for threads to finish while n_finished < n_thread: pass -print('done') +print("done") diff --git a/tests/thread/thread_start1.py b/tests/thread/thread_start1.py index 94df6dc625..f08ff05a8e 100644 --- a/tests/thread/thread_start1.py +++ b/tests/thread/thread_start1.py @@ -10,16 +10,19 @@ except ImportError: import time import _thread + def foo(): pass + def thread_entry(n): for i in range(n): foo() + _thread.start_new_thread(thread_entry, (10,)) _thread.start_new_thread(thread_entry, (20,)) # wait for threads to finish time.sleep(1) -print('done') +print("done") diff --git a/tests/thread/thread_start2.py b/tests/thread/thread_start2.py index 9412bb6183..40f8a05227 100644 --- a/tests/thread/thread_start2.py +++ b/tests/thread/thread_start2.py @@ -10,11 +10,13 @@ except ImportError: import time import _thread + def thread_entry(a0, a1, a2, a3): - print('thread', a0, a1, a2, a3) + print("thread", a0, a1, a2, a3) + # spawn thread using kw args -_thread.start_new_thread(thread_entry, (10, 20), {'a2': 0, 'a3': 1}) +_thread.start_new_thread(thread_entry, (10, 20), {"a2": 0, "a3": 1}) # wait for thread to finish time.sleep(1) @@ -23,6 +25,6 @@ time.sleep(1) try: _thread.start_new_thread(thread_entry, (), ()) except TypeError: - print('TypeError') + print("TypeError") -print('done') +print("done") diff --git a/tests/unicode/file2.py b/tests/unicode/file2.py index 8c45f91faf..1a5b933c89 100644 --- a/tests/unicode/file2.py +++ b/tests/unicode/file2.py @@ -1,11 +1,12 @@ # test reading a given number of characters + def do(mode): - if mode == 'rb': + if mode == "rb": enc = None else: - enc = 'utf-8' - f = open('unicode/data/utf-8_2.txt', mode=mode, encoding=enc) + enc = "utf-8" + f = open("unicode/data/utf-8_2.txt", mode=mode, encoding=enc) print(f.read(1)) print(f.read(1)) print(f.read(2)) @@ -15,12 +16,13 @@ def do(mode): f.readline() # check 3-byte utf-8 char - print(f.read(1 if mode == 'rt' else 3)) + print(f.read(1 if mode == "rt" else 3)) # check 4-byte utf-8 char - print(f.read(1 if mode == 'rt' else 4)) + print(f.read(1 if mode == "rt" else 4)) f.close() -do('rb') -do('rt') + +do("rb") +do("rt") diff --git a/tests/unicode/unicode.py b/tests/unicode/unicode.py index 3a35ce8948..f5af9cfff4 100644 --- a/tests/unicode/unicode.py +++ b/tests/unicode/unicode.py @@ -1,17 +1,17 @@ # Test a UTF-8 encoded literal s = "asdf©qwer" for i in range(len(s)): - print("s[%d]: %s %X"%(i, s[i], ord(s[i]))) + print("s[%d]: %s %X" % (i, s[i], ord(s[i]))) # Test all three forms of Unicode escape, and # all blocks of UTF-8 byte patterns s = "a\xA9\xFF\u0123\u0800\uFFEE\U0001F44C" for i in range(-len(s), len(s)): - print("s[%d]: %s %X"%(i, s[i], ord(s[i]))) - print("s[:%d]: %d chars, '%s'"%(i, len(s[:i]), s[:i])) + print("s[%d]: %s %X" % (i, s[i], ord(s[i]))) + print("s[:%d]: %d chars, '%s'" % (i, len(s[:i]), s[:i])) for j in range(i, len(s)): - print("s[%d:%d]: %d chars, '%s'"%(i, j, len(s[i:j]), s[i:j])) - print("s[%d:]: %d chars, '%s'"%(i, len(s[i:]), s[i:])) + print("s[%d:%d]: %d chars, '%s'" % (i, j, len(s[i:j]), s[i:j])) + print("s[%d:]: %d chars, '%s'" % (i, len(s[i:]), s[i:])) # Test UTF-8 encode and decode enc = s.encode() @@ -19,31 +19,31 @@ print(enc, enc.decode() == s) # printing of unicode chars using repr # NOTE: for some characters (eg \u10ff) we differ to CPython -print(repr('a\uffff')) -print(repr('a\U0001ffff')) +print(repr("a\uffff")) +print(repr("a\U0001ffff")) # test invalid escape code try: eval('"\\U00110000"') except SyntaxError: - print('SyntaxError') + print("SyntaxError") # test unicode string given to int try: - int('\u0200') + int("\u0200") except ValueError: - print('ValueError') + print("ValueError") # test invalid UTF-8 string try: - str(b'ab\xa1', 'utf8') + str(b"ab\xa1", "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") try: - str(b'ab\xf8', 'utf8') + str(b"ab\xf8", "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") try: - str(bytearray(b'ab\xc0a'), 'utf8') + str(bytearray(b"ab\xc0a"), "utf8") except UnicodeError: - print('UnicodeError') + print("UnicodeError") diff --git a/tests/unicode/unicode_id.py b/tests/unicode/unicode_id.py index 10f540c503..3a58e3f72b 100644 --- a/tests/unicode/unicode_id.py +++ b/tests/unicode/unicode_id.py @@ -14,14 +14,19 @@ print(α, αβγ, bβ, βb) def α(β, γ): δ = β + γ print(β, γ, δ) + + α(1, 2) # class, method identifiers class φ: def __init__(self): pass + def δ(self, ϵ): print(ϵ) + + zζzζz = φ() if hasattr(zζzζz, "δ"): zζzζz.δ(ϵ=123) diff --git a/tests/unicode/unicode_ord.py b/tests/unicode/unicode_ord.py index 47cfa1c2d7..73577050bf 100644 --- a/tests/unicode/unicode_ord.py +++ b/tests/unicode/unicode_ord.py @@ -1,3 +1,3 @@ # test builtin ord with unicode characters -print(ord('α')) +print(ord("α")) diff --git a/tests/unicode/unicode_str_format.py b/tests/unicode/unicode_str_format.py index bf8505a31a..1a60e7be4a 100644 --- a/tests/unicode/unicode_str_format.py +++ b/tests/unicode/unicode_str_format.py @@ -1,4 +1,4 @@ # test handling of unicode chars in format strings -print('α'.format()) -print('{α}'.format(α=1)) +print("α".format()) +print("{α}".format(α=1)) diff --git a/tests/unicode/unicode_str_modulo.py b/tests/unicode/unicode_str_modulo.py index e9b152473c..42211d0b05 100644 --- a/tests/unicode/unicode_str_modulo.py +++ b/tests/unicode/unicode_str_modulo.py @@ -1,3 +1,3 @@ # test handling of unicode chars in string % formatting -print('α' % ()) +print("α" % ()) diff --git a/tests/unicode/unicode_subscr.py b/tests/unicode/unicode_subscr.py index a2f434de58..5028910077 100644 --- a/tests/unicode/unicode_subscr.py +++ b/tests/unicode/unicode_subscr.py @@ -1,4 +1,4 @@ -a = '¢пр' +a = "¢пр" print(a[0], a[0:1]) print(a[1], a[1:2]) diff --git a/tests/unix/extra_coverage.py b/tests/unix/extra_coverage.py index 13721f1f47..e31eece774 100644 --- a/tests/unix/extra_coverage.py +++ b/tests/unix/extra_coverage.py @@ -13,33 +13,33 @@ data = extra_coverage() print(data[0], data[1]) print(hash(data[0])) print(hash(data[1])) -print(hash(bytes(data[0], 'utf8'))) -print(hash(str(data[1], 'utf8'))) +print(hash(bytes(data[0], "utf8"))) +print(hash(str(data[1], "utf8"))) # test streams -stream = data[2] # has set_error and set_buf. Write always returns error -stream.set_error(uerrno.EAGAIN) # non-blocking error -print(stream.read()) # read all encounters non-blocking error -print(stream.read(1)) # read 1 byte encounters non-blocking error -print(stream.readline()) # readline encounters non-blocking error -print(stream.readinto(bytearray(10))) # readinto encounters non-blocking error -print(stream.write(b'1')) # write encounters non-blocking error -print(stream.write1(b'1')) # write1 encounters non-blocking error -stream.set_buf(b'123') -print(stream.read(4)) # read encounters non-blocking error after successful reads -stream.set_buf(b'123') -print(stream.read1(4)) # read1 encounters non-blocking error after successful reads -stream.set_buf(b'123') -print(stream.readline(4)) # readline encounters non-blocking error after successful reads +stream = data[2] # has set_error and set_buf. Write always returns error +stream.set_error(uerrno.EAGAIN) # non-blocking error +print(stream.read()) # read all encounters non-blocking error +print(stream.read(1)) # read 1 byte encounters non-blocking error +print(stream.readline()) # readline encounters non-blocking error +print(stream.readinto(bytearray(10))) # readinto encounters non-blocking error +print(stream.write(b"1")) # write encounters non-blocking error +print(stream.write1(b"1")) # write1 encounters non-blocking error +stream.set_buf(b"123") +print(stream.read(4)) # read encounters non-blocking error after successful reads +stream.set_buf(b"123") +print(stream.read1(4)) # read1 encounters non-blocking error after successful reads +stream.set_buf(b"123") +print(stream.readline(4)) # readline encounters non-blocking error after successful reads try: - print(stream.ioctl(0, 0)) # ioctl encounters non-blocking error; raises OSError + print(stream.ioctl(0, 0)) # ioctl encounters non-blocking error; raises OSError except OSError: - print('OSError') + print("OSError") stream.set_error(0) -print(stream.ioctl(0, bytearray(10))) # successful ioctl call +print(stream.ioctl(0, bytearray(10))) # successful ioctl call -stream2 = data[3] # is textio -print(stream2.read(1)) # read 1 byte encounters non-blocking error with textio stream +stream2 = data[3] # is textio +print(stream2.read(1)) # read 1 byte encounters non-blocking error with textio stream # test BufferedWriter with stream errors stream.set_error(uerrno.EAGAIN) @@ -52,23 +52,28 @@ import frzmpy1 # test import of frozen packages with __init__.py import frzstr_pkg1 + print(frzstr_pkg1.x) import frzmpy_pkg1 + print(frzmpy_pkg1.x) # test import of frozen packages without __init__.py from frzstr_pkg2.mod import Foo + print(Foo.x) from frzmpy_pkg2.mod import Foo + print(Foo.x) # test raising exception in frozen script try: import frzmpy2 except ZeroDivisionError: - print('ZeroDivisionError') + print("ZeroDivisionError") # test loading a resource from a frozen string import uio -buf = uio.resource_stream('frzstr_pkg2', 'mod.py') + +buf = uio.resource_stream("frzstr_pkg2", "mod.py") print(buf.read(21)) diff --git a/tests/unix/ffi_callback.py b/tests/unix/ffi_callback.py index 23b058bcec..21bfccf251 100644 --- a/tests/unix/ffi_callback.py +++ b/tests/unix/ffi_callback.py @@ -15,16 +15,19 @@ def ffi_open(names): err = e raise err -libc = ffi_open(('libc.so', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) qsort = libc.func("v", "qsort", "piip") + def cmp(pa, pb): a = ffi.as_bytearray(pa, 1) b = ffi.as_bytearray(pb, 1) - #print("cmp:", a, b) + # print("cmp:", a, b) return a[0] - b[0] + cmp_c = ffi.callback("i", cmp, "pp") s = bytearray(b"foobar") diff --git a/tests/unix/ffi_float.py b/tests/unix/ffi_float.py index c92a39bcdc..b12bce9682 100644 --- a/tests/unix/ffi_float.py +++ b/tests/unix/ffi_float.py @@ -16,17 +16,18 @@ def ffi_open(names): err = e raise err -libc = ffi_open(('libc.so', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libc = ffi_open(("libc.so", "libc.so.0", "libc.so.6", "libc.dylib")) strtof = libc.func("f", "strtof", "sp") -print('%.6f' % strtof('1.23', None)) +print("%.6f" % strtof("1.23", None)) strtod = libc.func("d", "strtod", "sp") -print('%.6f' % strtod('1.23', None)) +print("%.6f" % strtod("1.23", None)) # test passing double and float args -libm = ffi_open(('libm.so', 'libm.so.6', 'libc.so.0', 'libc.so.6', 'libc.dylib')) -tgamma = libm.func('d', 'tgamma', 'd') +libm = ffi_open(("libm.so", "libm.so.6", "libc.so.0", "libc.so.6", "libc.dylib")) +tgamma = libm.func("d", "tgamma", "d") for fun in (tgamma,): for val in (0.5, 1, 1.0, 1.5, 4, 4.0): - print('%.6f' % fun(val)) + print("%.6f" % fun(val)) diff --git a/tests/unix/ffi_float2.py b/tests/unix/ffi_float2.py index 721eb4d192..bbed696662 100644 --- a/tests/unix/ffi_float2.py +++ b/tests/unix/ffi_float2.py @@ -16,16 +16,17 @@ def ffi_open(names): err = e raise err -libm = ffi_open(('libm.so', 'libm.so.6', 'libc.so.0', 'libc.so.6', 'libc.dylib')) + +libm = ffi_open(("libm.so", "libm.so.6", "libc.so.0", "libc.so.6", "libc.dylib")) # Some libc's implement tgammaf as header macro with tgamma(), so don't assume # it'll be in library. try: - tgammaf = libm.func('f', 'tgammaf', 'f') + tgammaf = libm.func("f", "tgammaf", "f") except OSError: print("SKIP") raise SystemExit for fun in (tgammaf,): for val in (0.5, 1, 1.0, 1.5, 4, 4.0): - print('%.6f' % fun(val)) + print("%.6f" % fun(val)) diff --git a/tests/wipy/adc.py b/tests/wipy/adc.py index 6fd4373dbd..73264113f3 100644 --- a/tests/wipy/adc.py +++ b/tests/wipy/adc.py @@ -1,19 +1,19 @@ -''' +""" ADC test for the CC3200 based boards. -''' +""" from machine import ADC import os mch = os.uname().machine -if 'LaunchPad' in mch: - adc_pin = 'GP5' +if "LaunchPad" in mch: + adc_pin = "GP5" adc_channel = 3 -elif 'WiPy' in mch: - adc_pin = 'GP3' +elif "WiPy" in mch: + adc_pin = "GP3" adc_channel = 1 else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") adc = ADC(0) print(adc) @@ -49,7 +49,7 @@ print(apin) print(apin() > 3000) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): adc = ADC() apin = adc.channel(adc_channel) @@ -57,56 +57,56 @@ for i in range (0, 1000): try: adc = ADC(bits=17) except: - print('Exception') + print("Exception") try: adc = ADC(id=1) except: - print('Exception') + print("Exception") try: adc = ADC(0, 16) except: - print('Exception') + print("Exception") adc = ADC() try: apin = adc.channel(4) except: - print('Exception') + print("Exception") try: apin = adc.channel(-1) except: - print('Exception') + print("Exception") try: - apin = adc.channel(0, pin='GP3') + apin = adc.channel(0, pin="GP3") except: - print('Exception') + print("Exception") apin = adc.channel(1) apin.deinit() try: apin() except: - print('Exception') + print("Exception") try: apin.value() except: - print('Exception') + print("Exception") adc.deinit() try: apin.value() except: - print('Exception') + print("Exception") try: apin = adc.channel(1) except: - print('Exception') + print("Exception") # re-init must work adc.init() diff --git a/tests/wipy/modwipy.py b/tests/wipy/modwipy.py index 7571af0753..59df3ae90a 100644 --- a/tests/wipy/modwipy.py +++ b/tests/wipy/modwipy.py @@ -1,13 +1,13 @@ -''' +""" wipy module test for the CC3200 based boards -''' +""" import os import wipy mch = os.uname().machine -if not 'LaunchPad' in mch and not'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") print(wipy.heartbeat() == True) wipy.heartbeat(False) @@ -18,4 +18,4 @@ print(wipy.heartbeat() == True) try: wipy.heartbeat(True, 1) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/os.py b/tests/wipy/os.py index 0596a16b52..1f4debcade 100644 --- a/tests/wipy/os.py +++ b/tests/wipy/os.py @@ -1,164 +1,164 @@ -''' +""" os module test for the CC3200 based boards -''' +""" from machine import SD import os mch = os.uname().machine -if 'LaunchPad' in mch: - sd_pins = ('GP16', 'GP17', 'GP15') -elif 'WiPy' in mch: - sd_pins = ('GP10', 'GP11', 'GP15') +if "LaunchPad" in mch: + sd_pins = ("GP16", "GP17", "GP15") +elif "WiPy" in mch: + sd_pins = ("GP10", "GP11", "GP15") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") sd = SD(pins=sd_pins) -os.mount(sd, '/sd') -os.mkfs('/sd') -os.chdir('/flash') +os.mount(sd, "/sd") +os.mkfs("/sd") +os.chdir("/flash") print(os.listdir()) -os.chdir('/sd') +os.chdir("/sd") print(os.listdir()) # create a test directory in flash -os.mkdir('/flash/test') -os.chdir('/flash/test') +os.mkdir("/flash/test") +os.chdir("/flash/test") print(os.getcwd()) -os.chdir('..') +os.chdir("..") print(os.getcwd()) -os.chdir('test') +os.chdir("test") print(os.getcwd()) # create a new file -f = open('test.txt', 'w') +f = open("test.txt", "w") test_bytes = os.urandom(1024) n_w = f.write(test_bytes) print(n_w == len(test_bytes)) f.close() -f = open('test.txt', 'r') -r = bytes(f.read(), 'ascii') +f = open("test.txt", "r") +r = bytes(f.read(), "ascii") # check that we can write and read it correctly print(r == test_bytes) f.close() -os.rename('test.txt', 'newtest.txt') +os.rename("test.txt", "newtest.txt") print(os.listdir()) -os.rename('/flash/test', '/flash/newtest') -print(os.listdir('/flash')) -os.remove('newtest.txt') -os.chdir('..') -os.rmdir('newtest') +os.rename("/flash/test", "/flash/newtest") +print(os.listdir("/flash")) +os.remove("newtest.txt") +os.chdir("..") +os.rmdir("newtest") # create a test directory in the sd card -os.mkdir('/sd/test') -os.chdir('/sd/test') +os.mkdir("/sd/test") +os.chdir("/sd/test") print(os.getcwd()) -os.chdir('..') +os.chdir("..") print(os.getcwd()) -os.chdir('test') +os.chdir("test") print(os.getcwd()) # create a new file -f = open('test.txt', 'w') +f = open("test.txt", "w") test_bytes = os.urandom(1024) n_w = f.write(test_bytes) print(n_w == len(test_bytes)) f.close() -f = open('test.txt', 'r') -r = bytes(f.read(), 'ascii') +f = open("test.txt", "r") +r = bytes(f.read(), "ascii") # check that we can write and read it correctly print(r == test_bytes) f.close() -print('CC3200' in os.uname().machine) -print('WiPy' == os.uname().sysname) +print("CC3200" in os.uname().machine) +print("WiPy" == os.uname().sysname) os.sync() -os.stat('/flash') -os.stat('/flash/sys') -os.stat('/flash/boot.py') -os.stat('/sd') -os.stat('/') -os.chdir('/sd/test') -os.remove('test.txt') -os.chdir('/sd') -os.rmdir('test') -os.listdir('/sd') -print(os.listdir('/')) -os.unmount('/sd') -print(os.listdir('/')) +os.stat("/flash") +os.stat("/flash/sys") +os.stat("/flash/boot.py") +os.stat("/sd") +os.stat("/") +os.chdir("/sd/test") +os.remove("test.txt") +os.chdir("/sd") +os.rmdir("test") +os.listdir("/sd") +print(os.listdir("/")) +os.unmount("/sd") +print(os.listdir("/")) os.mkfs(sd) -os.mount(sd, '/sd') -print(os.listdir('/')) -os.chdir('/flash') +os.mount(sd, "/sd") +print(os.listdir("/")) +os.chdir("/flash") # next ones must raise sd.deinit() try: - os.listdir('/sd') + os.listdir("/sd") except: - print('Exception') + print("Exception") -#re-initialization must work +# re-initialization must work sd.init() -print(os.listdir('/sd')) +print(os.listdir("/sd")) try: - os.mount(sd, '/sd') + os.mount(sd, "/sd") except: - print('Exception') + print("Exception") try: - os.mount(sd, '/sd2') + os.mount(sd, "/sd2") except: - print('Exception') + print("Exception") -os.unmount('/sd') +os.unmount("/sd") try: - os.listdir('/sd') + os.listdir("/sd") except: - print('Exception') + print("Exception") try: - os.unmount('/flash') + os.unmount("/flash") except: - print('Exception') + print("Exception") try: - os.unmount('/something') + os.unmount("/something") except: - print('Exception') + print("Exception") try: - os.unmount('something') + os.unmount("something") except: - print('Exception') + print("Exception") try: - os.mkfs('flash') # incorrect path format + os.mkfs("flash") # incorrect path format except: - print('Exception') + print("Exception") try: - os.remove('/flash/nofile.txt') + os.remove("/flash/nofile.txt") except: - print('Exception') + print("Exception") try: - os.rename('/flash/nofile.txt', '/flash/nofile2.txt') + os.rename("/flash/nofile.txt", "/flash/nofile2.txt") except: - print('Exception') + print("Exception") try: - os.chdir('/flash/nodir') + os.chdir("/flash/nodir") except: - print('Exception') + print("Exception") try: - os.listdir('/flash/nodir') + os.listdir("/flash/nodir") except: - print('Exception') + print("Exception") -os.mount(sd, '/sd') -print(os.listdir('/')) -os.unmount('/sd') +os.mount(sd, "/sd") +print(os.listdir("/")) +os.unmount("/sd") diff --git a/tests/wipy/pin.py b/tests/wipy/pin.py index 666ecb66bc..43537bba5c 100644 --- a/tests/wipy/pin.py +++ b/tests/wipy/pin.py @@ -7,27 +7,61 @@ from machine import Pin import os mch = os.uname().machine -if 'LaunchPad' in mch: - pin_map = ['GP24', 'GP12', 'GP14', 'GP15', 'GP16', 'GP17', 'GP28', 'GP8', 'GP6', 'GP30', 'GP31', 'GP3', 'GP0', 'GP4', 'GP5'] +if "LaunchPad" in mch: + pin_map = [ + "GP24", + "GP12", + "GP14", + "GP15", + "GP16", + "GP17", + "GP28", + "GP8", + "GP6", + "GP30", + "GP31", + "GP3", + "GP0", + "GP4", + "GP5", + ] max_af_idx = 15 -elif 'WiPy' in mch: - pin_map = ['GP23', 'GP24', 'GP12', 'GP13', 'GP14', 'GP9', 'GP17', 'GP28', 'GP22', 'GP8', 'GP30', 'GP31', 'GP0', 'GP4', 'GP5'] +elif "WiPy" in mch: + pin_map = [ + "GP23", + "GP24", + "GP12", + "GP13", + "GP14", + "GP9", + "GP17", + "GP28", + "GP22", + "GP8", + "GP30", + "GP31", + "GP0", + "GP4", + "GP5", + ] max_af_idx = 15 else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # test initial value -p = Pin('GP12', Pin.IN) -Pin('GP17', Pin.OUT, value=1) +p = Pin("GP12", Pin.IN) +Pin("GP17", Pin.OUT, value=1) print(p() == 1) -Pin('GP17', Pin.OUT, value=0) +Pin("GP17", Pin.OUT, value=0) print(p() == 0) + def test_noinit(): for p in pin_map: pin = Pin(p) pin.value() + def test_pin_read(pull): # enable the pull resistor on all pins, then read the value for p in pin_map: @@ -35,6 +69,7 @@ def test_pin_read(pull): for p in pin_map: print(pin()) + def test_pin_af(): for p in pin_map: for af in Pin(p).alt_list(): @@ -42,6 +77,7 @@ def test_pin_af(): Pin(p, mode=Pin.ALT, alt=af[1]) Pin(p, mode=Pin.ALT_OPEN_DRAIN, alt=af[1]) + # test un-initialized pins test_noinit() # test with pull-up and pull-down @@ -65,7 +101,7 @@ pin = Pin(pin_map[0], mode=Pin.OUT, drive=pin.LOW_POWER) pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_DOWN) pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP) pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP) -test_pin_af() # try the entire af range on all pins +test_pin_af() # try the entire af range on all pins # test pin init and printing pin = Pin(pin_map[0]) @@ -81,9 +117,9 @@ print(pin) # test value in OUT mode pin = Pin(pin_map[0], mode=Pin.OUT) pin.value(0) -pin.toggle() # test toggle +pin.toggle() # test toggle print(pin()) -pin.toggle() # test toggle again +pin.toggle() # test toggle again print(pin()) # test different value settings pin(1) @@ -116,66 +152,66 @@ print(pin.id() == pin_map[0]) # all the next ones MUST raise try: - pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value + pin = Pin(pin_map[0], mode=Pin.OUT, pull=Pin.PULL_UP, drive=pin.IN) # incorrect drive value except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value + pin = Pin(pin_map[0], mode=Pin.LOW_POWER, pull=Pin.PULL_UP) # incorrect mode value except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value + pin = Pin(pin_map[0], mode=Pin.IN, pull=Pin.HIGH_POWER) # incorrect pull value except Exception: - print('Exception') + print("Exception") try: - pin = Pin('A0', Pin.OUT, Pin.PULL_DOWN) # incorrect pin id + pin = Pin("A0", Pin.OUT, Pin.PULL_DOWN) # incorrect pin id except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode + pin = Pin(pin_map[0], Pin.IN, Pin.PULL_UP, alt=0) # af specified in GPIO mode except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode + pin = Pin(pin_map[0], Pin.OUT, Pin.PULL_UP, alt=7) # af specified in GPIO mode except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af + pin = Pin(pin_map[0], Pin.ALT, Pin.PULL_UP, alt=0) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af + pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=-1) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af + pin = Pin(pin_map[0], Pin.ALT_OPEN_DRAIN, Pin.PULL_UP, alt=16) # incorrect af except Exception: - print('Exception') + print("Exception") try: - pin.mode(Pin.PULL_UP) # incorrect pin mode + pin.mode(Pin.PULL_UP) # incorrect pin mode except Exception: - print('Exception') + print("Exception") try: - pin.pull(Pin.OUT) # incorrect pull + pin.pull(Pin.OUT) # incorrect pull except Exception: - print('Exception') + print("Exception") try: - pin.drive(Pin.IN) # incorrect drive strength + pin.drive(Pin.IN) # incorrect drive strength except Exception: - print('Exception') + print("Exception") try: - pin.id('ABC') # id cannot be set + pin.id("ABC") # id cannot be set except Exception: - print('Exception') + print("Exception") diff --git a/tests/wipy/pin_irq.py b/tests/wipy/pin_irq.py index 875f1f9397..be5e1f426c 100644 --- a/tests/wipy/pin_irq.py +++ b/tests/wipy/pin_irq.py @@ -1,6 +1,6 @@ -''' +""" Pin IRQ test for the CC3200 based boards. -''' +""" from machine import Pin import machine @@ -8,17 +8,18 @@ import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - pins = ['GP16', 'GP13'] -elif 'WiPy' in mch: - pins = ['GP16', 'GP13'] +if "LaunchPad" in mch: + pins = ["GP16", "GP13"] +elif "WiPy" in mch: + pins = ["GP16", "GP13"] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") pin0 = Pin(pins[0], mode=Pin.OUT, value=1) pin1 = Pin(pins[1], mode=Pin.IN, pull=Pin.PULL_UP) -def pin_handler (pin_o): + +def pin_handler(pin_o): global pin_irq_count_trigger global pin_irq_count_total global _trigger @@ -26,11 +27,12 @@ def pin_handler (pin_o): pin_irq_count_trigger += 1 pin_irq_count_total += 1 + pin_irq_count_trigger = 0 pin_irq_count_total = 0 _trigger = Pin.IRQ_FALLING pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range (0, 10): +for i in range(0, 10): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 5) @@ -40,7 +42,7 @@ pin_irq_count_trigger = 0 pin_irq_count_total = 0 _trigger = Pin.IRQ_RISING pin1_irq = pin1.irq(trigger=_trigger, handler=pin_handler) -for i in range (0, 200): +for i in range(0, 200): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 100) @@ -69,7 +71,7 @@ print(pin_irq_count_total == 2) pin1_irq.disable() pin_irq_count_trigger = 0 pin_irq_count_total = 0 -for i in range (0, 10): +for i in range(0, 10): pin0.toggle() time.sleep_ms(5) print(pin_irq_count_trigger == 0) @@ -81,7 +83,7 @@ t0 = time.ticks_ms() pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=machine.SLEEP) machine.sleep() print(time.ticks_ms() - t0 < 10) -print('Awake') +print("Awake") # test waking up from suspended mode on high level pin0(1) @@ -89,7 +91,7 @@ t0 = time.ticks_ms() pin1_irq.init(trigger=Pin.IRQ_HIGH_LEVEL, wake=machine.SLEEP) machine.sleep() print(time.ticks_ms() - t0 < 10) -print('Awake') +print("Awake") # check for memory leaks for i in range(0, 1000): @@ -100,17 +102,19 @@ for i in range(0, 1000): try: pin1_irq.init(trigger=123456, handler=pin_handler) except: - print('Exception') + print("Exception") try: pin1_irq.init(trigger=Pin.IRQ_LOW_LEVEL, wake=1789456) except: - print('Exception') + print("Exception") try: - pin0_irq = pin0.irq(trigger=Pin.IRQ_RISING, wake=machine.SLEEP) # GP16 can't wake up from DEEPSLEEP + pin0_irq = pin0.irq( + trigger=Pin.IRQ_RISING, wake=machine.SLEEP + ) # GP16 can't wake up from DEEPSLEEP except: - print('Exception') + print("Exception") pin0_irq.disable() pin1_irq.disable() diff --git a/tests/wipy/reset/reset.py b/tests/wipy/reset/reset.py index 35a970c673..8d314f3b49 100644 --- a/tests/wipy/reset/reset.py +++ b/tests/wipy/reset/reset.py @@ -1,16 +1,16 @@ -''' +""" Reset script for the cc3200 boards This is needed to force the board to reboot with the default WLAN AP settings -''' +""" from machine import WDT import time import os mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") wdt = WDT(timeout=1000) print(wdt) diff --git a/tests/wipy/rtc.py b/tests/wipy/rtc.py index 2737ebe73a..c62e400fe3 100644 --- a/tests/wipy/rtc.py +++ b/tests/wipy/rtc.py @@ -1,14 +1,14 @@ -''' +""" RTC test for the CC3200 based boards. -''' +""" from machine import RTC import os import time mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") rtc = RTC() print(rtc) @@ -41,10 +41,12 @@ print(rtc.now()[4]) rtc.init((2015, 9, 19)) print(rtc.now()[3]) + def set_and_print(datetime): rtc.init(datetime) print(rtc.now()[:6]) + # make sure that setting works correctly set_and_print((2000, 1, 1, 0, 0, 0, 0, None)) set_and_print((2000, 1, 31, 0, 0, 0, 0, None)) @@ -66,7 +68,7 @@ rtc.alarm(0, 5000) rtc.alarm(time=2000) time.sleep_ms(1000) left = rtc.alarm_left() -print(abs(left-1000) <= 10) +print(abs(left - 1000) <= 10) time.sleep_ms(1000) print(rtc.alarm_left() == 0) time.sleep_ms(100) @@ -75,13 +77,13 @@ print(rtc.alarm_left(0) == 0) rtc.alarm(time=1000, repeat=True) time.sleep_ms(1500) left = rtc.alarm_left() -print(abs(left-500) <= 15) +print(abs(left - 500) <= 15) rtc.init((2015, 8, 29, 9, 0, 0, 0, None)) rtc.alarm(time=(2015, 8, 29, 9, 0, 45)) time.sleep_ms(1000) left = rtc.alarm_left() -print(abs(left-44000) <= 90) +print(abs(left - 44000) <= 90) rtc.alarm_cancel() rtc.deinit() @@ -89,29 +91,29 @@ rtc.deinit() try: rtc.alarm(5000) except: - print('Exception') + print("Exception") try: rtc.alarm_left(1) except: - print('Exception') + print("Exception") try: rtc.alarm_cancel(1) except: - print('Exception') + print("Exception") try: rtc.alarm(5000) except: - print('Exception') + print("Exception") try: rtc = RTC(200000000) except: - print('Exception') + print("Exception") try: rtc = RTC((2015, 8, 29, 9, 0, 0, 0, None)) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/sd.py b/tests/wipy/sd.py index c946e0c9f0..381d46f30a 100644 --- a/tests/wipy/sd.py +++ b/tests/wipy/sd.py @@ -1,17 +1,17 @@ -''' +""" SD card test for the CC3200 based boards. -''' +""" from machine import SD import os mch = os.uname().machine -if 'LaunchPad' in mch: - sd_pins = ('GP16', 'GP17', 'GP15') -elif 'WiPy' in mch: - sd_pins = ('GP10', 'GP11', 'GP15') +if "LaunchPad" in mch: + sd_pins = ("GP16", "GP17", "GP15") +elif "WiPy" in mch: + sd_pins = ("GP10", "GP11", "GP15") else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") sd = SD(pins=sd_pins) print(sd) @@ -35,11 +35,11 @@ except Exception: print("Exception") try: - sd = SD(pins=('GP10', 'GP11', 'GP8')) + sd = SD(pins=("GP10", "GP11", "GP8")) except Exception: print("Exception") try: - sd = SD(pins=('GP10', 'GP11')) + sd = SD(pins=("GP10", "GP11")) except Exception: print("Exception") diff --git a/tests/wipy/skipped/rtc_irq.py b/tests/wipy/skipped/rtc_irq.py index ec3baa5524..99712f8d18 100644 --- a/tests/wipy/skipped/rtc_irq.py +++ b/tests/wipy/skipped/rtc_irq.py @@ -1,6 +1,6 @@ -''' +""" RTC IRQ test for the CC3200 based boards. -''' +""" from machine import RTC import machine @@ -8,21 +8,25 @@ import os import time mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") + def rtc_ticks_ms(rtc): timedate = rtc.now() return (timedate[5] * 1000) + (timedate[6] // 1000) + rtc_irq_count = 0 -def alarm_handler (rtc_o): + +def alarm_handler(rtc_o): global rtc_irq global rtc_irq_count if rtc_irq.flags() & RTC.ALARM0: rtc_irq_count += 1 + rtc = RTC() rtc.alarm(time=500, repeat=True) rtc_irq = rtc.irq(trigger=RTC.ALARM0, handler=alarm_handler) @@ -81,9 +85,9 @@ while rtc_irq_count < 3: try: rtc_irq = rtc.irq(trigger=10, handler=alarm_handler) except: - print('Exception') + print("Exception") try: rtc_irq = rtc.irq(trigger=RTC.ALARM0, wake=1789456) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/time.py b/tests/wipy/time.py index e6237de356..c1d105d64d 100644 --- a/tests/wipy/time.py +++ b/tests/wipy/time.py @@ -2,12 +2,14 @@ import time DAYS_PER_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + def is_leap(year): return (year % 4) == 0 + def test(): seconds = 0 - wday = 5 # Jan 1, 2000 was a Saturday + wday = 5 # Jan 1, 2000 was a Saturday for year in range(2000, 2049): print("Testing %d" % year) yday = 1 @@ -19,53 +21,69 @@ def test(): for day in range(1, DAYS_PER_MONTH[month] + 1): secs = time.mktime((year, month, day, 0, 0, 0, 0, 0)) if secs != seconds: - print("mktime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "mktime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) tuple = time.localtime(seconds) secs = time.mktime(tuple) if secs != seconds: - print("localtime failed for %d-%02d-%02d got %d expected %d" % (year, month, day, secs, seconds)) + print( + "localtime failed for %d-%02d-%02d got %d expected %d" + % (year, month, day, secs, seconds) + ) return seconds += 86400 if yday != tuple[7]: - print("locatime for %d-%02d-%02d got yday %d, expecting %d" % (year, month, day, tuple[7], yday)) + print( + "locatime for %d-%02d-%02d got yday %d, expecting %d" + % (year, month, day, tuple[7], yday) + ) return if wday != tuple[6]: - print("locatime for %d-%02d-%02d got wday %d, expecting %d" % (year, month, day, tuple[6], wday)) + print( + "locatime for %d-%02d-%02d got wday %d, expecting %d" + % (year, month, day, tuple[6], wday) + ) return yday += 1 wday = (wday + 1) % 7 + def spot_test(seconds, expected_time): actual_time = time.localtime(seconds) for i in range(len(actual_time)): if actual_time[i] != expected_time[i]: - print("time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time) + print( + "time.localtime(", seconds, ") returned", actual_time, "expecting", expected_time + ) return print("time.localtime(", seconds, ") returned", actual_time, "(pass)") + test() -spot_test( 0, (2000, 1, 1, 0, 0, 0, 5, 1)) -spot_test( 1, (2000, 1, 1, 0, 0, 1, 5, 1)) -spot_test( 59, (2000, 1, 1, 0, 0, 59, 5, 1)) -spot_test( 60, (2000, 1, 1, 0, 1, 0, 5, 1)) -spot_test( 3599, (2000, 1, 1, 0, 59, 59, 5, 1)) -spot_test( 3600, (2000, 1, 1, 1, 0, 0, 5, 1)) -spot_test( -1, (1999, 12, 31, 23, 59, 59, 4, 365)) -spot_test( 447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) -spot_test( -940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) -spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) -spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) -spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) +spot_test(0, (2000, 1, 1, 0, 0, 0, 5, 1)) +spot_test(1, (2000, 1, 1, 0, 0, 1, 5, 1)) +spot_test(59, (2000, 1, 1, 0, 0, 59, 5, 1)) +spot_test(60, (2000, 1, 1, 0, 1, 0, 5, 1)) +spot_test(3599, (2000, 1, 1, 0, 59, 59, 5, 1)) +spot_test(3600, (2000, 1, 1, 1, 0, 0, 5, 1)) +spot_test(-1, (1999, 12, 31, 23, 59, 59, 4, 365)) +spot_test(447549467, (2014, 3, 7, 23, 17, 47, 4, 66)) +spot_test(-940984933, (1970, 3, 7, 23, 17, 47, 5, 66)) +spot_test(-1072915199, (1966, 1, 1, 0, 0, 1, 5, 1)) +spot_test(-1072915200, (1966, 1, 1, 0, 0, 0, 5, 1)) +spot_test(-1072915201, (1965, 12, 31, 23, 59, 59, 4, 365)) t1 = time.time() time.sleep(2) t2 = time.time() -print(abs(time.ticks_diff(t1, t2) -2) <= 1) +print(abs(time.ticks_diff(t1, t2) - 2) <= 1) t1 = time.ticks_ms() time.sleep_ms(50) t2 = time.ticks_ms() -print(abs(time.ticks_diff(t1, t2)- 50) <= 1) +print(abs(time.ticks_diff(t1, t2) - 50) <= 1) t1 = time.ticks_us() time.sleep_us(1000) diff --git a/tests/wipy/timer.py b/tests/wipy/timer.py index f62899b472..db25870db0 100644 --- a/tests/wipy/timer.py +++ b/tests/wipy/timer.py @@ -1,18 +1,18 @@ -''' +""" Timer test for the CC3200 based boards. -''' +""" from machine import Timer import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - pwm_pin = ('GP24') -elif 'WiPy' in mch: - pwm_pin = ('GP24') +if "LaunchPad" in mch: + pwm_pin = "GP24" +elif "WiPy" in mch: + pwm_pin = "GP24" else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") for i in range(4): tim = Timer(i, mode=Timer.PERIODIC) @@ -49,6 +49,7 @@ class TimerTest: def timer_isr(self, tim_ch): self.int_count += 1 + timer_test = TimerTest() ch = timer_test.tim.channel(Timer.A, freq=5) print(ch.freq() == 5) @@ -92,26 +93,26 @@ for i in range(1000): try: tim = Timer(0, mode=12) except: - print('Exception') + print("Exception") try: tim = Timer(4, mode=Timer.ONE_SHOT) except: - print('Exception') + print("Exception") try: tim = Timer(0, mode=Timer.PWM, width=32) except: - print('Exception') + print("Exception") tim = Timer(0, mode=Timer.PWM) try: ch = tim.channel(TIMER_A | TIMER_B, freq=10) except: - print('Exception') + print("Exception") try: ch = tim.channel(TIMER_A, freq=4) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/uart.py b/tests/wipy/uart.py index d8b405f770..0b1744d4ff 100644 --- a/tests/wipy/uart.py +++ b/tests/wipy/uart.py @@ -1,7 +1,7 @@ -''' +""" UART test for the CC3200 based boards. UART0 and UART1 must be connected together for this test to pass. -''' +""" from machine import UART from machine import Pin @@ -9,14 +9,20 @@ import os import time mch = os.uname().machine -if 'LaunchPad' in mch: +if "LaunchPad" in mch: uart_id_range = range(0, 2) - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] -elif 'WiPy' in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] +elif "WiPy" in mch: uart_id_range = range(0, 2) - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # just in case we have the repl duplicated on any of the uarts os.dupterm(None) @@ -33,13 +39,13 @@ for uart_id in uart_id_range: uart = UART(baudrate=1000000) uart = UART() print(uart) -uart = UART(baudrate=38400, pins=('GP12', 'GP13')) +uart = UART(baudrate=38400, pins=("GP12", "GP13")) print(uart) -uart = UART(pins=('GP12', 'GP13')) +uart = UART(pins=("GP12", "GP13")) print(uart) -uart = UART(pins=(None, 'GP17')) +uart = UART(pins=(None, "GP17")) print(uart) -uart = UART(baudrate=57600, pins=('GP16', 'GP17')) +uart = UART(baudrate=57600, pins=("GP16", "GP17")) print(uart) # now it's time for some loopback tests between the uarts @@ -48,15 +54,15 @@ print(uart0) uart1 = UART(1, 1000000, pins=uart_pins[1][0]) print(uart1) -print(uart0.write(b'123456') == 6) -print(uart1.read() == b'123456') +print(uart0.write(b"123456") == 6) +print(uart1.read() == b"123456") -print(uart1.write(b'123') == 3) -print(uart0.read(1) == b'1') -print(uart0.read(2) == b'23') +print(uart1.write(b"123") == 3) +print(uart0.read(1) == b"1") +print(uart0.read(2) == b"23") print(uart0.read() == None) -uart0.write(b'123') +uart0.write(b"123") buf = bytearray(3) print(uart1.readinto(buf, 1) == 1) print(buf) @@ -65,87 +71,87 @@ print(buf) # try initializing without the id uart0 = UART(baudrate=1000000, pins=uart_pins[0][0]) -uart0.write(b'1234567890') -time.sleep_ms(2) # because of the fifo interrupt levels +uart0.write(b"1234567890") +time.sleep_ms(2) # because of the fifo interrupt levels print(uart1.any() == 10) -print(uart1.readline() == b'1234567890') +print(uart1.readline() == b"1234567890") print(uart1.any() == 0) -uart0.write(b'1234567890') -print(uart1.read() == b'1234567890') +uart0.write(b"1234567890") +print(uart1.read() == b"1234567890") # tx only mode -uart0 = UART(0, 1000000, pins=('GP12', None)) -print(uart0.write(b'123456') == 6) -print(uart1.read() == b'123456') -print(uart1.write(b'123') == 3) +uart0 = UART(0, 1000000, pins=("GP12", None)) +print(uart0.write(b"123456") == 6) +print(uart1.read() == b"123456") +print(uart1.write(b"123") == 3) print(uart0.read() == None) # rx only mode -uart0 = UART(0, 1000000, pins=(None, 'GP13')) -print(uart0.write(b'123456') == 6) +uart0 = UART(0, 1000000, pins=(None, "GP13")) +print(uart0.write(b"123456") == 6) print(uart1.read() == None) -print(uart1.write(b'123') == 3) -print(uart0.read() == b'123') +print(uart1.write(b"123") == 3) +print(uart0.read() == b"123") # leave pins as they were (rx only mode) uart0 = UART(0, 1000000, pins=None) -print(uart0.write(b'123456') == 6) +print(uart0.write(b"123456") == 6) print(uart1.read() == None) -print(uart1.write(b'123') == 3) -print(uart0.read() == b'123') +print(uart1.write(b"123") == 3) +print(uart0.read() == b"123") # no pin assignment uart0 = UART(0, 1000000, pins=(None, None)) -print(uart0.write(b'123456789') == 9) +print(uart0.write(b"123456789") == 9) print(uart1.read() == None) -print(uart1.write(b'123456789') == 9) +print(uart1.write(b"123456789") == 9) print(uart0.read() == None) print(Pin.board.GP12) print(Pin.board.GP13) # check for memory leaks... -for i in range (0, 1000): +for i in range(0, 1000): uart0 = UART(0, 1000000) uart1 = UART(1, 1000000) # next ones must raise try: - UART(0, 9600, parity=None, pins=('GP12', 'GP13', 'GP7')) + UART(0, 9600, parity=None, pins=("GP12", "GP13", "GP7")) except Exception: - print('Exception') + print("Exception") try: - UART(0, 9600, parity=UART.ODD, pins=('GP12', 'GP7')) + UART(0, 9600, parity=UART.ODD, pins=("GP12", "GP7")) except Exception: - print('Exception') + print("Exception") uart0 = UART(0, 1000000) uart0.deinit() try: uart0.any() except Exception: - print('Exception') + print("Exception") try: uart0.read() except Exception: - print('Exception') + print("Exception") try: - uart0.write('abc') + uart0.write("abc") except Exception: - print('Exception') + print("Exception") try: - uart0.sendbreak('abc') + uart0.sendbreak("abc") except Exception: - print('Exception') + print("Exception") try: UART(2, 9600) except Exception: - print('Exception') + print("Exception") for uart_id in uart_id_range: uart = UART(uart_id, 1000000) diff --git a/tests/wipy/uart_irq.py b/tests/wipy/uart_irq.py index d4cd900585..e631e46a9c 100644 --- a/tests/wipy/uart_irq.py +++ b/tests/wipy/uart_irq.py @@ -1,18 +1,24 @@ -''' +""" UART IRQ test for the CC3200 based boards. -''' +""" from machine import UART import os import time mch = os.uname().machine -if 'LaunchPad' in mch: - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] -elif 'WiPy' in mch: - uart_pins = [[('GP12', 'GP13'), ('GP12', 'GP13', 'GP7', 'GP6')], [('GP16', 'GP17'), ('GP16', 'GP17', 'GP7', 'GP6')]] +if "LaunchPad" in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] +elif "WiPy" in mch: + uart_pins = [ + [("GP12", "GP13"), ("GP12", "GP13", "GP7", "GP6")], + [("GP16", "GP17"), ("GP16", "GP17", "GP7", "GP6")], + ] else: - raise Exception('Board not supported!') + raise Exception("Board not supported!") # just in case we have stdio duplicated on any of the uarts os.dupterm(None) @@ -23,22 +29,25 @@ uart1 = UART(1, 1000000, pins=uart_pins[1][0]) uart0_int_count = 0 uart1_int_count = 0 -def uart0_handler (uart_o): + +def uart0_handler(uart_o): global uart0_irq global uart0_int_count - if (uart0_irq.flags() & UART.RX_ANY): + if uart0_irq.flags() & UART.RX_ANY: uart0_int_count += 1 -def uart1_handler (uart_o): + +def uart1_handler(uart_o): global uart1_irq global uart1_int_count - if (uart1_irq.flags() & UART.RX_ANY): + if uart1_irq.flags() & UART.RX_ANY: uart1_int_count += 1 + uart0_irq = uart0.irq(trigger=UART.RX_ANY, handler=uart0_handler) uart1_irq = uart1.irq(trigger=UART.RX_ANY, handler=uart1_handler) -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -48,9 +57,9 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") -uart1.write(b'12345') +uart1.write(b"12345") # wait for the characters to be received while not uart0.any(): pass @@ -60,11 +69,11 @@ print(uart0.any() == 5) print(uart0_int_count > 0) print(uart0_irq.flags() == 0) print(uart1_irq.flags() == 0) -print(uart0.read() == b'12345') +print(uart0.read() == b"12345") # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -74,29 +83,29 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # disable the interrupt uart1_irq.disable() # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass time.sleep_us(100) print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt triggered this time +print(uart1_int_count == 0) # no interrupt triggered this time print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # enable the interrupt uart1_irq.enable() # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass @@ -106,22 +115,22 @@ print(uart1.any() == 3) print(uart1_int_count > 0) print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") -uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler +uart1_irq.init(trigger=UART.RX_ANY, handler=None) # No handler # do it again uart1_int_count = 0 -uart0.write(b'123') +uart0.write(b"123") # wait for the characters to be received while not uart1.any(): pass time.sleep_us(100) print(uart1.any() == 3) -print(uart1_int_count == 0) # no interrupt handler called +print(uart1_int_count == 0) # no interrupt handler called print(uart1_irq.flags() == 0) print(uart0_irq.flags() == 0) -print(uart1.read() == b'123') +print(uart1.read() == b"123") # check for memory leaks for i in range(0, 1000): @@ -132,17 +141,17 @@ for i in range(0, 1000): try: uart0_irq = uart0.irq(trigger=100, handler=uart0_handler) except: - print('Exception') + print("Exception") try: uart0_irq = uart0.irq(trigger=0) except: - print('Exception') + print("Exception") try: uart0_irq = uart0.irq(trigger=UART.RX_ANY, wake=Sleep.SUSPENDED) except: - print('Exception') + print("Exception") uart0_irq.disable() uart1_irq.disable() diff --git a/tests/wipy/wdt.py b/tests/wipy/wdt.py index a894b88fd8..56f6ea8d95 100644 --- a/tests/wipy/wdt.py +++ b/tests/wipy/wdt.py @@ -1,6 +1,6 @@ -''' +""" WDT test for the CC3200 based boards -''' +""" from machine import WDT import time diff --git a/tests/wipy/wlan/machine.py b/tests/wipy/wlan/machine.py index 2ee5299651..f69b117b74 100644 --- a/tests/wipy/wlan/machine.py +++ b/tests/wipy/wlan/machine.py @@ -1,14 +1,14 @@ -''' +""" machine test for the CC3200 based boards. -''' +""" import machine import os from network import WLAN mch = os.uname().machine -if not 'LaunchPad' in mch and not'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") wifi = WLAN() @@ -17,7 +17,7 @@ machine.idle() print(machine.freq() == (80000000,)) print(machine.unique_id() == wifi.mac()) -machine.main('main.py') +machine.main("main.py") rand_nums = [] for i in range(0, 100): @@ -25,7 +25,7 @@ for i in range(0, 100): if rand not in rand_nums: rand_nums.append(rand) else: - print('RNG number repeated') + print("RNG number repeated") break for i in range(0, 10): @@ -39,4 +39,4 @@ print(machine.wake_reason() >= 0) try: machine.main(123456) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/wlan/server.py b/tests/wipy/wlan/server.py index 05847e3761..40f56745c9 100644 --- a/tests/wipy/wlan/server.py +++ b/tests/wipy/wlan/server.py @@ -1,13 +1,13 @@ -''' +""" network server test for the CC3200 based boards. -''' +""" import os import network mch = os.uname().machine -if not 'LaunchPad' in mch and not'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") server = network.Server() @@ -16,7 +16,7 @@ print(server.isrunning() == True) server.deinit() print(server.isrunning() == False) -server.init(login=('test-user', 'test-password'), timeout=60) +server.init(login=("test-user", "test-password"), timeout=60) print(server.isrunning() == True) print(server.timeout() == 60) @@ -28,14 +28,14 @@ print(server.isrunning() == True) try: server.init(1) except: - print('Exception') + print("Exception") try: - server.init(0, login=('0000000000011111111111222222222222333333', 'abc')) + server.init(0, login=("0000000000011111111111222222222222333333", "abc")) except: - print('Exception') + print("Exception") try: server.timeout(1) except: - print('Exception') + print("Exception") diff --git a/tests/wipy/wlan/wlan.py b/tests/wipy/wlan/wlan.py index 96121325cf..dd85c86967 100644 --- a/tests/wipy/wlan/wlan.py +++ b/tests/wipy/wlan/wlan.py @@ -1,6 +1,6 @@ -''' +""" WLAN test for the CC3200 based boards. -''' +""" from network import WLAN import os @@ -8,8 +8,8 @@ import time import testconfig mch = os.uname().machine -if not 'LaunchPad' in mch and not 'WiPy' in mch: - raise Exception('Board not supported!') +if not "LaunchPad" in mch and not "WiPy" in mch: + raise Exception("Board not supported!") def wait_for_connection(wifi, timeout=10): @@ -17,9 +17,9 @@ def wait_for_connection(wifi, timeout=10): time.sleep(1) timeout -= 1 if wifi.isconnected(): - print('Connected') + print("Connected") else: - print('Connection failed!') + print("Connection failed!") wifi = WLAN(0, WLAN.STA) @@ -31,16 +31,16 @@ print(wifi.mode() == WLAN.AP) print(wifi.channel() == 1) print(wifi.auth() == None) print(wifi.antenna() == WLAN.INT_ANT) -wifi = WLAN(0, mode=WLAN.AP, ssid='test-wlan', auth=(WLAN.WPA, '123456abc'), channel=7) +wifi = WLAN(0, mode=WLAN.AP, ssid="test-wlan", auth=(WLAN.WPA, "123456abc"), channel=7) print(wifi.mode() == WLAN.AP) print(wifi.channel() == 7) -print(wifi.ssid() == 'test-wlan') -print(wifi.auth() == (WLAN.WPA, '123456abc')) +print(wifi.ssid() == "test-wlan") +print(wifi.auth() == (WLAN.WPA, "123456abc")) print(wifi.antenna() == WLAN.INT_ANT) wifi = WLAN(mode=WLAN.STA) print(wifi.mode() == WLAN.STA) -time.sleep(5) # this ensures a full network scan +time.sleep(5) # this ensures a full network scan scan_r = wifi.scan() print(len(scan_r) > 3) for net in scan_r: @@ -50,30 +50,30 @@ for net in scan_r: print(net.channel == None) print(net.sec == testconfig.wlan_auth[0]) print(net.rssi < 0) - print('Network found') + print("Network found") break wifi.mode(WLAN.STA) print(wifi.mode() == WLAN.STA) wifi.channel(7) print(wifi.channel() == 7) -wifi.ssid('t-wlan') -print(wifi.ssid() == 't-wlan') +wifi.ssid("t-wlan") +print(wifi.ssid() == "t-wlan") wifi.auth(None) print(wifi.auth() == None) -wifi.auth((WLAN.WEP, '11223344556677889900')) -print(wifi.auth() == (WLAN.WEP, '11223344556677889900')) +wifi.auth((WLAN.WEP, "11223344556677889900")) +print(wifi.auth() == (WLAN.WEP, "11223344556677889900")) wifi.antenna(WLAN.INT_ANT) print(wifi.antenna() == WLAN.INT_ANT) wifi.antenna(WLAN.EXT_ANT) print(wifi.antenna() == WLAN.EXT_ANT) -time.sleep(2) # this ensures a full network scan +time.sleep(2) # this ensures a full network scan scan_r = wifi.scan() print(len(scan_r) > 3) for net in scan_r: if net.ssid == testconfig.wlan_ssid: - print('Network found') + print("Network found") break wifi.antenna(WLAN.INT_ANT) @@ -82,12 +82,12 @@ print(wifi.mode() == WLAN.STA) wifi.connect(testconfig.wlan_ssid, auth=testconfig.wlan_auth, timeout=10000) wait_for_connection(wifi) -wifi.ifconfig(config='dhcp') +wifi.ifconfig(config="dhcp") wait_for_connection(wifi) -print('0.0.0.0' not in wifi.ifconfig()) -wifi.ifconfig(0, ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8')) +print("0.0.0.0" not in wifi.ifconfig()) +wifi.ifconfig(0, ("192.168.178.109", "255.255.255.0", "192.168.178.1", "8.8.8.8")) wait_for_connection(wifi) -print(wifi.ifconfig(0) == ('192.168.178.109', '255.255.255.0', '192.168.178.1', '8.8.8.8')) +print(wifi.ifconfig(0) == ("192.168.178.109", "255.255.255.0", "192.168.178.1", "8.8.8.8")) wait_for_connection(wifi) print(wifi.isconnected() == True) @@ -102,7 +102,7 @@ wifi.disconnect() print(wifi.isconnected() == False) # test init again -wifi.init(WLAN.AP, ssid='www.wipy.io', auth=None, channel=5, antenna=WLAN.INT_ANT) +wifi.init(WLAN.AP, ssid="www.wipy.io", auth=None, channel=5, antenna=WLAN.INT_ANT) print(wifi.mode() == WLAN.AP) # get the current instance without re-init @@ -118,64 +118,66 @@ print(len(wifi.mac()) == 6) try: wifi.init(mode=12345) except: - print('Exception') + print("Exception") try: wifi.init(1, mode=WLAN.AP) except: - print('Exception') + print("Exception") try: wifi.init(mode=WLAN.AP, ssid=None) except: - print('Exception') + print("Exception") try: wifi = WLAN(mode=WLAN.AP, channel=12) except: - print('Exception') + print("Exception") try: wifi.antenna(2) except: - print('Exception') + print("Exception") try: wifi.mode(10) except: - print('Exception') + print("Exception") try: - wifi.ssid('11111sdfasdfasdfasdf564sdf654asdfasdf123451245ssdgfsdf1111111111111111111111111234123412341234asdfasdf') + wifi.ssid( + "11111sdfasdfasdfasdf564sdf654asdfasdf123451245ssdgfsdf1111111111111111111111111234123412341234asdfasdf" + ) except: - print('Exception') + print("Exception") try: wifi.auth((0)) except: - print('Exception') + print("Exception") try: wifi.auth((0, None)) except: - print('Exception') + print("Exception") try: wifi.auth((10, 10)) except: - print('Exception') + print("Exception") try: wifi.channel(0) except: - print('Exception') + print("Exception") try: - wifi.ifconfig(1, 'dhcp') + wifi.ifconfig(1, "dhcp") except: - print('Exception') + print("Exception") try: wifi.ifconfig(config=()) except: - print('Exception') + print("Exception") diff --git a/tools/analyze_heap_dump.py b/tools/analyze_heap_dump.py index 887871db7a..d9b3dda599 100755 --- a/tools/analyze_heap_dump.py +++ b/tools/analyze_heap_dump.py @@ -38,42 +38,73 @@ MP_OBJ_SENTINEL = 4 READLINE_HIST_SIZE = 8 -SKIP_SYMBOLS = [".debug_ranges", ".debug_frame", ".debug_loc", ".comment", ".debug_str", ".debug_line", ".debug_abbrev", ".debug_info", "COMMON"] +SKIP_SYMBOLS = [ + ".debug_ranges", + ".debug_frame", + ".debug_loc", + ".comment", + ".debug_str", + ".debug_line", + ".debug_abbrev", + ".debug_info", + "COMMON", +] + @click.command() @click.argument("ram_filename") @click.argument("bin_filename") @click.argument("map_filename") -@click.option("--print_block_contents", default=False, - help="Prints the contents of each allocated block") -@click.option("--print_unknown_types", default=False, - help="Prints the micropython base type if we don't understand it.") -@click.option("--print_block_state", default=False, - help="Prints the heap block states (allocated or free)") -@click.option("--print_conflicting_symbols", default=False, - help="Prints conflicting symbols from the map") -@click.option("--print-heap-structure/--no-print-heap-structure", default=False, - help="Print heap structure") -@click.option("--output_directory", default="heapvis", - help="Destination for rendered output") -@click.option("--draw-heap-layout/--no-draw-heap-layout", default=True, - help="Draw the heap layout") -@click.option("--draw-heap-ownership/--no-draw-heap-ownership", default=False, - help="Draw the ownership graph of blocks on the heap") -@click.option("--analyze-snapshots", default="last", type=click.Choice(['all', 'last'])) -def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_contents, - print_unknown_types, print_block_state, print_conflicting_symbols, - print_heap_structure, output_directory, draw_heap_layout, - draw_heap_ownership, analyze_snapshots): +@click.option( + "--print_block_contents", default=False, help="Prints the contents of each allocated block" +) +@click.option( + "--print_unknown_types", + default=False, + help="Prints the micropython base type if we don't understand it.", +) +@click.option( + "--print_block_state", default=False, help="Prints the heap block states (allocated or free)" +) +@click.option( + "--print_conflicting_symbols", default=False, help="Prints conflicting symbols from the map" +) +@click.option( + "--print-heap-structure/--no-print-heap-structure", default=False, help="Print heap structure" +) +@click.option("--output_directory", default="heapvis", help="Destination for rendered output") +@click.option( + "--draw-heap-layout/--no-draw-heap-layout", default=True, help="Draw the heap layout" +) +@click.option( + "--draw-heap-ownership/--no-draw-heap-ownership", + default=False, + help="Draw the ownership graph of blocks on the heap", +) +@click.option("--analyze-snapshots", default="last", type=click.Choice(["all", "last"])) +def do_all_the_things( + ram_filename, + bin_filename, + map_filename, + print_block_contents, + print_unknown_types, + print_block_state, + print_conflicting_symbols, + print_heap_structure, + output_directory, + draw_heap_layout, + draw_heap_ownership, + analyze_snapshots, +): with open(ram_filename, "rb") as f: ram_dump = f.read() with open(bin_filename, "rb") as f: rom = f.read() - symbols = {} # name -> address, size - symbol_lookup = {} # address -> name - manual_symbol_map = {} # autoname -> name + symbols = {} # name -> address, size + symbol_lookup = {} # address -> name + manual_symbol_map = {} # autoname -> name def add_symbol(name, address=None, size=None): if "lto_priv" in name: @@ -85,7 +116,11 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont if name in symbols: if address and symbols[name][0] and symbols[name][0] != address: if print_conflicting_symbols: - print("Conflicting symbol: {} at addresses 0x{:08x} and 0x{:08x}".format(name, address, symbols[name][0])) + print( + "Conflicting symbol: {} at addresses 0x{:08x} and 0x{:08x}".format( + name, address, symbols[name][0] + ) + ) return if not address: address = symbols[name][0] @@ -118,21 +153,42 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont add_symbol(parts[0], size=parts[1]) name = None else: - if len(parts) == 1 and parts[0].startswith((".text", ".rodata", ".bss")) and parts[0].count(".") > 1 and not parts[0].isnumeric() and ".str" not in parts[0]: + if ( + len(parts) == 1 + and parts[0].startswith((".text", ".rodata", ".bss")) + and parts[0].count(".") > 1 + and not parts[0].isnumeric() + and ".str" not in parts[0] + ): name = parts[0].split(".")[2] - if len(parts) == 3 and parts[0].startswith("0x") and parts[1].startswith("0x") and name: + if ( + len(parts) == 3 + and parts[0].startswith("0x") + and parts[1].startswith("0x") + and name + ): add_symbol(name, parts[0], parts[1]) name = None if len(parts) == 2 and parts[0].startswith("0x") and not parts[1].startswith("0x"): add_symbol(parts[1], parts[0]) - if len(parts) == 4 and parts[0] not in SKIP_SYMBOLS and parts[1].startswith("0x") and parts[2].startswith("0x"): + if ( + len(parts) == 4 + and parts[0] not in SKIP_SYMBOLS + and parts[1].startswith("0x") + and parts[2].startswith("0x") + ): name, address, size, source = parts if name.startswith((".text", ".rodata", ".bss")) and name.count(".") > 1: name = name.split(".")[-1] add_symbol(name, address, size) name = None # Linker symbols - if len(parts) >= 4 and parts[0].startswith("0x") and parts[2] == "=" and parts[1] != ".": + if ( + len(parts) >= 4 + and parts[0].startswith("0x") + and parts[2] == "=" + and parts[1] != "." + ): add_symbol(parts[1], parts[0]) rom_start = symbols["_sfixed"][0] @@ -143,13 +199,14 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont # print(len(ram_dump) // ram_length, "snapshots") if analyze_snapshots == "all": snapshots = range(len(ram_dump) // ram_length - 1, -1, -1) - #snapshots = range(4576, -1, -1) + # snapshots = range(4576, -1, -1) elif analyze_snapshots == "last": snapshots = range(len(ram_dump) // ram_length - 1, len(ram_dump) // ram_length - 2, -1) for snapshot_num in snapshots: - ram = ram_dump[ram_length*snapshot_num:ram_length*(snapshot_num + 1)] + ram = ram_dump[ram_length * snapshot_num : ram_length * (snapshot_num + 1)] ownership_graph = pgv.AGraph(directed=True) + def load(address, size=4): if size is None: raise ValueError("You must provide a size") @@ -157,11 +214,11 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont ram_address = address - ram_start if (ram_address + size) > len(ram): raise ValueError("Unable to read 0x{:08x} from ram.".format(address)) - return ram[ram_address:ram_address+size] + return ram[ram_address : ram_address + size] elif address < len(rom): if (address + size) > len(rom): raise ValueError("Unable to read 0x{:08x} from rom.".format(address)) - return rom[address:address+size] + return rom[address : address + size] def load_pointer(address): return struct.unpack("".format(4 * (k + 1) + l) + rows += ''.format(4 * (k + 1) + l) rows += "" - table = "<{}
0x{:08x}
>".format(address, rows) + table = '<{}
0x{:08x}
>'.format( + address, rows + ) ownership_graph.add_node(address, label=table, style="invisible", shape="plaintext") print("add 0x{:08x}".format(address)) @@ -299,7 +379,7 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont potential_type = word bgcolor = "gray" if address in qstr_pools: - #print(address, len(data)) + # print(address, len(data)) bgcolor = "tomato" elif potential_type in function_types: bgcolor = "green" @@ -308,12 +388,13 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont elif print_unknown_types: print("unknown type", hex(potential_type)) - node.attr["label"] = "<" + node.attr["label"].replace("\"gray\"", "\"" + bgcolor + "\"") + ">" + node.attr["label"] = ( + "<" + node.attr["label"].replace('"gray"', '"' + bgcolor + '"') + ">" + ) if potential_type == str_type and k == 3: string_blocks.append(word) - if potential_type == dict_type: if k == 3: map_element_blocks.append(word) @@ -322,7 +403,7 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont port = k if k < 4: port = 0 - ownership_graph.add_edge(address, word, tailport=str(port)+":_") + ownership_graph.add_edge(address, word, tailport=str(port) + ":_") print(" 0x{:08x}".format(word)) if address in qstr_pools: if k > 0: @@ -330,7 +411,6 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont if k == 0: potential_type = dynamic_type - if potential_type == dynamic_type: if k == 0: node.attr["fillcolor"] = "plum" @@ -341,7 +421,6 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont if k == 2 and ram_start < word < ram_end: bytecode_blocks.append(word) - longest_free = 0 current_free = 0 current_allocation = 0 @@ -356,7 +435,9 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont print("{} bytes free".format(current_free * BYTES_PER_BLOCK)) current_free = 0 if block_state != AT_TAIL and current_allocation > 0: - save_allocated_block((i * BLOCKS_PER_ATB + j) * BYTES_PER_BLOCK, current_allocation) + save_allocated_block( + (i * BLOCKS_PER_ATB + j) * BYTES_PER_BLOCK, current_allocation + ) current_allocation = 0 if block_state == AT_FREE: current_free += 1 @@ -368,13 +449,13 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont # current_allocation > 0 ensures we only extend an allocation thats started. current_allocation += 1 longest_free = max(longest_free, current_free) - #if current_free > 0: + # if current_free > 0: # print("{} bytes free".format(current_free * BYTES_PER_BLOCK)) if current_allocation > 0: save_allocated_block(pool_length, current_allocation) def is_qstr(obj): - return obj & 0xff800007 == 0x00000006 + return obj & 0xFF800007 == 0x00000006 def find_qstr(qstr_index): pool_ptr = last_pool @@ -396,8 +477,10 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont return "missing" else: rom_offset = pool_ptr - rom_start - prev, total_prev_len, alloc, length = struct.unpack_from("= total_prev_len: offset = (qstr_index - total_prev_len) * 4 + 16 @@ -406,14 +489,14 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont start -= rom_start if start > len(rom): return "more than rom: {:x}".format(start + rom_start) - qstr_hash, qstr_len = struct.unpack(" heap_start + len(heap): return "out of range: {:x}".format(start) local = start - heap_start - qstr_hash, qstr_len = struct.unpack("{}{}".format( - cells[2*i][0], - cells[2*i][1], - cells[2*i+1][0], - cells[2*i+1][1]) + rows += '{}{}'.format( + cells[2 * i][0], cells[2 * i][1], cells[2 * i + 1][0], cells[2 * i + 1][1] + ) node.attr["shape"] = "plaintext" node.attr["style"] = "invisible" - node.attr["label"] = "<{}
0x{:08x}
>".format(block, rows) + node.attr[ + "label" + ] = '<{}
0x{:08x}
>'.format( + block, rows + ) for node, degree in ownership_graph.in_degree_iter(): print(node, degree) @@ -488,12 +577,12 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont print("Unable to find memory block for string at 0x{:08x}.".format(block)) continue try: - raw_string = block_data[block].decode('utf-8') + raw_string = block_data[block].decode("utf-8") except: raw_string = str(block_data[block]) wrapped = [] for i in range(0, len(raw_string), 16): - wrapped.append(raw_string[i:i+16]) + wrapped.append(raw_string[i : i + 16]) node.attr["label"] = "\n".join(wrapped) node.attr["style"] = "filled" node.attr["fontname"] = "FiraCode-Medium" @@ -516,17 +605,29 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont rows = "" remaining_bytecode = len(data) - 16 while code_info_size >= 16: - rows += "" + rows += ( + '' + ) code_info_size -= 16 remaining_bytecode -= 16 if code_info_size > 0: - rows += ("" - "" - ).format(code_info_size, code_info_size * (80 / 16), (16 - code_info_size), (80 / 16) * (16 - code_info_size)) + rows += ( + '' + '' + ).format( + code_info_size, + code_info_size * (80 / 16), + (16 - code_info_size), + (80 / 16) * (16 - code_info_size), + ) remaining_bytecode -= 16 for i in range(remaining_bytecode // 16): - rows += "" - node.attr["label"] = "<{}
0x{:08x}
>".format(block, rows) + rows += '' + node.attr[ + "label" + ] = '<{}
0x{:08x}
>'.format( + block, rows + ) for block in qstr_chunks: if block not in block_data: @@ -543,9 +644,11 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont continue offset += 2 + qstr_len + 1 try: - qstrs_in_chunk += " " + data[offset - qstr_len - 1: offset - 1].decode("utf-8") + qstrs_in_chunk += " " + data[offset - qstr_len - 1 : offset - 1].decode( + "utf-8" + ) except UnicodeDecodeError: - qstrs_in_chunk += " " + "â–‘"*qstr_len + qstrs_in_chunk += " " + "â–‘" * qstr_len printable_qstrs = "" for i in range(len(qstrs_in_chunk)): c = qstrs_in_chunk[i] @@ -555,9 +658,13 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont printable_qstrs += qstrs_in_chunk[i] wrapped = [] for i in range(0, len(printable_qstrs), 16): - wrapped.append(html.escape(printable_qstrs[i:i+16])) + wrapped.append(html.escape(printable_qstrs[i : i + 16])) node = ownership_graph.get_node(block) - node.attr["label"] = "<
0x{:08x}
{}
>".format(block, 18 * (len(wrapped) - 1), "
".join(wrapped)) + node.attr[ + "label" + ] = '<
0x{:08x}
{}
>'.format( + block, 18 * (len(wrapped) - 1), "
".join(wrapped) + ) node.attr["fontname"] = "FiraCode-Bold" if block >= long_lived_start: node.attr["fontcolor"] = "hotpink" @@ -598,10 +705,10 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont height = float(node.attr["height"]) except: height = 0.25 - #print(hex(address), "height", height, y) - #if address in block_data: + # print(hex(address), "height", height, y) + # if address in block_data: # print(hex(address), block, len(block_data[address]), x, y, height) - node.attr["pos"] = "{},{}".format(x * 80, (y - (height - 0.25) * 2) * 18) # in inches + node.attr["pos"] = "{},{}".format(x * 80, (y - (height - 0.25) * 2) * 18) # in inches # Reformat block nodes so they are the correct size and do not have keys in them. for block in sorted(map_element_blocks): @@ -609,45 +716,58 @@ def do_all_the_things(ram_filename, bin_filename, map_filename, print_block_cont node = ownership_graph.get_node(block) except KeyError: if block != 0: - print("Unable to find memory block for 0x{:08x}. Is there something running?".format(block)) + print( + "Unable to find memory block for 0x{:08x}. Is there something running?".format( + block + ) + ) continue - #node.attr["fillcolor"] = "gold" + # node.attr["fillcolor"] = "gold" if block not in block_data: continue data = block_data[block] - #print("0x{:08x}".format(block)) + # print("0x{:08x}".format(block)) cells = [] for i in range(len(data) // 8): key, value = struct.unpack_from("") + # print(" ") cells.append(("", " ")) else: - #print(" {}, {}".format(format(key), format(value))) + # print(" {}, {}".format(format(key), format(value))) cells.append((key, "")) # if value in block_data: # edge = ownership_graph.get_edge(block, value) # edge.attr["tailport"] = str(key) rows = "" for i in range(len(cells) // 2): - rows += "{}{}".format( - cells[2*i][0], - cells[2*i][1], - cells[2*i+1][0], - cells[2*i+1][1]) - node.attr["label"] = "<{}
>".format(rows) + rows += '{}{}'.format( + cells[2 * i][0], cells[2 * i][1], cells[2 * i + 1][0], cells[2 * i + 1][1] + ) + node.attr[ + "label" + ] = '<{}
>'.format( + rows + ) - - ownership_graph.add_node("center", pos="{},{}".format(total_width // 2 - 40, total_height // 2), shape="plaintext", label=" ") - ownership_graph.graph_attr["viewport"] = "{},{},1,{}".format(total_width, total_height, "center") + ownership_graph.add_node( + "center", + pos="{},{}".format(total_width // 2 - 40, total_height // 2), + shape="plaintext", + label=" ", + ) + ownership_graph.graph_attr["viewport"] = "{},{},1,{}".format( + total_width, total_height, "center" + ) ownership_graph.has_layout = True if draw_heap_layout: fn = os.path.join(output_directory, "heap_layout{:04d}.png".format(snapshot_num)) print(fn) - #ownership_graph.write(fn+".dot") + # ownership_graph.write(fn+".dot") ownership_graph.draw(fn) + if __name__ == "__main__": do_all_the_things() diff --git a/tools/analyze_mpy.py b/tools/analyze_mpy.py index 99c06f62ad..8c2056e030 100755 --- a/tools/analyze_mpy.py +++ b/tools/analyze_mpy.py @@ -10,219 +10,129 @@ import io bytecode_format_sizes = { "MP_OPCODE_BYTE": 1, "MP_OPCODE_QSTR": 3, - "MP_OPCODE_VAR_UINT": None, # Unknown because uint encoding uses the top bit to indicate the end. + "MP_OPCODE_VAR_UINT": None, # Unknown because uint encoding uses the top bit to indicate the end. "MP_OPCODE_OFFSET": 3, "MP_OPCODE_BYTE_EXTRA": 2, "MP_OPCODE_VAR_UINT_EXTRA": None, - "MP_OPCODE_OFFSET_EXTRA": 4 + "MP_OPCODE_OFFSET_EXTRA": 4, } bytecodes = { - 0x00: {"name": "MP_BC_LOAD_FAST_MULTI", - "format": "MP_OPCODE_BYTE"}, - 0x10: {"name": "MP_BC_LOAD_CONST_FALSE", - "format": "MP_OPCODE_BYTE"}, - 0x11: {"name": "MP_BC_LOAD_CONST_NONE", - "format": "MP_OPCODE_BYTE"}, - 0x12: {"name": "MP_BC_LOAD_CONST_TRUE", - "format": "MP_OPCODE_BYTE"}, - 0x14: {"name": "MP_BC_LOAD_CONST_SMALL_INT", - "format": "MP_OPCODE_VAR_UINT"}, - 0x16: {"name": "MP_BC_LOAD_CONST_STRING", - "format": "MP_OPCODE_QSTR"}, - 0x17: {"name": "MP_BC_LOAD_CONST_OBJ", - "format": "MP_OPCODE_VAR_UINT"}, -#define MP_BC_LOAD_CONST_OBJ (0x17) // ptr - 0x18: {"name": "MP_BC_LOAD_NULL", - "format": "MP_OPCODE_BYTE"}, - -#define MP_BC_LOAD_FAST_N (0x19) // uint - 0x1a: {"name": "MP_BC_LOAD_DEREF", - "format": "MP_OPCODE_VAR_UINT"}, - 0x1b: {"name": "MP_BC_LOAD_NAME", - "format": "MP_OPCODE_QSTR"}, - 0x1c: {"name": "MP_BC_LOAD_GLOBAL", - "format": "MP_OPCODE_QSTR"}, - 0x1d: {"name": "MP_BC_LOAD_ATTR", - "format": "MP_OPCODE_QSTR"}, - 0x1e: {"name": "MP_BC_LOAD_METHOD", - "format": "MP_OPCODE_QSTR"}, - 0x1f: {"name": "MP_BC_LOAD_SUPER_METHOD", - "format": "MP_OPCODE_QSTR"}, - 0x20: {"name": "MP_BC_LOAD_BUILD_CLASS", - "format": "MP_OPCODE_BYTE"}, -#define MP_BC_LOAD_BUILD_CLASS (0x20) -#define MP_BC_LOAD_SUBSCR (0x21) - 0x21: {"name": "MP_BC_LOAD_SUBSCR", - "format": "MP_OPCODE_BYTE"}, - -#define MP_BC_STORE_FAST_N (0x22) // uint -#define MP_BC_STORE_DEREF (0x23) // uint -#define MP_BC_STORE_NAME (0x24) // qstr - 0x24: {"name": "MP_BC_STORE_NAME", - "format": "MP_OPCODE_QSTR"}, - 0x25: {"name": "MP_BC_STORE_GLOBAL", - "format": "MP_OPCODE_QSTR"}, - 0x26: {"name": "MP_BC_STORE_ATTR", - "format": "MP_OPCODE_QSTR"}, - 0x27: {"name": "MP_BC_LOAD_SUBSCR", - "format": "MP_OPCODE_BYTE"}, - - 0x28: {"name": "MP_BC_DELETE_FAST", - "format": "MP_OPCODE_VAR_UINT"}, -#define MP_BC_DELETE_FAST (0x28) // uint -#define MP_BC_DELETE_DEREF (0x29) // uint -#define MP_BC_DELETE_NAME (0x2a) // qstr -#define MP_BC_DELETE_GLOBAL (0x2b) // qstr - - 0x30: {"name": "MP_BC_DUP_TOP", - "format": "MP_OPCODE_BYTE"}, -#define MP_BC_DUP_TOP_TWO (0x31) - 0x32: {"name": "MP_BC_POP_TOP", - "format": "MP_OPCODE_BYTE"}, - 0x33: {"name": "MP_BC_ROT_TWO", - "format": "MP_OPCODE_BYTE"}, - 0x34: {"name": "MP_BC_ROT_THREE", - "format": "MP_OPCODE_BYTE"}, - - 0x35: {"name": "MP_BC_JUMP", - "format": "MP_OPCODE_OFFSET"}, - 0x36: {"name": "MP_BC_POP_JUMP_IF_TRUE", - "format": "MP_OPCODE_OFFSET"}, - 0x37: {"name": "MP_BC_POP_JUMP_IF_FALSE", - "format": "MP_OPCODE_OFFSET"}, -#define MP_BC_JUMP_IF_TRUE_OR_POP (0x38) // rel byte code offset, 16-bit signed, in excess -#define MP_BC_JUMP_IF_FALSE_OR_POP (0x39) // rel byte code offset, 16-bit signed, in excess -#define MP_BC_SETUP_WITH (0x3d) // rel byte code offset, 16-bit unsigned -#define MP_BC_WITH_CLEANUP (0x3e) -#define MP_BC_SETUP_EXCEPT (0x3f) // rel byte code offset, 16-bit unsigned -#define MP_BC_SETUP_FINALLY (0x40) // rel byte code offset, 16-bit unsigned -#define MP_BC_END_FINALLY (0x41) -#define MP_BC_GET_ITER (0x42) -#define MP_BC_FOR_ITER (0x43) // rel byte code offset, 16-bit unsigned - 0x43: {"name": "MP_BC_FOR_ITER", - "format": "MP_OPCODE_OFFSET"}, - - 0x44: {"name": "MP_BC_POP_BLOCK", - "format": "MP_OPCODE_BYTE"}, -#define MP_BC_POP_EXCEPT (0x45) -#define MP_BC_UNWIND_JUMP (0x46) // rel byte code offset, 16-bit signed, in excess; then a byte - 0x47: {"name": "MP_BC_GET_ITER_STACK", - "format": "MP_OPCODE_BYTE"}, - - - 0x50: {"name": "MP_BC_BUILD_TUPLE", - "format": "MP_OPCODE_VAR_UINT"}, - 0x51: {"name": "MP_BC_BUILD_LIST", - "format": "MP_OPCODE_VAR_UINT"}, - 0x53: {"name": "MP_BC_BUILD_MAP", - "format": "MP_OPCODE_VAR_UINT"}, - 0x54: {"name": "MP_BC_STORE_MAP", - "format": "MP_OPCODE_BYTE"}, -#define MP_BC_BUILD_SET (0x56) // uint -#define MP_BC_BUILD_SLICE (0x58) // uint -#define MP_BC_STORE_COMP (0x57) // uint - 0x57: {"name": "MP_BC_STORE_COMP", - "format": "MP_OPCODE_VAR_UINT"}, -#define MP_BC_UNPACK_SEQUENCE (0x59) // uint -#define MP_BC_UNPACK_EX (0x5a) // uint - - 0x5b: {"name": "MP_BC_RETURN_VALUE", - "format": "MP_OPCODE_BYTE"}, - 0x5c: {"name": "MP_BC_RAISE_VARARGS", - "format": "MP_OPCODE_BYTE_EXTRA"}, -#define MP_BC_YIELD_VALUE (0x5d) -#define MP_BC_YIELD_FROM (0x5e) - -#define MP_BC_MAKE_FUNCTION (0x60) // uint - 0x60: {"name": "MP_BC_MAKE_FUNCTION", - "format": "MP_OPCODE_VAR_UINT"}, - 0x61: {"name": "MP_BC_MAKE_FUNCTION_DEFARGS", - "format": "MP_OPCODE_VAR_UINT"}, - 0x62: {"name": "MP_BC_MAKE_CLOSURE", - "format": "MP_OPCODE_VAR_UINT_EXTRA"}, - 0x63: {"name": "MP_BC_MAKE_CLOSURE", - "format": "MP_OPCODE_VAR_UINT_EXTRA"}, - 0x64: {"name": "MP_BC_CALL_FUNCTION", - "format": "MP_OPCODE_VAR_UINT"}, - 0x65: {"name": "MP_BC_CALL_FUNCTION_VAR_KW", - "format": "MP_OPCODE_VAR_UINT"}, - 0x66: {"name": "MP_BC_CALL_METHOD", - "format": "MP_OPCODE_VAR_UINT"}, - 0x67: {"name": "MP_BC_CALL_METHOD_VAR_KW", - "format": "MP_OPCODE_VAR_UINT"}, - - 0x68: {"name": "MP_BC_IMPORT_NAME", - "format": "MP_OPCODE_QSTR"}, - 0x69: {"name": "MP_BC_IMPORT_FROM", - "format": "MP_OPCODE_QSTR"}, -#define MP_BC_IMPORT_FROM (0x69) // qstr -#define MP_BC_IMPORT_STAR (0x6a) - -#define MP_BC_LOAD_CONST_SMALL_INT_MULTI (0x70) // + N(64) - 0x7f: {"name": "MP_BC_LOAD_CONST_SMALL_INT_MULTI -1", - "format": "MP_OPCODE_BYTE"}, - 0x80: {"name": "MP_BC_LOAD_CONST_SMALL_INT_MULTI 0", - "format": "MP_OPCODE_BYTE"}, - 0x81: {"name": "MP_BC_LOAD_CONST_SMALL_INT_MULTI 1", - "format": "MP_OPCODE_BYTE"}, - 0x82: {"name": "MP_BC_LOAD_CONST_SMALL_INT_MULTI 2", - "format": "MP_OPCODE_BYTE"}, - 0x83: {"name": "MP_BC_LOAD_CONST_SMALL_INT_MULTI 3", - "format": "MP_OPCODE_BYTE"}, - 0x84: {"name": "MP_BC_LOAD_CONST_SMALL_INT_MULTI 4", - "format": "MP_OPCODE_BYTE"}, -#define MP_BC_LOAD_FAST_MULTI (0xb0) // + N(16) - 0xb0: {"name": "MP_BC_LOAD_FAST_MULTI 0", - "format": "MP_OPCODE_BYTE"}, - 0xb1: {"name": "MP_BC_LOAD_FAST_MULTI 1", - "format": "MP_OPCODE_BYTE"}, - 0xb2: {"name": "MP_BC_LOAD_FAST_MULTI 2", - "format": "MP_OPCODE_BYTE"}, - 0xb3: {"name": "MP_BC_LOAD_FAST_MULTI 3", - "format": "MP_OPCODE_BYTE"}, - 0xb4: {"name": "MP_BC_LOAD_FAST_MULTI 4", - "format": "MP_OPCODE_BYTE"}, - 0xb5: {"name": "MP_BC_LOAD_FAST_MULTI 5", - "format": "MP_OPCODE_BYTE"}, - 0xb6: {"name": "MP_BC_LOAD_FAST_MULTI 6", - "format": "MP_OPCODE_BYTE"}, - 0xb7: {"name": "MP_BC_LOAD_FAST_MULTI 7", - "format": "MP_OPCODE_BYTE"}, - 0xb8: {"name": "MP_BC_LOAD_FAST_MULTI 8", - "format": "MP_OPCODE_BYTE"}, -#define MP_BC_STORE_FAST_MULTI (0xc0) // + N(16) - 0xc0: {"name": "MP_BC_STORE_FAST_MULTI 0", - "format": "MP_OPCODE_BYTE"}, - 0xc1: {"name": "MP_BC_STORE_FAST_MULTI 1", - "format": "MP_OPCODE_BYTE"}, - 0xc2: {"name": "MP_BC_STORE_FAST_MULTI 2", - "format": "MP_OPCODE_BYTE"}, - 0xc3: {"name": "MP_BC_STORE_FAST_MULTI 3", - "format": "MP_OPCODE_BYTE"}, - 0xc4: {"name": "MP_BC_STORE_FAST_MULTI 4", - "format": "MP_OPCODE_BYTE"}, - 0xc5: {"name": "MP_BC_STORE_FAST_MULTI 5", - "format": "MP_OPCODE_BYTE"}, - 0xc6: {"name": "MP_BC_STORE_FAST_MULTI 6", - "format": "MP_OPCODE_BYTE"}, - 0xc7: {"name": "MP_BC_STORE_FAST_MULTI 7", - "format": "MP_OPCODE_BYTE"}, -#define MP_BC_UNARY_OP_MULTI (0xd0) // + op(> 8 + bytecode[i + 1] = qstr_index + bytecode[i + 2] = qstr_index >> 8 if not opcode_size: i += 2 while (bytecode[i] & 0x80) != 0: @@ -404,17 +311,19 @@ class RawCode: else: i += opcode_size + class mpyFile: def __init__(self, encoded_mpy): # this matches mp-raw_code_save in py/persistentcode.c first_byte = encoded_mpy.read(1) - if first_byte != b'M': + if first_byte != b"M": raise ValueError("Not a valid first byte. Should be 'M' but is {}".format(first_byte)) self.version = encoded_mpy.read(1)[0] self.feature_flags = encoded_mpy.read(1)[0] self.small_int_bits = encoded_mpy.read(1)[0] self.raw_code = RawCode(encoded_mpy) + if __name__ == "__main__": with open(sys.argv[1], "rb") as f: mpy = mpyFile(f) diff --git a/tools/build_board_info.py b/tools/build_board_info.py index 70d5e2bc7a..30246bd17f 100644 --- a/tools/build_board_info.py +++ b/tools/build_board_info.py @@ -125,9 +125,7 @@ def get_version_info(): version = None sha = git("rev-parse", "--short", "HEAD").stdout.decode("utf-8") try: - version = ( - git("describe", "--tags", "--exact-match").stdout.decode("utf-8").strip() - ) + version = git("describe", "--tags", "--exact-match").stdout.decode("utf-8").strip() except sh.ErrorReturnCode_128: # No exact match pass @@ -191,9 +189,7 @@ def create_pr(changes, updated, git_info, user): ) create_branch = {"ref": "refs/heads/" + branch_name, "sha": commit_sha} - response = github.post( - "/repos/{}/circuitpython-org/git/refs".format(user), json=create_branch - ) + response = github.post("/repos/{}/circuitpython-org/git/refs".format(user), json=create_branch) if not response.ok and response.json()["message"] != "Reference already exists": print("unable to create branch") print(response.text) @@ -207,8 +203,7 @@ def create_pr(changes, updated, git_info, user): } response = github.put( - "/repos/{}/circuitpython-org/contents/_data/files.json".format(user), - json=update_file, + "/repos/{}/circuitpython-org/contents/_data/files.json".format(user), json=update_file ) if not response.ok: print("unable to post new file") @@ -257,9 +252,7 @@ def generate_download_info(): languages = get_languages() - support_matrix = shared_bindings_matrix.support_matrix_by_board( - use_branded_name=False - ) + support_matrix = shared_bindings_matrix.support_matrix_by_board(use_branded_name=False) new_stable = "-" not in new_tag diff --git a/tools/build_memory_info.py b/tools/build_memory_info.py index 89aedf0f40..722c548a1c 100644 --- a/tools/build_memory_info.py +++ b/tools/build_memory_info.py @@ -9,11 +9,11 @@ import re import sys # Handle size constants with K or M suffixes (allowed in .ld but not in Python). -K_PATTERN = re.compile(r'([0-9]+)[kK]') -K_REPLACE = r'(\1*1024)' +K_PATTERN = re.compile(r"([0-9]+)[kK]") +K_REPLACE = r"(\1*1024)" -M_PATTERN = re.compile(r'([0-9]+)[mM]') -M_REPLACE = r'(\1*1024*1024)' +M_PATTERN = re.compile(r"([0-9]+)[mM]") +M_REPLACE = r"(\1*1024*1024)" print() @@ -51,8 +51,16 @@ used_flash = data + text free_flash = firmware_region - used_flash used_ram = data + bss free_ram = ram_region - used_ram -print("{} bytes used, {} bytes free in flash firmware space out of {} bytes ({}kB).".format(used_flash, free_flash, firmware_region, firmware_region / 1024)) -print("{} bytes used, {} bytes free in ram for stack and heap out of {} bytes ({}kB).".format(used_ram, free_ram, ram_region, ram_region / 1024)) +print( + "{} bytes used, {} bytes free in flash firmware space out of {} bytes ({}kB).".format( + used_flash, free_flash, firmware_region, firmware_region / 1024 + ) +) +print( + "{} bytes used, {} bytes free in ram for stack and heap out of {} bytes ({}kB).".format( + used_ram, free_ram, ram_region, ram_region / 1024 + ) +) print() # Check that we have free flash space. GCC doesn't fail when the text + data diff --git a/tools/build_release_files.py b/tools/build_release_files.py index dc6c094c0a..4e22e97254 100755 --- a/tools/build_release_files.py +++ b/tools/build_release_files.py @@ -17,7 +17,7 @@ for port in build_info.SUPPORTED_PORTS: PARALLEL = "-j 5" if "GITHUB_ACTION" in os.environ: - PARALLEL="-j 2" + PARALLEL = "-j 2" all_boards = build_info.get_board_mapping() build_boards = list(all_boards.keys()) @@ -27,12 +27,27 @@ if "BOARDS" in os.environ: sha, version = build_info.get_version_info() languages = build_info.get_languages() -language_allow_list = ['ID', 'de_DE', 'en_US', 'en_x_pirate', 'es', 'fil', 'fr', 'it_IT', 'ja', 'nl', 'pl', 'pt_BR', 'sv', 'zh_Latn_pinyin'] -print('Note: Not building languages', set(languages) - set(language_allow_list)) +language_allow_list = [ + "ID", + "de_DE", + "en_US", + "en_x_pirate", + "es", + "fil", + "fr", + "it_IT", + "ja", + "nl", + "pl", + "pt_BR", + "sv", + "zh_Latn_pinyin", +] +print("Note: Not building languages", set(languages) - set(language_allow_list)) exit_status = 0 cores = multiprocessing.cpu_count() -print('building boards with parallelism {}'.format(cores)) +print("building boards with parallelism {}".format(cores)) for board in build_boards: bin_directory = "../bin/{}/".format(board) os.makedirs(bin_directory, exist_ok=True) @@ -48,8 +63,12 @@ for board in build_boards: # CFLAGS_INLINE_LIMIT is set for a particular language to make it fit. clean_build_check_result = subprocess.run( "make -C ../ports/{port} TRANSLATION={language} BOARD={board} check-release-needs-clean-build -j {cores} | fgrep 'RELEASE_NEEDS_CLEAN_BUILD = 1'".format( - port = board_info["port"], language=language, board=board, cores=cores), - shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + port=board_info["port"], language=language, board=board, cores=cores + ), + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) clean_build = clean_build_check_result.returncode == 0 build_dir = "build-{board}".format(board=board) @@ -58,8 +77,16 @@ for board in build_boards: make_result = subprocess.run( "make -C ../ports/{port} TRANSLATION={language} BOARD={board} BUILD={build} -j {cores}".format( - port = board_info["port"], language=language, board=board, build=build_dir, cores=cores), - shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + port=board_info["port"], + language=language, + board=board, + build=build_dir, + cores=cores, + ), + shell=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) build_duration = time.monotonic() - start_time success = "\033[32msucceeded\033[0m" @@ -71,13 +98,14 @@ for board in build_boards: for extension in board_info["extensions"]: temp_filename = "../ports/{port}/{build}/firmware.{extension}".format( - port=board_info["port"], build=build_dir, extension=extension) + port=board_info["port"], build=build_dir, extension=extension + ) for alias in board_info["aliases"] + [board]: - bin_directory = "../bin/{alias}/{language}".format( - alias=alias, language=language) + bin_directory = "../bin/{alias}/{language}".format(alias=alias, language=language) os.makedirs(bin_directory, exist_ok=True) final_filename = "adafruit-circuitpython-{alias}-{language}-{version}.{extension}".format( - alias=alias, language=language, version=version, extension=extension) + alias=alias, language=language, version=version, extension=extension + ) final_filename = os.path.join(bin_directory, final_filename) try: shutil.copyfile(temp_filename, final_filename) @@ -86,9 +114,15 @@ for board in build_boards: if exit_status == 0: exit_status = 1 - print("Build {board} for {language}{clean_build} took {build_duration:.2f}s and {success}".format( - board=board, language=language, clean_build=(" (clean_build)" if clean_build else ""), - build_duration=build_duration, success=success)) + print( + "Build {board} for {language}{clean_build} took {build_duration:.2f}s and {success}".format( + board=board, + language=language, + clean_build=(" (clean_build)" if clean_build else ""), + build_duration=build_duration, + success=success, + ) + ) print(make_result.stdout.decode("utf-8")) print(other_output) diff --git a/tools/chart_code_size.py b/tools/chart_code_size.py index f75269130f..2328edd72f 100644 --- a/tools/chart_code_size.py +++ b/tools/chart_code_size.py @@ -12,15 +12,15 @@ import sh # Replace dashes with underscores objdump = sh.arm_none_eabi_objdump + def parse_hex(h): return int("0x" + h, 0) + BAD_JUMPS = ["UNPREDICTABLE", "_etext"] -SPECIAL_NODE_COLORS = { - "main": "pink", - "exception_table": "green" -} +SPECIAL_NODE_COLORS = {"main": "pink", "exception_table": "green"} + @click.command() @click.argument("elf_filename") @@ -60,7 +60,17 @@ def do_all_the_things(elf_filename): pass else: symbols_by_memory_address[symbol["start_address"]] = symbol - elif symbol["debug_type"] in ["DW_TAG_member", "DW_TAG_label", "DW_TAG_typedef", "DW_TAG_enumerator", "DW_TAG_enumeration_type", "DW_TAG_base_type", "DW_TAG_structure_type", "DW_TAG_compile_unit", "DW_TAG_union_type"]: + elif symbol["debug_type"] in [ + "DW_TAG_member", + "DW_TAG_label", + "DW_TAG_typedef", + "DW_TAG_enumerator", + "DW_TAG_enumeration_type", + "DW_TAG_base_type", + "DW_TAG_structure_type", + "DW_TAG_compile_unit", + "DW_TAG_union_type", + ]: # skip symbols that don't end up in memory. the type info is available through the debug address map pass else: @@ -71,7 +81,11 @@ def do_all_the_things(elf_filename): # print() pass all_symbols[symbol["name"]] = symbol - elif symbol and symbol["debug_type"] == "DW_TAG_GNU_call_site_parameter" and "call_site_value" in symbol: + elif ( + symbol + and symbol["debug_type"] == "DW_TAG_GNU_call_site_parameter" + and "call_site_value" in symbol + ): parent = -1 while symbol_stack[parent]["debug_type"] != "DW_TAG_subprogram": parent -= 1 @@ -144,10 +158,10 @@ def do_all_the_things(elf_filename): symbol["call_site_value"] = parse_hex(parts[-1].strip(")")) else: symbol["other"].append(line) - #print(parts) + # print(parts) pass else: - #print(line) + # print(line) pass MEMORY_NONE = 0 @@ -162,10 +176,16 @@ def do_all_the_things(elf_filename): def get_pointer_map(t, depth=0): if t["debug_type"] == "DW_TAG_pointer_type": return {0: MEMORY_POINTER} - elif t["debug_type"] in ["DW_TAG_const_type", "DW_TAG_typedef", "DW_TAG_member", "DW_TAG_subrange_type", "DW_TAG_volatile_type"]: + elif t["debug_type"] in [ + "DW_TAG_const_type", + "DW_TAG_typedef", + "DW_TAG_member", + "DW_TAG_subrange_type", + "DW_TAG_volatile_type", + ]: if "name" in t and t["name"] == "mp_rom_obj_t": return {0: MEMORY_PY_OBJECT} - return get_pointer_map(symbols_by_debug_address[t["type"]], depth+1) + return get_pointer_map(symbols_by_debug_address[t["type"]], depth + 1) elif t["debug_type"] in ["DW_TAG_base_type", "DW_TAG_enumeration_type"]: return {} elif t["debug_type"] == "DW_TAG_union_type": @@ -181,7 +201,7 @@ def do_all_the_things(elf_filename): return combined_map elif "subtype" in t: subtype = symbols_by_debug_address[t["type"]] - pmap = get_pointer_map(subtype, depth+1) + pmap = get_pointer_map(subtype, depth + 1) size = get_size(subtype) expanded_map = {} for i in range(t["maxlen"]): @@ -216,11 +236,11 @@ def do_all_the_things(elf_filename): elif t_symbol["debug_type"] == "DW_TAG_volatile_type": type_string.append("volatile") else: - #print(" ", t_symbol) + # print(" ", t_symbol) pass type_string.reverse() symbol["type_string"] = " ".join(type_string) - #print(symbol_name, symbol["debug_type"], symbol.get("type_string", "")) + # print(symbol_name, symbol["debug_type"], symbol.get("type_string", "")) # print() # print() @@ -263,13 +283,17 @@ def do_all_the_things(elf_filename): elif symbol_name not in all_symbols: if symbol_name == "nlr_push_tail_var": fake_type = all_symbols["mp_obj_get_type"]["type"] - symbol = {"debug_type": "DW_TAG_variable", "name": symbol_name, "type": fake_type} + symbol = { + "debug_type": "DW_TAG_variable", + "name": symbol_name, + "type": fake_type, + } else: print(line) print(symbol_name, symbol_address) symbol = {"debug_type": "DW_TAG_subprogram", "name": symbol_name} all_symbols[symbol_name] = symbol - #raise RuntimeError() + # raise RuntimeError() symbol = all_symbols[symbol_name] symbol["start_address"] = symbol_address @@ -292,13 +316,13 @@ def do_all_the_things(elf_filename): offset = last_address - symbol["start_address"] if "pointer_map" in symbol: if offset not in symbol["pointer_map"]: - #print(offset, symbol) + # print(offset, symbol) pass else: ref = parse_hex(parts[1]) pointer_style = symbol["pointer_map"][offset] if pointer_style == MEMORY_POINTER: - symbol["outgoing_pointers"].add(ref & 0xfffffffe) + symbol["outgoing_pointers"].add(ref & 0xFFFFFFFE) elif pointer_style == MEMORY_PY_OBJECT and ref & 0x3 == 0: symbol["outgoing_pointers"].add(ref) if len(parts[1]) == 8 and parts[1][0] == "0": @@ -315,7 +339,7 @@ def do_all_the_things(elf_filename): print(symbol) if jump_to != symbol["name"] and jump_to not in BAD_JUMPS: symbol["outgoing_jumps"].add(jump_to) - #print(symbol_name, jump_to) + # print(symbol_name, jump_to) if jump_to == "_etext": print(line) elif "UNDEFINED" in line: @@ -325,7 +349,7 @@ def do_all_the_things(elf_filename): else: print(line) else: - #print(line) + # print(line) pass # print() @@ -344,7 +368,7 @@ def do_all_the_things(elf_filename): for outgoing in symbol["outgoing_pointers"]: if outgoing in symbols_by_memory_address: outgoing = symbols_by_memory_address[outgoing] - #print(outgoing) + # print(outgoing) if outgoing["debug_type"] in ["DW_TAG_GNU_call_site", "DW_TAG_lexical_block"]: continue if outgoing["name"] == "audioio_wavefile_type": @@ -359,25 +383,25 @@ def do_all_the_things(elf_filename): if "outgoing_jumps" in symbol: for outgoing in symbol["outgoing_jumps"]: if outgoing not in all_symbols: - #print(outgoing, symbol_name) + # print(outgoing, symbol_name) continue - #print(all_symbols[outgoing], symbol_name) + # print(all_symbols[outgoing], symbol_name) referenced_symbol = all_symbols[outgoing] if "incoming_jumps" not in referenced_symbol: - #print(symbol_name, "->", outgoing) + # print(symbol_name, "->", outgoing) referenced_symbol["incoming_jumps"] = set() referenced_symbol["incoming_jumps"].add(symbol_name) if "outgoing_pointers" in symbol: for outgoing in symbol["outgoing_pointers"]: if outgoing not in all_symbols: - #print(outgoing, symbol_name) + # print(outgoing, symbol_name) continue - #print(all_symbols[outgoing], symbol_name) + # print(all_symbols[outgoing], symbol_name) referenced_symbol = all_symbols[outgoing] if "incoming_pointers" not in referenced_symbol: - #print(symbol_name, "->", outgoing) + # print(symbol_name, "->", outgoing) referenced_symbol["incoming_pointers"] = set() referenced_symbol["incoming_pointers"].add(symbol_name) @@ -395,8 +419,10 @@ def do_all_the_things(elf_filename): # print(" ", len(symbol["outgoing_pointers"]), "ptrs") # if i > 3000: # break - if ("incoming_jumps" not in symbol or len(symbol["incoming_jumps"]) == 0) and ("incoming_pointers" not in symbol or len(symbol["incoming_pointers"]) == 0): - #print(symbol_name) + if ("incoming_jumps" not in symbol or len(symbol["incoming_jumps"]) == 0) and ( + "incoming_pointers" not in symbol or len(symbol["incoming_pointers"]) == 0 + ): + # print(symbol_name) continue if "start_address" not in symbol: continue @@ -407,7 +433,7 @@ def do_all_the_things(elf_filename): if "outgoing_pointers" in symbol: for outgoing in symbol["outgoing_pointers"]: callgraph.add_edge(symbol_name, outgoing, color="red") - #print(symbol_name, symbol) + # print(symbol_name, symbol) # Style all of the nodes print("styling") @@ -454,5 +480,6 @@ def do_all_the_things(elf_filename): print(fn) callgraph.draw(fn) + if __name__ == "__main__": do_all_the_things() diff --git a/tools/ci_check_duplicate_usb_vid_pid.py b/tools/ci_check_duplicate_usb_vid_pid.py index cb4efc5f11..33260eb390 100644 --- a/tools/ci_check_duplicate_usb_vid_pid.py +++ b/tools/ci_check_duplicate_usb_vid_pid.py @@ -46,7 +46,7 @@ DEFAULT_IGNORELIST = [ "cp32-m4", "metro_m4_express", "unexpectedmaker_feathers2", - "unexpectedmaker_feathers2_prerelease" + "unexpectedmaker_feathers2_prerelease", ] cli_parser = argparse.ArgumentParser(description="USB VID/PID Duplicate Checker") @@ -60,27 +60,28 @@ cli_parser.add_argument( "Board names to ignore duplicate VID/PID combinations. Pass an empty " "string to disable all duplicate ignoring. Defaults are: " f"{', '.join(DEFAULT_IGNORELIST)}" - ) + ), ) -def configboard_files(): - """ A pathlib glob search for all ports/*/boards/*/mpconfigboard.mk file - paths. - :returns: A ``pathlib.Path.glob()`` genarator object +def configboard_files(): + """A pathlib glob search for all ports/*/boards/*/mpconfigboard.mk file + paths. + + :returns: A ``pathlib.Path.glob()`` genarator object """ working_dir = pathlib.Path().resolve() if not working_dir.name.startswith("circuitpython"): raise RuntimeError( - "Please run USB VID/PID duplicate verification at the " - "top-level directory." + "Please run USB VID/PID duplicate verification at the " "top-level directory." ) return working_dir.glob("ports/**/boards/**/mpconfigboard.mk") + def check_vid_pid(files, ignorelist): - """ Compiles a list of USB VID & PID values for all boards, and checks - for duplicates. Exits with ``sys.exit()`` (non-zero exit code) - if duplicates are found, and lists the duplicates. + """Compiles a list of USB VID & PID values for all boards, and checks + for duplicates. Exits with ``sys.exit()`` (non-zero exit code) + if duplicates are found, and lists the duplicates. """ duplicates_found = False @@ -106,24 +107,18 @@ def check_vid_pid(files, ignorelist): if usb_vid and usb_pid: id_group = f"{usb_vid.group(1)}:{usb_pid.group(1)}" if id_group not in usb_ids: - usb_ids[id_group] = { - "boards": [board_name], - "duplicate": False - } + usb_ids[id_group] = {"boards": [board_name], "duplicate": False} else: - usb_ids[id_group]['boards'].append(board_name) + usb_ids[id_group]["boards"].append(board_name) if not board_ignorelisted: - usb_ids[id_group]['duplicate'] = True + usb_ids[id_group]["duplicate"] = True duplicates_found = True if duplicates_found: duplicates = "" for key, value in usb_ids.items(): if value["duplicate"]: - duplicates += ( - f"- VID/PID: {key}\n" - f" Boards: {', '.join(value['boards'])}\n" - ) + duplicates += f"- VID/PID: {key}\n" f" Boards: {', '.join(value['boards'])}\n" duplicate_message = ( f"Duplicate VID/PID usage found!\n{duplicates}\n" @@ -139,10 +134,7 @@ if __name__ == "__main__": arguments = cli_parser.parse_args() print("Running USB VID/PID Duplicate Checker...") - print( - f"Ignoring the following boards: {', '.join(arguments.ignorelist)}", - end="\n\n" - ) + print(f"Ignoring the following boards: {', '.join(arguments.ignorelist)}", end="\n\n") board_files = configboard_files() check_vid_pid(board_files, arguments.ignorelist) diff --git a/tools/ci_new_boards_check.py b/tools/ci_new_boards_check.py index 86010bad3e..3b41c8d67b 100644 --- a/tools/ci_new_boards_check.py +++ b/tools/ci_new_boards_check.py @@ -11,17 +11,19 @@ import yaml import build_board_info -workflow_file = '.github/workflows/build.yml' +workflow_file = ".github/workflows/build.yml" # Get boards in json format boards_info_json = build_board_info.get_board_mapping() # Get all the boards out of the json format -info_boards = [board for board in boards_info_json.keys() if not boards_info_json[board].get("alias", False)] +info_boards = [ + board for board in boards_info_json.keys() if not boards_info_json[board].get("alias", False) +] # We need to know the path of the workflow file base_path = os.path.dirname(__file__) -yml_path = os.path.abspath(os.path.join(base_path, '..', workflow_file)) +yml_path = os.path.abspath(os.path.join(base_path, "..", workflow_file)) # Loading board list based on build jobs in the workflow file. ci_boards = [] @@ -34,8 +36,8 @@ for job in workflow["jobs"]: continue job_boards = workflow["jobs"][job]["strategy"]["matrix"]["board"] if job_boards != sorted(job_boards): - print("Boards for job \"{}\" not sorted. Must be:".format(job)) - print(" - \"" + "\"\n - \"".join(sorted(job_boards)) + "\"") + print('Boards for job "{}" not sorted. Must be:'.format(job)) + print(' - "' + '"\n - "'.join(sorted(job_boards)) + '"') ok = False ci_boards.extend(job_boards) @@ -47,7 +49,7 @@ missing_boards = set(info_boards) - set(ci_boards) if missing_boards: ok = False - print('Boards missing in {}:'.format(workflow_file)) + print("Boards missing in {}:".format(workflow_file)) for board in missing_boards: print(board) diff --git a/tools/codeformat.py b/tools/codeformat.py index 42b43b6618..389bda8772 100644 --- a/tools/codeformat.py +++ b/tools/codeformat.py @@ -71,10 +71,7 @@ TOP = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) UNCRUSTIFY_CFG = os.path.join(TOP, "tools/uncrustify.cfg") -C_EXTS = ( - ".c", - ".h", -) +C_EXTS = (".c", ".h") PY_EXTS = (".py",) diff --git a/tools/convert_release_notes.py b/tools/convert_release_notes.py index 797e71834b..964a7fc376 100644 --- a/tools/convert_release_notes.py +++ b/tools/convert_release_notes.py @@ -16,13 +16,14 @@ html = mistune.create_markdown() print() print("HTML") print("=====================================") -print("From the GitHub release page:\n
") +print('From the GitHub release page:\n
') print(html(source)) print("
") + class AdafruitBBCodeRenderer(mistune.renderers.BaseRenderer): def placeholder(self): - return '' + return "" def paragraph(self, text): return text + "\n\n" @@ -63,6 +64,7 @@ class AdafruitBBCodeRenderer(mistune.renderers.BaseRenderer): def strong(self, text): return "[i]{}[/i]".format(text) + bbcode = mistune.create_markdown(renderer=AdafruitBBCodeRenderer()) print() diff --git a/tools/cpboard.py b/tools/cpboard.py index 464be4ba44..647a3ddc5a 100644 --- a/tools/cpboard.py +++ b/tools/cpboard.py @@ -100,9 +100,7 @@ class REPL: # Use read() since serial.reset_input_buffer() fails with termios.error now and then self.read() self.session = b"" - self.write( - b"\r" + REPL.CHAR_CTRL_C + REPL.CHAR_CTRL_C - ) # interrupt any running program + self.write(b"\r" + REPL.CHAR_CTRL_C + REPL.CHAR_CTRL_C) # interrupt any running program self.write(b"\r" + REPL.CHAR_CTRL_B) # enter or reset friendly repl data = self.read_until(b">>> ") @@ -158,11 +156,7 @@ class Disk: self.mountpoint = None with open("/etc/mtab", "r") as f: mtab = f.read() - mount = [ - mount.split(" ") - for mount in mtab.splitlines() - if mount.startswith(self.dev) - ] + mount = [mount.split(" ") for mount in mtab.splitlines() if mount.startswith(self.dev)] if mount: self._path = mount[0][1] else: @@ -268,9 +262,7 @@ class CPboard: vendor, _, product = name.partition(":") if vendor and product: - return CPboard.from_usb( - **kwargs, idVendor=int(vendor, 16), idProduct=int(product, 16) - ) + return CPboard.from_usb(**kwargs, idVendor=int(vendor, 16), idProduct=int(product, 16)) return CPboard(name, **kwargs) @@ -363,11 +355,7 @@ class CPboard: except: pass else: - serials = [ - serial - for serial in os.listdir("/dev/serial/by-path") - if portstr in serial - ] + serials = [serial for serial in os.listdir("/dev/serial/by-path") if portstr in serial] if len(serials) != 1: raise RuntimeError("Can't find excatly one matching usb serial device") self.device = os.path.realpath("/dev/serial/by-path/" + serials[0]) @@ -461,9 +449,7 @@ class CPboard: % mode ) try: - self.exec( - "import microcontroller;microcontroller.reset()", wait_for_response=False - ) + self.exec("import microcontroller;microcontroller.reset()", wait_for_response=False) except OSError: pass @@ -512,9 +498,7 @@ class CPboard: if not serial: raise RuntimeError("Serial number not found for: " + self.device) return [ - "/dev/disk/by-id/" + disk - for disk in os.listdir("/dev/disk/by-id") - if serial in disk + "/dev/disk/by-id/" + disk for disk in os.listdir("/dev/disk/by-id") if serial in disk ] @property @@ -562,9 +546,7 @@ PyboardError = CPboardError class Pyboard: - def __init__( - self, device, baudrate=115200, user="micro", password="python", wait=0 - ): + def __init__(self, device, baudrate=115200, user="micro", password="python", wait=0): self.board = CPboard.from_try_all(device, baudrate=baudrate, wait=wait) with self.board.disk as disk: disk.copy("skip_if.py") @@ -616,9 +598,7 @@ def upload(args): if not board.bootloader: print_verbose(args, "Reset to bootloader...", end="") - board.reset_to_bootloader( - repl=True - ) # Feather M0 Express doesn't respond to 1200 baud + board.reset_to_bootloader(repl=True) # Feather M0 Express doesn't respond to 1200 baud time.sleep(5) print_verbose(args, "done") @@ -655,9 +635,7 @@ def main(): cmd_parser.add_argument("-f", "--firmware", help="upload UF2 firmware file") cmd_parser.add_argument("-c", "--command", help="program passed in as string") cmd_parser.add_argument("--tty", action="store_true", help="print tty") - cmd_parser.add_argument( - "--verbose", "-v", action="count", default=0, help="be verbose" - ) + cmd_parser.add_argument("--verbose", "-v", action="count", default=0, help="be verbose") cmd_parser.add_argument("-q", "--quiet", action="store_true", help="be quiet") cmd_parser.add_argument("--debug", action="store_true", help="raise exceptions") args = cmd_parser.parse_args() @@ -702,9 +680,7 @@ def main(): with board as b: print("Device: ", end="") if b.usb_dev: - print( - "%04x:%04x on " % (b.usb_dev.idVendor, b.usb_dev.idProduct), end="" - ) + print("%04x:%04x on " % (b.usb_dev.idVendor, b.usb_dev.idProduct), end="") print(b.device) print("Serial number:", b.serial_number) uname = os_uname(b) diff --git a/tools/dfu.py b/tools/dfu.py index 489465f0cf..4dcb4fdca7 100644 --- a/tools/dfu.py +++ b/tools/dfu.py @@ -9,91 +9,122 @@ # Distributed under Gnu LGPL 3.0 # see http://www.gnu.org/licenses/lgpl-3.0.txt -import sys,struct,zlib,os +import sys, struct, zlib, os from optparse import OptionParser -DEFAULT_DEVICE="0x0483:0xdf11" +DEFAULT_DEVICE = "0x0483:0xdf11" + + +def named(tuple, names): + return dict(zip(names.split(), tuple)) + + +def consume(fmt, data, names): + n = struct.calcsize(fmt) + return named(struct.unpack(fmt, data[:n]), names), data[n:] + -def named(tuple,names): - return dict(zip(names.split(),tuple)) -def consume(fmt,data,names): - n = struct.calcsize(fmt) - return named(struct.unpack(fmt,data[:n]),names),data[n:] def cstring(string): - return string.split('\0',1)[0] + return string.split("\0", 1)[0] + + def compute_crc(data): - return 0xFFFFFFFF & -zlib.crc32(data) -1 + return 0xFFFFFFFF & -zlib.crc32(data) - 1 -def parse(file,dump_images=False): - print ('File: "%s"' % file) - data = open(file,'rb').read() - crc = compute_crc(data[:-4]) - data = data[len(data)-16:] - suffix = named(struct.unpack('<4H3sBI',data[:16]),'device product vendor dfu ufd len crc') - print ('usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x' % suffix) - if crc != suffix['crc']: - print ("CRC ERROR: computed crc32 is 0x%08x" % crc) - data = data[16:] - if data: - print ("PARSE ERROR") -def build(file,data,device=DEFAULT_DEVICE): - # Parse the VID and PID from the `device` argument - v,d=map(lambda x: int(x,0) & 0xFFFF, device.split(':',1)) +def parse(file, dump_images=False): + print('File: "%s"' % file) + data = open(file, "rb").read() + crc = compute_crc(data[:-4]) + data = data[len(data) - 16 :] + suffix = named(struct.unpack("<4H3sBI", data[:16]), "device product vendor dfu ufd len crc") + print( + "usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x" + % suffix + ) + if crc != suffix["crc"]: + print("CRC ERROR: computed crc32 is 0x%08x" % crc) + data = data[16:] + if data: + print("PARSE ERROR") - # Generate the DFU suffix, consisting of these fields: - # Field name | Length | Description - # ================+=========+================================ - # bcdDevice | 2 | The release number of this firmware (0xffff - don't care) - # idProduct | 2 | PID of this device - # idVendor | 2 | VID of this device - # bcdDFU | 2 | Version of this DFU spec (0x01 0x00) - # ucDfuSignature | 3 | The characters 'DFU', printed in reverse order - # bLength | 1 | The length of this suffix (16 bytes) - # dwCRC | 4 | A CRC32 of the data, including this suffix - data += struct.pack('<4H3sB',0xffff,d,v,0x0100,b'UFD',16) - crc = compute_crc(data) - # Append the CRC32 of the entire block - data += struct.pack('= (3, 8): allargs.extend(node.posonlyargs) for arg_node in allargs: - if not is_typed(arg_node.annotation) and (arg_node.arg != "self" and arg_node.arg != "cls"): - yield ("WARN", f"Missing argument type: {arg_node.arg} on line {arg_node.lineno}") + if not is_typed(arg_node.annotation) and ( + arg_node.arg != "self" and arg_node.arg != "cls" + ): + yield ( + "WARN", + f"Missing argument type: {arg_node.arg} on line {arg_node.lineno}", + ) if node.vararg and not is_typed(node.vararg.annotation, allow_any=True): - yield ("WARN", f"Missing argument type: *{node.vararg.arg} on line {node.vararg.lineno}") + yield ( + "WARN", + f"Missing argument type: *{node.vararg.arg} on line {node.vararg.lineno}", + ) if node.kwarg and not is_typed(node.kwarg.annotation, allow_any=True): - yield ("WARN", f"Missing argument type: **{node.kwarg.arg} on line {node.kwarg.lineno}") + yield ( + "WARN", + f"Missing argument type: **{node.kwarg.arg} on line {node.kwarg.lineno}", + ) elif isinstance(node, ast.FunctionDef): if not is_typed(node.returns): yield ("WARN", f"Missing return type: {node.name} on line {node.lineno}") @@ -196,7 +248,7 @@ def convert_folder(top_level, stub_directory): import_body = "\n".join(import_lines) m = re.match(r'(\s*""".*?""")', stub_contents, flags=re.DOTALL) if m: - stub_contents = m.group(1) + "\n\n" + import_body + "\n\n" + stub_contents[m.end():] + stub_contents = m.group(1) + "\n\n" + import_body + "\n\n" + stub_contents[m.end() :] else: stub_contents = import_body + "\n\n" + stub_contents diff --git a/tools/file2h.py b/tools/file2h.py index 706dd4dd23..df9cc02fda 100644 --- a/tools/file2h.py +++ b/tools/file2h.py @@ -16,19 +16,19 @@ import sys # Can either be set explicitly, or left blank to auto-detect # Except auto-detect doesn't work because the file has been passed # through Python text processing, which makes all EOL a \n -line_end = '\\r\\n' +line_end = "\\r\\n" if __name__ == "__main__": filename = sys.argv[1] - for line in open(filename, 'r').readlines(): + for line in open(filename, "r").readlines(): if not line_end: - for ending in ('\r\n', '\r', '\n'): + for ending in ("\r\n", "\r", "\n"): if line.endswith(ending): - line_end = ending.replace('\r', '\\r').replace('\n', '\\n') + line_end = ending.replace("\r", "\\r").replace("\n", "\\n") break if not line_end: raise Exception("Couldn't auto-detect line-ending of %s" % filename) - line = line.rstrip('\r\n') - line = line.replace('\\', '\\\\') + line = line.rstrip("\r\n") + line = line.replace("\\", "\\\\") line = line.replace('"', '\\"') print('"%s%s"' % (line, line_end)) diff --git a/tools/fixup_translations.py b/tools/fixup_translations.py index 0362923e88..4c6f89b26f 100644 --- a/tools/fixup_translations.py +++ b/tools/fixup_translations.py @@ -45,7 +45,9 @@ for po_filename in po_filenames: entry.merge(newer_entry) print(entry) elif newer_entry and entry.msgstr != newer_entry.msgstr: - if newer_entry.msgstr != "" and (newer_entry.msgstr != entry.msgid or entry.msgid in NO_TRANSLATION_WHITELIST): + if newer_entry.msgstr != "" and ( + newer_entry.msgstr != entry.msgid or entry.msgid in NO_TRANSLATION_WHITELIST + ): entry.merge(newer_entry) entry.msgstr = newer_entry.msgstr if "fuzzy" not in newer_entry.flags and "fuzzy" in entry.flags: @@ -55,7 +57,7 @@ for po_filename in po_filenames: bad_commits[commit] = set() bad_commits[commit].add(po_filename) fixed_ids.add(entry.msgid) - #print(entry.msgid, "\"" + entry.msgstr + "\"", "\"" + newer_entry.msgstr + "\"",) + # print(entry.msgid, "\"" + entry.msgstr + "\"", "\"" + newer_entry.msgstr + "\"",) elif newer_entry and newer_entry.flags != entry.flags: entry.flags = newer_entry.flags elif newer_entry and newer_entry.obsolete != entry.obsolete: @@ -86,4 +88,4 @@ for commit in bad_commits: files = bad_commits[commit] print(commit) for file in files: - print("\t",file) + print("\t", file) diff --git a/tools/gc_activity.py b/tools/gc_activity.py index cc9a218361..6a1772faa7 100644 --- a/tools/gc_activity.py +++ b/tools/gc_activity.py @@ -10,18 +10,22 @@ current_heap = {} allocation_history = [] root = {} + def change_root(trace, size): level = root for frame in reversed(trace): file_location = frame[1] if file_location not in level: - level[file_location] = {"blocks": 0, - "file": file_location, - "function": frame[2], - "subcalls": {}} + level[file_location] = { + "blocks": 0, + "file": file_location, + "function": frame[2], + "subcalls": {}, + } level[file_location]["blocks"] += size level = level[file_location]["subcalls"] + total_actions = 0 with open(sys.argv[1], "r") as f: for line in f: @@ -31,13 +35,13 @@ with open(sys.argv[1], "r") as f: action = None if line.startswith("Breakpoint 2"): break - next(f) # throw away breakpoint code line - next(f) # first frame + next(f) # throw away breakpoint code line + next(f) # first frame block = 0 size = 0 trace = [] for line in f: - #print(line.strip()) + # print(line.strip()) if line[0] == "#": frame = line.strip().split() if frame[1].startswith("0x"): @@ -52,7 +56,12 @@ with open(sys.argv[1], "r") as f: action = "unknown" if block not in current_heap: - current_heap[block] = {"start_block": block, "size": size, "start_trace": trace, "start_time": total_actions} + current_heap[block] = { + "start_block": block, + "size": size, + "start_trace": trace, + "start_time": total_actions, + } action = "alloc" change_root(trace, size) else: @@ -62,7 +71,12 @@ with open(sys.argv[1], "r") as f: change_root(alloc["start_trace"], -1 * alloc["size"]) if size > 0: action = "realloc" - current_heap[block] = {"start_block": block, "size": size, "start_trace": trace, "start_time": total_actions} + current_heap[block] = { + "start_block": block, + "size": size, + "start_trace": trace, + "start_time": total_actions, + } change_root(trace, size) else: action = "free" @@ -81,13 +95,19 @@ for alloc in current_heap.values(): alloc["end_time"] = total_actions allocation_history.append(alloc) + def print_frame(frame, indent=0): for key in sorted(frame): - if not frame[key]["blocks"] or key.startswith("../py/malloc.c") or key.startswith("../py/gc.c"): + if ( + not frame[key]["blocks"] + or key.startswith("../py/malloc.c") + or key.startswith("../py/gc.c") + ): continue print(" " * (indent - 1), key, frame[key]["function"], frame[key]["blocks"], "blocks") print_frame(frame[key]["subcalls"], indent + 2) + print_frame(root) total_blocks = 0 for key in sorted(root): diff --git a/tools/gc_activity_between_collects.py b/tools/gc_activity_between_collects.py index f906cf5c7e..f1afede702 100644 --- a/tools/gc_activity_between_collects.py +++ b/tools/gc_activity_between_collects.py @@ -10,18 +10,22 @@ current_heap = {} allocation_history = [] root = {} + def change_root(trace, size): level = root for frame in reversed(trace): file_location = frame[1] if file_location not in level: - level[file_location] = {"blocks": 0, - "file": file_location, - "function": frame[2], - "subcalls": {}} + level[file_location] = { + "blocks": 0, + "file": file_location, + "function": frame[2], + "subcalls": {}, + } level[file_location]["blocks"] += size level = level[file_location]["subcalls"] + total_actions = 0 non_single_block_streak = 0 max_nsbs = 0 @@ -41,7 +45,7 @@ with open(sys.argv[1], "r") as f: action = None if line.startswith("Breakpoint 2"): break - next(f) # throw away breakpoint code line + next(f) # throw away breakpoint code line # print(next(f)) # first frame block = 0 size = 0 @@ -55,7 +59,7 @@ with open(sys.argv[1], "r") as f: else: trace.append(("0x0", frame[-1], frame[1])) elif line[0] == "$": - #print(line.strip().split()[-1]) + # print(line.strip().split()[-1]) block = int(line.strip().split()[-1][2:], 16) next_line = next(f) size = int(next_line.strip().split()[-1][2:], 16) @@ -66,14 +70,19 @@ with open(sys.argv[1], "r") as f: action = "unknown" if block not in current_heap: - current_heap[block] = {"start_block": block, "size": size, "start_trace": trace, "start_time": total_actions} + current_heap[block] = { + "start_block": block, + "size": size, + "start_trace": trace, + "start_time": total_actions, + } action = "alloc" if size == 1: max_nsbs = max(max_nsbs, non_single_block_streak) non_single_block_streak = 0 else: non_single_block_streak += 1 - #change_root(trace, size) + # change_root(trace, size) if size not in block_sizes: block_sizes[size] = 0 source = trace[-1][-1] @@ -89,15 +98,27 @@ with open(sys.argv[1], "r") as f: change_root(alloc["start_trace"], -1 * alloc["size"]) if size > 0: action = "realloc" - current_heap[block] = {"start_block": block, "size": size, "start_trace": trace, "start_time": total_actions} - #change_root(trace, size) + current_heap[block] = { + "start_block": block, + "size": size, + "start_trace": trace, + "start_time": total_actions, + } + # change_root(trace, size) else: action = "free" if trace[0][2] == "gc_sweep": action = "sweep" non_single_block_streak = 0 - if (trace[3][2] == "py_gc_collect" or (trace[3][2] == "gc_deinit" and count > 1)) and last_action != "sweep": - print(ticks_ms - last_ticks_ms, total_actions - last_total_actions, "gc.collect", max_nsbs) + if ( + trace[3][2] == "py_gc_collect" or (trace[3][2] == "gc_deinit" and count > 1) + ) and last_action != "sweep": + print( + ticks_ms - last_ticks_ms, + total_actions - last_total_actions, + "gc.collect", + max_nsbs, + ) print(actions) print(block_sizes) print(allocation_sources) @@ -117,7 +138,7 @@ with open(sys.argv[1], "r") as f: actions[action] = 0 actions[action] += 1 last_action = action - #print(total_actions, non_single_block_streak, action, block, size) + # print(total_actions, non_single_block_streak, action, block, size) total_actions += 1 print(actions) print(max_nsbs) @@ -128,13 +149,19 @@ for alloc in current_heap.values(): alloc["end_time"] = total_actions allocation_history.append(alloc) + def print_frame(frame, indent=0): for key in sorted(frame): - if not frame[key]["blocks"] or key.startswith("../py/malloc.c") or key.startswith("../py/gc.c"): + if ( + not frame[key]["blocks"] + or key.startswith("../py/malloc.c") + or key.startswith("../py/gc.c") + ): continue print(" " * (indent - 1), key, frame[key]["function"], frame[key]["blocks"], "blocks") print_frame(frame[key]["subcalls"], indent + 2) + # print_frame(root) # total_blocks = 0 # for key in sorted(root): diff --git a/tools/gen_display_resources.py b/tools/gen_display_resources.py index 141e6ee2a1..69ad501787 100644 --- a/tools/gen_display_resources.py +++ b/tools/gen_display_resources.py @@ -13,25 +13,28 @@ sys.path.insert(0, "../../tools/bitmap_font") from adafruit_bitmap_font import bitmap_font -parser = argparse.ArgumentParser(description='Generate USB descriptors.') -parser.add_argument('--font', type=str, - help='Font path', required=True) -parser.add_argument('--extra_characters', type=str, - help='Unicode string of extra characters') -parser.add_argument('--sample_file', type=argparse.FileType('r'), - help='Text file that includes strings to support.') -parser.add_argument('--output_c_file', type=argparse.FileType('w'), required=True) +parser = argparse.ArgumentParser(description="Generate USB descriptors.") +parser.add_argument("--font", type=str, help="Font path", required=True) +parser.add_argument("--extra_characters", type=str, help="Unicode string of extra characters") +parser.add_argument( + "--sample_file", + type=argparse.FileType("r"), + help="Text file that includes strings to support.", +) +parser.add_argument("--output_c_file", type=argparse.FileType("w"), required=True) args = parser.parse_args() + class BitmapStub: def __init__(self, width, height, color_depth): self.width = width - self.rows = [b''] * height + self.rows = [b""] * height def _load_row(self, y, row): self.rows[y] = bytes(row) + f = bitmap_font.load_font(args.font, BitmapStub) # Load extra characters from the sample file. @@ -45,7 +48,7 @@ if args.sample_file: sample_characters.add(c) # Merge visible ascii, sample characters and extra characters. -visible_ascii = bytes(range(0x20, 0x7f)).decode("utf-8") +visible_ascii = bytes(range(0x20, 0x7F)).decode("utf-8") all_characters = visible_ascii for c in sample_characters: if c not in all_characters: @@ -87,7 +90,7 @@ for x, c in enumerate(filtered_characters): for i in range(g["bounds"][0]): byte = i // 8 bit = i % 8 - if row[byte] & (1 << (7-bit)) != 0: + if row[byte] & (1 << (7 - bit)) != 0: overall_bit = start_bit + (start_y + y) * bytes_per_row * 8 + i b[overall_bit // 8] |= 1 << (7 - (overall_bit % 8)) @@ -99,14 +102,17 @@ for c in filtered_characters: c_file = args.output_c_file -c_file.write("""\ +c_file.write( + """\ #include "shared-bindings/displayio/Palette.h" #include "supervisor/shared/display.h" -""") +""" +) -c_file.write("""\ +c_file.write( + """\ _displayio_color_t terminal_colors[2] = { { .rgb888 = 0x000000, @@ -128,9 +134,11 @@ displayio_palette_t supervisor_terminal_color = { .color_count = 2, .needs_refresh = false }; -""") +""" +) -c_file.write("""\ +c_file.write( + """\ displayio_tilegrid_t supervisor_terminal_text_grid = {{ .base = {{ .type = &displayio_tilegrid_type }}, .bitmap = (displayio_bitmap_t*) &supervisor_terminal_font_bitmap, @@ -154,22 +162,32 @@ displayio_tilegrid_t supervisor_terminal_text_grid = {{ .inline_tiles = false, .in_group = true }}; -""".format(len(all_characters), tile_x, tile_y)) +""".format( + len(all_characters), tile_x, tile_y + ) +) -c_file.write("""\ +c_file.write( + """\ const uint32_t font_bitmap_data[{}] = {{ -""".format(bytes_per_row * tile_y // 4)) +""".format( + bytes_per_row * tile_y // 4 + ) +) for i, word in enumerate(struct.iter_unpack(">I", b)): c_file.write("0x{:08x}, ".format(word[0])) if (i + 1) % (bytes_per_row // 4) == 0: c_file.write("\n") -c_file.write("""\ +c_file.write( + """\ }; -""") +""" +) -c_file.write("""\ +c_file.write( + """\ displayio_bitmap_t supervisor_terminal_font_bitmap = {{ .base = {{.type = &displayio_bitmap_type }}, .width = {}, @@ -182,10 +200,14 @@ displayio_bitmap_t supervisor_terminal_font_bitmap = {{ .bitmask = 0x1, .read_only = true }}; -""".format(len(all_characters) * tile_x, tile_y, bytes_per_row / 4)) +""".format( + len(all_characters) * tile_x, tile_y, bytes_per_row / 4 + ) +) -c_file.write("""\ +c_file.write( + """\ const fontio_builtinfont_t supervisor_terminal_font = {{ .base = {{.type = &fontio_builtinfont_type }}, .bitmap = &supervisor_terminal_font_bitmap, @@ -194,9 +216,13 @@ const fontio_builtinfont_t supervisor_terminal_font = {{ .unicode_characters = (const uint8_t*) "{}", .unicode_characters_len = {} }}; -""".format(tile_x, tile_y, extra_characters, len(extra_characters.encode("utf-8")))) +""".format( + tile_x, tile_y, extra_characters, len(extra_characters.encode("utf-8")) + ) +) -c_file.write("""\ +c_file.write( + """\ terminalio_terminal_obj_t supervisor_terminal = { .base = { .type = &terminalio_terminal_type }, .font = &supervisor_terminal_font, @@ -204,4 +230,5 @@ terminalio_terminal_obj_t supervisor_terminal = { .cursor_y = 0, .tilegrid = &supervisor_terminal_text_grid }; -""") +""" +) diff --git a/tools/gen_ld_files.py b/tools/gen_ld_files.py index 1fea1a7efa..28f73d9be2 100755 --- a/tools/gen_ld_files.py +++ b/tools/gen_ld_files.py @@ -12,31 +12,39 @@ import sys import re from string import Template -parser = argparse.ArgumentParser(description='Apply #define values to .template.ld file.') -parser.add_argument('template_files', metavar='TEMPLATE_FILE', type=argparse.FileType('r'), - nargs='+', help="template filename: .template.ld") -parser.add_argument('--defines', type=argparse.FileType('r'), required=True) -parser.add_argument('--out_dir', required=True) +parser = argparse.ArgumentParser(description="Apply #define values to .template.ld file.") +parser.add_argument( + "template_files", + metavar="TEMPLATE_FILE", + type=argparse.FileType("r"), + nargs="+", + help="template filename: .template.ld", +) +parser.add_argument("--defines", type=argparse.FileType("r"), required=True) +parser.add_argument("--out_dir", required=True) args = parser.parse_args() defines = {} # -REMOVE_UL_RE = re.compile('([0-9]+)UL') +REMOVE_UL_RE = re.compile("([0-9]+)UL") + + def remove_UL(s): - return REMOVE_UL_RE.sub(r'\1', s) + return REMOVE_UL_RE.sub(r"\1", s) + # We skip all lines before # // START_LD_DEFINES # Then we look for lines like this: # /*NAME_OF_VALUE=*/ NAME_OF_VALUE; -VALUE_LINE_RE = re.compile(r'^/\*\s*(\w+)\s*=\*/\s*(.*);\s*$') +VALUE_LINE_RE = re.compile(r"^/\*\s*(\w+)\s*=\*/\s*(.*);\s*$") start_processing = False for line in args.defines: line = line.strip() - if line == '// START_LD_DEFINES': + if line == "// START_LD_DEFINES": start_processing = True continue if start_processing: @@ -50,10 +58,10 @@ fail = False for template_file in args.template_files: ld_template_basename = os.path.basename(template_file.name) - ld_pathname = os.path.join(args.out_dir, ld_template_basename.replace('.template.ld', '.ld')) - with open(ld_pathname, 'w') as output: - for k,v in defines.items(): - print('/*', k, '=', v, '*/', file=output) + ld_pathname = os.path.join(args.out_dir, ld_template_basename.replace(".template.ld", ".ld")) + with open(ld_pathname, "w") as output: + for k, v in defines.items(): + print("/*", k, "=", v, "*/", file=output) print(file=output) try: output.write(Template(template_file.read()).substitute(defines)) diff --git a/tools/gen_usb_descriptor.py b/tools/gen_usb_descriptor.py index b21cfd920f..89bb8a8177 100644 --- a/tools/gen_usb_descriptor.py +++ b/tools/gen_usb_descriptor.py @@ -25,16 +25,11 @@ ALL_HID_DEVICES_SET = frozenset(ALL_HID_DEVICES.split()) DEFAULT_HID_DEVICES = "KEYBOARD MOUSE CONSUMER GAMEPAD" # In the following URL, don't include the https:// because that prefix gets added automatically -DEFAULT_WEBUSB_URL = ( - "circuitpython.org" # In the future, this may become a specific landing page -) +DEFAULT_WEBUSB_URL = "circuitpython.org" # In the future, this may become a specific landing page parser = argparse.ArgumentParser(description="Generate USB descriptors.") parser.add_argument( - "--highspeed", - default=False, - action="store_true", - help="descriptor for highspeed device", + "--highspeed", default=False, action="store_true", help="descriptor for highspeed device" ) parser.add_argument("--manufacturer", type=str, help="manufacturer of the device") parser.add_argument("--product", type=str, help="product name of the device") @@ -71,16 +66,10 @@ parser.add_argument( help="use to not renumber endpoint", ) parser.add_argument( - "--cdc_ep_num_notification", - type=int, - default=0, - help="endpoint number of CDC NOTIFICATION", + "--cdc_ep_num_notification", type=int, default=0, help="endpoint number of CDC NOTIFICATION" ) parser.add_argument( - "--cdc2_ep_num_notification", - type=int, - default=0, - help="endpoint number of CDC2 NOTIFICATION", + "--cdc2_ep_num_notification", type=int, default=0, help="endpoint number of CDC2 NOTIFICATION" ) parser.add_argument( "--cdc_ep_num_data_out", type=int, default=0, help="endpoint number of CDC DATA OUT" @@ -89,35 +78,18 @@ parser.add_argument( "--cdc_ep_num_data_in", type=int, default=0, help="endpoint number of CDC DATA IN" ) parser.add_argument( - "--cdc2_ep_num_data_out", - type=int, - default=0, - help="endpoint number of CDC2 DATA OUT", + "--cdc2_ep_num_data_out", type=int, default=0, help="endpoint number of CDC2 DATA OUT" ) parser.add_argument( "--cdc2_ep_num_data_in", type=int, default=0, help="endpoint number of CDC2 DATA IN" ) -parser.add_argument( - "--msc_ep_num_out", type=int, default=0, help="endpoint number of MSC OUT" -) -parser.add_argument( - "--msc_ep_num_in", type=int, default=0, help="endpoint number of MSC IN" -) -parser.add_argument( - "--hid_ep_num_out", type=int, default=0, help="endpoint number of HID OUT" -) -parser.add_argument( - "--hid_ep_num_in", type=int, default=0, help="endpoint number of HID IN" -) -parser.add_argument( - "--midi_ep_num_out", type=int, default=0, help="endpoint number of MIDI OUT" -) -parser.add_argument( - "--midi_ep_num_in", type=int, default=0, help="endpoint number of MIDI IN" -) -parser.add_argument( - "--max_ep", type=int, default=0, help="total number of endpoints available" -) +parser.add_argument("--msc_ep_num_out", type=int, default=0, help="endpoint number of MSC OUT") +parser.add_argument("--msc_ep_num_in", type=int, default=0, help="endpoint number of MSC IN") +parser.add_argument("--hid_ep_num_out", type=int, default=0, help="endpoint number of HID OUT") +parser.add_argument("--hid_ep_num_in", type=int, default=0, help="endpoint number of HID IN") +parser.add_argument("--midi_ep_num_out", type=int, default=0, help="endpoint number of MIDI OUT") +parser.add_argument("--midi_ep_num_in", type=int, default=0, help="endpoint number of MIDI IN") +parser.add_argument("--max_ep", type=int, default=0, help="total number of endpoints available") parser.add_argument( "--webusb_url", type=str, @@ -127,9 +99,7 @@ parser.add_argument( parser.add_argument( "--vendor_ep_num_out", type=int, default=0, help="endpoint number of VENDOR OUT" ) -parser.add_argument( - "--vendor_ep_num_in", type=int, default=0, help="endpoint number of VENDOR IN" -) +parser.add_argument("--vendor_ep_num_in", type=int, default=0, help="endpoint number of VENDOR IN") parser.add_argument( "--output_c_file", type=argparse.FileType("w", encoding="UTF-8"), required=True ) @@ -261,9 +231,7 @@ def make_cdc_call_management(name): ) -def make_cdc_comm_interface( - name, cdc_union, cdc_call_management, cdc_ep_num_notification -): +def make_cdc_comm_interface(name, cdc_union, cdc_call_management, cdc_ep_num_notification): return standard.InterfaceDescriptor( description="{} comm".format(name), bInterfaceClass=cdc.CDC_CLASS_COMM, # Communications Device Class @@ -273,9 +241,7 @@ def make_cdc_comm_interface( subdescriptors=[ cdc.Header(description="{} comm".format(name), bcdCDC=0x0110), cdc_call_management, - cdc.AbstractControlManagement( - description="{} comm".format(name), bmCapabilities=0x02 - ), + cdc.AbstractControlManagement(description="{} comm".format(name), bmCapabilities=0x02), cdc_union, standard.EndpointDescriptor( description="{} comm in".format(name), @@ -297,16 +263,14 @@ def make_cdc_data_interface(name, cdc_ep_num_data_in, cdc_ep_num_data_out): subdescriptors=[ standard.EndpointDescriptor( description="{} data out".format(name), - bEndpointAddress=cdc_ep_num_data_out - | standard.EndpointDescriptor.DIRECTION_OUT, + bEndpointAddress=cdc_ep_num_data_out | standard.EndpointDescriptor.DIRECTION_OUT, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=0, wMaxPacketSize=512 if args.highspeed else 64, ), standard.EndpointDescriptor( description="{} data in".format(name), - bEndpointAddress=cdc_ep_num_data_in - | standard.EndpointDescriptor.DIRECTION_IN, + bEndpointAddress=cdc_ep_num_data_in | standard.EndpointDescriptor.DIRECTION_IN, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=0, wMaxPacketSize=512 if args.highspeed else 64, @@ -350,8 +314,7 @@ if include_msc: subdescriptors=[ standard.EndpointDescriptor( description="MSC in", - bEndpointAddress=args.msc_ep_num_in - | standard.EndpointDescriptor.DIRECTION_IN, + bEndpointAddress=args.msc_ep_num_in | standard.EndpointDescriptor.DIRECTION_IN, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=0, wMaxPacketSize=512 if args.highspeed else 64, @@ -383,9 +346,7 @@ if include_hid: name = args.hid_devices[0] combined_hid_report_descriptor = hid.ReportDescriptor( description=name, - report_descriptor=bytes( - hid_report_descriptors.REPORT_DESCRIPTOR_FUNCTIONS[name](0) - ), + report_descriptor=bytes(hid_report_descriptors.REPORT_DESCRIPTOR_FUNCTIONS[name](0)), ) report_ids[name] = 0 else: @@ -393,9 +354,7 @@ if include_hid: concatenated_descriptors = bytearray() for name in args.hid_devices: concatenated_descriptors.extend( - bytes( - hid_report_descriptors.REPORT_DESCRIPTOR_FUNCTIONS[name](report_id) - ) + bytes(hid_report_descriptors.REPORT_DESCRIPTOR_FUNCTIONS[name](report_id)) ) report_ids[name] = report_id report_id += 1 @@ -414,8 +373,7 @@ if include_hid: hid_endpoint_out_descriptor = standard.EndpointDescriptor( description="HID out", - bEndpointAddress=args.hid_ep_num_out - | standard.EndpointDescriptor.DIRECTION_OUT, + bEndpointAddress=args.hid_ep_num_out | standard.EndpointDescriptor.DIRECTION_OUT, bmAttributes=standard.EndpointDescriptor.TYPE_INTERRUPT, bInterval=8, ) @@ -429,13 +387,12 @@ if include_hid: iInterface=StringIndex.index("{} HID".format(args.interface_name)), subdescriptors=[ hid.HIDDescriptor( - description="HID", - wDescriptorLength=len(bytes(combined_hid_report_descriptor)), + description="HID", wDescriptorLength=len(bytes(combined_hid_report_descriptor)) ), hid_endpoint_in_descriptor, hid_endpoint_out_descriptor, ], - ), + ) ] if include_audio: @@ -457,9 +414,7 @@ if include_audio: # USB IN <- midi_out_jack_emb <- midi_in_jack_ext <- CircuitPython midi_in_jack_ext = midi.InJackDescriptor( - description="MIDI data in from user code.", - bJackType=midi.JACK_TYPE_EXTERNAL, - iJack=0, + description="MIDI data in from user code.", bJackType=midi.JACK_TYPE_EXTERNAL, iJack=0 ) midi_out_jack_emb = midi.OutJackDescriptor( description="MIDI PC <- {}".format(args.interface_name), @@ -481,12 +436,11 @@ if include_audio: midi_in_jack_ext, midi_out_jack_emb, midi_out_jack_ext, - ], + ] ), standard.EndpointDescriptor( description="MIDI data out to {}".format(args.interface_name), - bEndpointAddress=args.midi_ep_num_out - | standard.EndpointDescriptor.DIRECTION_OUT, + bEndpointAddress=args.midi_ep_num_out | standard.EndpointDescriptor.DIRECTION_OUT, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=0, wMaxPacketSize=512 if args.highspeed else 64, @@ -494,8 +448,7 @@ if include_audio: midi.DataEndpointDescriptor(baAssocJack=[midi_in_jack_emb]), standard.EndpointDescriptor( description="MIDI data in from {}".format(args.interface_name), - bEndpointAddress=args.midi_ep_num_in - | standard.EndpointDescriptor.DIRECTION_IN, + bEndpointAddress=args.midi_ep_num_in | standard.EndpointDescriptor.DIRECTION_IN, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=0x0, wMaxPacketSize=512 if args.highspeed else 64, @@ -516,9 +469,7 @@ if include_audio: bInterfaceSubClass=audio.AUDIO_SUBCLASS_CONTROL, bInterfaceProtocol=audio.AUDIO_PROTOCOL_V1, iInterface=StringIndex.index("{} Audio".format(args.interface_name)), - subdescriptors=[ - cs_ac_interface, - ], + subdescriptors=[cs_ac_interface], ) # Audio streaming interfaces must occur before MIDI ones. @@ -532,16 +483,14 @@ if include_vendor: # Vendor-specific interface, for example WebUSB vendor_endpoint_in_descriptor = standard.EndpointDescriptor( description="VENDOR in", - bEndpointAddress=args.vendor_ep_num_in - | standard.EndpointDescriptor.DIRECTION_IN, + bEndpointAddress=args.vendor_ep_num_in | standard.EndpointDescriptor.DIRECTION_IN, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=16, ) vendor_endpoint_out_descriptor = standard.EndpointDescriptor( description="VENDOR out", - bEndpointAddress=args.vendor_ep_num_out - | standard.EndpointDescriptor.DIRECTION_OUT, + bEndpointAddress=args.vendor_ep_num_out | standard.EndpointDescriptor.DIRECTION_OUT, bmAttributes=standard.EndpointDescriptor.TYPE_BULK, bInterval=16, ) @@ -552,10 +501,7 @@ if include_vendor: bInterfaceSubClass=0x00, bInterfaceProtocol=0x00, iInterface=StringIndex.index("{} VENDOR".format(args.interface_name)), - subdescriptors=[ - vendor_endpoint_in_descriptor, - vendor_endpoint_out_descriptor, - ], + subdescriptors=[vendor_endpoint_in_descriptor, vendor_endpoint_out_descriptor], ) vendor_interfaces = [vendor_interface] @@ -583,9 +529,7 @@ if include_vendor: # util.join_interfaces() will renumber the endpoints to make them unique across descriptors, # and renumber the interfaces in order. But we still need to fix up certain # interface cross-references. -interfaces = util.join_interfaces( - interfaces_to_join, renumber_endpoints=args.renumber_endpoints -) +interfaces = util.join_interfaces(interfaces_to_join, renumber_endpoints=args.renumber_endpoints) if args.max_ep != 0: for interface in interfaces: @@ -597,10 +541,7 @@ if args.max_ep != 0: % (endpoint_address & 0x7F, interface.description, args.max_ep) ) else: - print( - "Unable to check whether maximum number of endpoints is respected", - file=sys.stderr, - ) + print("Unable to check whether maximum number of endpoints is respected", file=sys.stderr) # Now adjust the CDC interface cross-references. @@ -668,8 +609,7 @@ if include_vendor: configuration = standard.ConfigurationDescriptor( description="Composite configuration", wTotalLength=( - standard.ConfigurationDescriptor.bLength - + sum([len(bytes(x)) for x in descriptor_list]) + standard.ConfigurationDescriptor.bLength + sum([len(bytes(x)) for x in descriptor_list]) ), bNumInterfaces=len(interfaces), ) @@ -783,7 +723,9 @@ for idx, descriptor in enumerate(string_descriptors): const = "const " if variable_name == "usb_serial_number": length = len(b) - c_file.write(" uint16_t {NAME}[{length}];\n".format(NAME=variable_name, length=length//2)) + c_file.write( + " uint16_t {NAME}[{length}];\n".format(NAME=variable_name, length=length // 2) + ) else: c_file.write( """\ @@ -804,7 +746,7 @@ for idx, descriptor in enumerate(string_descriptors): """\ }; """ - ) + ) c_file.write( """\ @@ -932,9 +874,7 @@ const uint8_t hid_report_descriptor[{HID_DESCRIPTOR_LENGTH}] = {{ static uint8_t {name}_report_buffer[{report_length}]; """.format( name=name.lower(), - report_length=hid_report_descriptors.HID_DEVICE_DATA[ - name - ].report_length, + report_length=hid_report_descriptors.HID_DEVICE_DATA[name].report_length, ) ) @@ -944,9 +884,7 @@ static uint8_t {name}_report_buffer[{report_length}]; static uint8_t {name}_out_report_buffer[{report_length}]; """.format( name=name.lower(), - report_length=hid_report_descriptors.HID_DEVICE_DATA[ - name - ].out_report_length, + report_length=hid_report_descriptors.HID_DEVICE_DATA[name].out_report_length, ) ) @@ -1113,7 +1051,6 @@ TU_VERIFY_STATIC(sizeof(desc_ms_os_20) == MS_OS_20_DESC_LEN, "Incorrect size"); // End of section about desc_ms_os_20 """.format( - webusb_url=args.webusb_url, - webusb_interface=vendor_interface.bInterfaceNumber, + webusb_url=args.webusb_url, webusb_interface=vendor_interface.bInterfaceNumber ) ) diff --git a/tools/gendoc.py b/tools/gendoc.py index 85411cb410..bf79b3cf5f 100644 --- a/tools/gendoc.py +++ b/tools/gendoc.py @@ -19,10 +19,12 @@ def re_match_first(regexs, line): return name, match return None, None + def makedirs(d): if not os.path.isdir(d): os.makedirs(d) + class Lexer: class LexerError(Exception): pass @@ -35,15 +37,15 @@ class Lexer: def __init__(self, file): self.filename = file - with open(file, 'rt') as f: + with open(file, "rt") as f: line_num = 0 lines = [] for line in f: line_num += 1 line = line.strip() - if line == '///': - lines.append((line_num, '')) - elif line.startswith('/// '): + if line == "///": + lines.append((line_num, "")) + elif line.startswith("/// "): lines.append((line_num, line[4:])) elif len(lines) > 0 and lines[-1][1] is not None: lines.append((line_num, None)) @@ -68,9 +70,10 @@ class Lexer: return l[1] def error(self, msg): - print('({}:{}) {}'.format(self.filename, self.cur_line, msg)) + print("({}:{}) {}".format(self.filename, self.cur_line, msg)) raise Lexer.LexerError + class MarkdownWriter: def __init__(self): pass @@ -79,52 +82,53 @@ class MarkdownWriter: self.lines = [] def end(self): - return '\n'.join(self.lines) + return "\n".join(self.lines) def heading(self, level, text): if len(self.lines) > 0: - self.lines.append('') - self.lines.append(level * '#' + ' ' + text) - self.lines.append('') + self.lines.append("") + self.lines.append(level * "#" + " " + text) + self.lines.append("") def para(self, text): - if len(self.lines) > 0 and self.lines[-1] != '': - self.lines.append('') + if len(self.lines) > 0 and self.lines[-1] != "": + self.lines.append("") if isinstance(text, list): self.lines.extend(text) elif isinstance(text, str): self.lines.append(text) else: assert False - self.lines.append('') + self.lines.append("") def single_line(self, text): self.lines.append(text) def module(self, name, short_descr, descr): - self.heading(1, 'module {}'.format(name)) + self.heading(1, "module {}".format(name)) self.para(descr) def function(self, ctx, name, args, descr): - proto = '{}.{}{}'.format(ctx, self.name, self.args) - self.heading(3, '`' + proto + '`') + proto = "{}.{}{}".format(ctx, self.name, self.args) + self.heading(3, "`" + proto + "`") self.para(descr) def method(self, ctx, name, args, descr): - if name == '\\constructor': - proto = '{}{}'.format(ctx, args) - elif name == '\\call': - proto = '{}{}'.format(ctx, args) + if name == "\\constructor": + proto = "{}{}".format(ctx, args) + elif name == "\\call": + proto = "{}{}".format(ctx, args) else: - proto = '{}.{}{}'.format(ctx, name, args) - self.heading(3, '`' + proto + '`') + proto = "{}.{}{}".format(ctx, name, args) + self.heading(3, "`" + proto + "`") self.para(descr) def constant(self, ctx, name, descr): - self.single_line('`{}.{}` - {}'.format(ctx, name, descr)) + self.single_line("`{}.{}` - {}".format(ctx, name, descr)) + class ReStructuredTextWriter: - head_chars = {1:'=', 2:'-', 3:'.'} + head_chars = {1: "=", 2: "-", 3: "."} def __init__(self): pass @@ -133,23 +137,23 @@ class ReStructuredTextWriter: self.lines = [] def end(self): - return '\n'.join(self.lines) + return "\n".join(self.lines) def _convert(self, text): - return text.replace('`', '``').replace('*', '\\*') + return text.replace("`", "``").replace("*", "\\*") def heading(self, level, text, convert=True): if len(self.lines) > 0: - self.lines.append('') + self.lines.append("") if convert: text = self._convert(text) self.lines.append(text) self.lines.append(len(text) * self.head_chars[level]) - self.lines.append('') + self.lines.append("") - def para(self, text, indent=''): - if len(self.lines) > 0 and self.lines[-1] != '': - self.lines.append('') + def para(self, text, indent=""): + if len(self.lines) > 0 and self.lines[-1] != "": + self.lines.append("") if isinstance(text, list): for t in text: self.lines.append(indent + self._convert(t)) @@ -157,39 +161,41 @@ class ReStructuredTextWriter: self.lines.append(indent + self._convert(text)) else: assert False - self.lines.append('') + self.lines.append("") def single_line(self, text): self.lines.append(self._convert(text)) def module(self, name, short_descr, descr): - self.heading(1, ':mod:`{}` --- {}'.format(name, self._convert(short_descr)), convert=False) - self.lines.append('.. module:: {}'.format(name)) - self.lines.append(' :synopsis: {}'.format(short_descr)) + self.heading(1, ":mod:`{}` --- {}".format(name, self._convert(short_descr)), convert=False) + self.lines.append(".. module:: {}".format(name)) + self.lines.append(" :synopsis: {}".format(short_descr)) self.para(descr) def function(self, ctx, name, args, descr): args = self._convert(args) - self.lines.append('.. function:: ' + name + args) - self.para(descr, indent=' ') + self.lines.append(".. function:: " + name + args) + self.para(descr, indent=" ") def method(self, ctx, name, args, descr): args = self._convert(args) - if name == '\\constructor': - self.lines.append('.. class:: ' + ctx + args) - elif name == '\\call': - self.lines.append('.. method:: ' + ctx + args) + if name == "\\constructor": + self.lines.append(".. class:: " + ctx + args) + elif name == "\\call": + self.lines.append(".. method:: " + ctx + args) else: - self.lines.append('.. method:: ' + ctx + '.' + name + args) - self.para(descr, indent=' ') + self.lines.append(".. method:: " + ctx + "." + name + args) + self.para(descr, indent=" ") def constant(self, ctx, name, descr): - self.lines.append('.. data:: ' + name) - self.para(descr, indent=' ') + self.lines.append(".. data:: " + name) + self.para(descr, indent=" ") + class DocValidateError(Exception): pass + class DocItem: def __init__(self): self.doc = [] @@ -206,6 +212,7 @@ class DocItem: def dump(self, writer): writer.para(self.doc) + class DocConstant(DocItem): def __init__(self, name, descr): super().__init__() @@ -215,6 +222,7 @@ class DocConstant(DocItem): def dump(self, ctx, writer): writer.constant(ctx, self.name, self.descr) + class DocFunction(DocItem): def __init__(self, name, args): super().__init__() @@ -224,6 +232,7 @@ class DocFunction(DocItem): def dump(self, ctx, writer): writer.function(ctx, self.name, self.args, self.doc) + class DocMethod(DocItem): def __init__(self, name, args): super().__init__() @@ -233,6 +242,7 @@ class DocMethod(DocItem): def dump(self, ctx, writer): writer.method(ctx, self.name, self.args, self.doc) + class DocClass(DocItem): def __init__(self, name, descr): super().__init__() @@ -244,51 +254,52 @@ class DocClass(DocItem): self.constants = {} def process_classmethod(self, lex, d): - name = d['id'] - if name == '\\constructor': + name = d["id"] + if name == "\\constructor": dict_ = self.constructors else: dict_ = self.classmethods if name in dict_: lex.error("multiple definition of method '{}'".format(name)) - method = dict_[name] = DocMethod(name, d['args']) + method = dict_[name] = DocMethod(name, d["args"]) method.add_doc(lex) def process_method(self, lex, d): - name = d['id'] + name = d["id"] dict_ = self.methods if name in dict_: lex.error("multiple definition of method '{}'".format(name)) - method = dict_[name] = DocMethod(name, d['args']) + method = dict_[name] = DocMethod(name, d["args"]) method.add_doc(lex) def process_constant(self, lex, d): - name = d['id'] + name = d["id"] if name in self.constants: lex.error("multiple definition of constant '{}'".format(name)) - self.constants[name] = DocConstant(name, d['descr']) + self.constants[name] = DocConstant(name, d["descr"]) lex.opt_break() def dump(self, writer): - writer.heading(1, 'class {}'.format(self.name)) + writer.heading(1, "class {}".format(self.name)) super().dump(writer) if len(self.constructors) > 0: - writer.heading(2, 'Constructors') - for f in sorted(self.constructors.values(), key=lambda x:x.name): + writer.heading(2, "Constructors") + for f in sorted(self.constructors.values(), key=lambda x: x.name): f.dump(self.name, writer) if len(self.classmethods) > 0: - writer.heading(2, 'Class methods') - for f in sorted(self.classmethods.values(), key=lambda x:x.name): + writer.heading(2, "Class methods") + for f in sorted(self.classmethods.values(), key=lambda x: x.name): f.dump(self.name, writer) if len(self.methods) > 0: - writer.heading(2, 'Methods') - for f in sorted(self.methods.values(), key=lambda x:x.name): + writer.heading(2, "Methods") + for f in sorted(self.methods.values(), key=lambda x: x.name): f.dump(self.name.lower(), writer) if len(self.constants) > 0: - writer.heading(2, 'Constants') - for c in sorted(self.constants.values(), key=lambda x:x.name): + writer.heading(2, "Constants") + for c in sorted(self.constants.values(), key=lambda x: x.name): c.dump(self.name, writer) + class DocModule(DocItem): def __init__(self, name, descr): super().__init__() @@ -303,22 +314,22 @@ class DocModule(DocItem): self.cur_class = None def process_function(self, lex, d): - name = d['id'] + name = d["id"] if name in self.functions: lex.error("multiple definition of function '{}'".format(name)) - function = self.functions[name] = DocFunction(name, d['args']) + function = self.functions[name] = DocFunction(name, d["args"]) function.add_doc(lex) - #def process_classref(self, lex, d): + # def process_classref(self, lex, d): # name = d['id'] # self.classes[name] = name # lex.opt_break() def process_class(self, lex, d): - name = d['id'] + name = d["id"] if name in self.classes: lex.error("multiple definition of class '{}'".format(name)) - self.cur_class = self.classes[name] = DocClass(name, d['descr']) + self.cur_class = self.classes[name] = DocClass(name, d["descr"]) self.cur_class.add_doc(lex) def process_classmethod(self, lex, d): @@ -330,10 +341,10 @@ class DocModule(DocItem): def process_constant(self, lex, d): if self.cur_class is None: # a module-level constant - name = d['id'] + name = d["id"] if name in self.constants: lex.error("multiple definition of constant '{}'".format(name)) - self.constants[name] = DocConstant(name, d['descr']) + self.constants[name] = DocConstant(name, d["descr"]) lex.opt_break() else: # a class-level constant @@ -341,50 +352,51 @@ class DocModule(DocItem): def validate(self): if self.descr is None: - raise DocValidateError('module {} referenced but never defined'.format(self.name)) + raise DocValidateError("module {} referenced but never defined".format(self.name)) def dump(self, writer): writer.module(self.name, self.descr, self.doc) if self.functions: - writer.heading(2, 'Functions') - for f in sorted(self.functions.values(), key=lambda x:x.name): + writer.heading(2, "Functions") + for f in sorted(self.functions.values(), key=lambda x: x.name): f.dump(self.name, writer) if self.constants: - writer.heading(2, 'Constants') - for c in sorted(self.constants.values(), key=lambda x:x.name): + writer.heading(2, "Constants") + for c in sorted(self.constants.values(), key=lambda x: x.name): c.dump(self.name, writer) if self.classes: - writer.heading(2, 'Classes') - for c in sorted(self.classes.values(), key=lambda x:x.name): - writer.para('[`{}.{}`]({}) - {}'.format(self.name, c.name, c.name, c.descr)) + writer.heading(2, "Classes") + for c in sorted(self.classes.values(), key=lambda x: x.name): + writer.para("[`{}.{}`]({}) - {}".format(self.name, c.name, c.name, c.descr)) def write_html(self, dir): md_writer = MarkdownWriter() md_writer.start() self.dump(md_writer) - with open(os.path.join(dir, 'index.html'), 'wt') as f: + with open(os.path.join(dir, "index.html"), "wt") as f: f.write(markdown.markdown(md_writer.end())) for c in self.classes.values(): class_dir = os.path.join(dir, c.name) makedirs(class_dir) md_writer.start() - md_writer.para('part of the [{} module](./)'.format(self.name)) + md_writer.para("part of the [{} module](./)".format(self.name)) c.dump(md_writer) - with open(os.path.join(class_dir, 'index.html'), 'wt') as f: + with open(os.path.join(class_dir, "index.html"), "wt") as f: f.write(markdown.markdown(md_writer.end())) def write_rst(self, dir): rst_writer = ReStructuredTextWriter() rst_writer.start() self.dump(rst_writer) - with open(dir + '/' + self.name + '.rst', 'wt') as f: + with open(dir + "/" + self.name + ".rst", "wt") as f: f.write(rst_writer.end()) for c in self.classes.values(): rst_writer.start() c.dump(rst_writer) - with open(dir + '/' + self.name + '.' + c.name + '.rst', 'wt') as f: + with open(dir + "/" + self.name + "." + c.name + ".rst", "wt") as f: f.write(rst_writer.end()) + class Doc: def __init__(self): self.modules = {} @@ -397,20 +409,20 @@ class Doc: def check_module(self, lex): if self.cur_module is None: - lex.error('module not defined') + lex.error("module not defined") def process_module(self, lex, d): - name = d['id'] + name = d["id"] if name not in self.modules: self.modules[name] = DocModule(name, None) self.cur_module = self.modules[name] if self.cur_module.descr is not None: lex.error("multiple definition of module '{}'".format(name)) - self.cur_module.descr = d['descr'] + self.cur_module.descr = d["descr"] self.cur_module.add_doc(lex) def process_moduleref(self, lex, d): - name = d['id'] + name = d["id"] if name not in self.modules: self.modules[name] = DocModule(name, None) self.cur_module = self.modules[name] @@ -441,41 +453,46 @@ class Doc: m.validate() def dump(self, writer): - writer.heading(1, 'Modules') - writer.para('These are the Python modules that are implemented.') - for m in sorted(self.modules.values(), key=lambda x:x.name): - writer.para('[`{}`]({}/) - {}'.format(m.name, m.name, m.descr)) + writer.heading(1, "Modules") + writer.para("These are the Python modules that are implemented.") + for m in sorted(self.modules.values(), key=lambda x: x.name): + writer.para("[`{}`]({}/) - {}".format(m.name, m.name, m.descr)) def write_html(self, dir): md_writer = MarkdownWriter() - with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f: + with open(os.path.join(dir, "module", "index.html"), "wt") as f: md_writer.start() self.dump(md_writer) f.write(markdown.markdown(md_writer.end())) for m in self.modules.values(): - mod_dir = os.path.join(dir, 'module', m.name) + mod_dir = os.path.join(dir, "module", m.name) makedirs(mod_dir) m.write_html(mod_dir) def write_rst(self, dir): - #with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f: + # with open(os.path.join(dir, 'module', 'index.html'), 'wt') as f: # f.write(markdown.markdown(self.dump())) for m in self.modules.values(): m.write_rst(dir) -regex_descr = r'(?P.*)' + +regex_descr = r"(?P.*)" doc_regexs = ( - (Doc.process_module, re.compile(r'\\module (?P[a-z][a-z0-9]*) - ' + regex_descr + r'$')), - (Doc.process_moduleref, re.compile(r'\\moduleref (?P[a-z]+)$')), - (Doc.process_function, re.compile(r'\\function (?P[a-z0-9_]+)(?P\(.*\))$')), - (Doc.process_classmethod, re.compile(r'\\classmethod (?P\\?[a-z0-9_]+)(?P\(.*\))$')), - (Doc.process_method, re.compile(r'\\method (?P\\?[a-z0-9_]+)(?P\(.*\))$')), - (Doc.process_constant, re.compile(r'\\constant (?P[A-Za-z0-9_]+) - ' + regex_descr + r'$')), - #(Doc.process_classref, re.compile(r'\\classref (?P[A-Za-z0-9_]+)$')), - (Doc.process_class, re.compile(r'\\class (?P[A-Za-z0-9_]+) - ' + regex_descr + r'$')), + (Doc.process_module, re.compile(r"\\module (?P[a-z][a-z0-9]*) - " + regex_descr + r"$")), + (Doc.process_moduleref, re.compile(r"\\moduleref (?P[a-z]+)$")), + (Doc.process_function, re.compile(r"\\function (?P[a-z0-9_]+)(?P\(.*\))$")), + (Doc.process_classmethod, re.compile(r"\\classmethod (?P\\?[a-z0-9_]+)(?P\(.*\))$")), + (Doc.process_method, re.compile(r"\\method (?P\\?[a-z0-9_]+)(?P\(.*\))$")), + ( + Doc.process_constant, + re.compile(r"\\constant (?P[A-Za-z0-9_]+) - " + regex_descr + r"$"), + ), + # (Doc.process_classref, re.compile(r'\\classref (?P[A-Za-z0-9_]+)$')), + (Doc.process_class, re.compile(r"\\class (?P[A-Za-z0-9_]+) - " + regex_descr + r"$")), ) + def process_file(file, doc): lex = Lexer(file) doc.new_file() @@ -485,11 +502,11 @@ def process_file(file, doc): line = lex.next() fun, match = re_match_first(doc_regexs, line) if fun == None: - lex.error('unknown line format: {}'.format(line)) + lex.error("unknown line format: {}".format(line)) fun(doc, lex, match.groupdict()) except Lexer.Break: - lex.error('unexpected break') + lex.error("unexpected break") except Lexer.EOF: pass @@ -499,16 +516,21 @@ def process_file(file, doc): return True + def main(): - cmd_parser = argparse.ArgumentParser(description='Generate documentation for pyboard API from C files.') - cmd_parser.add_argument('--outdir', metavar='', default='gendoc-out', help='ouput directory') - cmd_parser.add_argument('--format', default='html', help='output format: html or rst') - cmd_parser.add_argument('files', nargs='+', help='input files') + cmd_parser = argparse.ArgumentParser( + description="Generate documentation for pyboard API from C files." + ) + cmd_parser.add_argument( + "--outdir", metavar="", default="gendoc-out", help="ouput directory" + ) + cmd_parser.add_argument("--format", default="html", help="output format: html or rst") + cmd_parser.add_argument("files", nargs="+", help="input files") args = cmd_parser.parse_args() doc = Doc() for file in args.files: - print('processing', file) + print("processing", file) if not process_file(file, doc): return try: @@ -518,15 +540,16 @@ def main(): makedirs(args.outdir) - if args.format == 'html': + if args.format == "html": doc.write_html(args.outdir) - elif args.format == 'rst': + elif args.format == "rst": doc.write_rst(args.outdir) else: - print('unknown format:', args.format) + print("unknown format:", args.format) return - print('written to', args.outdir) + print("written to", args.outdir) + if __name__ == "__main__": main() diff --git a/tools/hid_report_descriptors.py b/tools/hid_report_descriptors.py index aaa5b18b1f..827af3a3f0 100644 --- a/tools/hid_report_descriptors.py +++ b/tools/hid_report_descriptors.py @@ -18,17 +18,36 @@ from adafruit_usb_descriptor import hid # Information about each kind of device # report_length does not include report ID in first byte, if present when sent. -DeviceData = namedtuple('DeviceData', ('report_length', 'out_report_length', 'usage_page', 'usage')) +DeviceData = namedtuple( + "DeviceData", ("report_length", "out_report_length", "usage_page", "usage") +) HID_DEVICE_DATA = { - "KEYBOARD" : DeviceData(report_length=8, out_report_length=1, usage_page=0x01, usage=0x06), # Generic Desktop, Keyboard - "MOUSE" : DeviceData(report_length=4, out_report_length=0, usage_page=0x01, usage=0x02), # Generic Desktop, Mouse - "CONSUMER" : DeviceData(report_length=2, out_report_length=0, usage_page=0x0C, usage=0x01), # Consumer, Consumer Control - "SYS_CONTROL" : DeviceData(report_length=1, out_report_length=0, usage_page=0x01, usage=0x80), # Generic Desktop, Sys Control - "GAMEPAD" : DeviceData(report_length=6, out_report_length=0, usage_page=0x01, usage=0x05), # Generic Desktop, Game Pad - "DIGITIZER" : DeviceData(report_length=5, out_report_length=0, usage_page=0x0D, usage=0x02), # Digitizers, Pen - "XAC_COMPATIBLE_GAMEPAD" : DeviceData(report_length=3, out_report_length=0, usage_page=0x01, usage=0x05), # Generic Desktop, Game Pad - "RAW" : DeviceData(report_length=64, out_report_length=0, usage_page=0xFFAF, usage=0xAF), # Vendor 0xFFAF "Adafruit", 0xAF - } + "KEYBOARD": DeviceData( + report_length=8, out_report_length=1, usage_page=0x01, usage=0x06 + ), # Generic Desktop, Keyboard + "MOUSE": DeviceData( + report_length=4, out_report_length=0, usage_page=0x01, usage=0x02 + ), # Generic Desktop, Mouse + "CONSUMER": DeviceData( + report_length=2, out_report_length=0, usage_page=0x0C, usage=0x01 + ), # Consumer, Consumer Control + "SYS_CONTROL": DeviceData( + report_length=1, out_report_length=0, usage_page=0x01, usage=0x80 + ), # Generic Desktop, Sys Control + "GAMEPAD": DeviceData( + report_length=6, out_report_length=0, usage_page=0x01, usage=0x05 + ), # Generic Desktop, Game Pad + "DIGITIZER": DeviceData( + report_length=5, out_report_length=0, usage_page=0x0D, usage=0x02 + ), # Digitizers, Pen + "XAC_COMPATIBLE_GAMEPAD": DeviceData( + report_length=3, out_report_length=0, usage_page=0x01, usage=0x05 + ), # Generic Desktop, Game Pad + "RAW": DeviceData( + report_length=64, out_report_length=0, usage_page=0xFFAF, usage=0xAF + ), # Vendor 0xFFAF "Adafruit", 0xAF +} + def keyboard_hid_descriptor(report_id): data = HID_DEVICE_DATA["KEYBOARD"] @@ -36,39 +55,73 @@ def keyboard_hid_descriptor(report_id): description="KEYBOARD", report_descriptor=bytes( # Regular keyboard - (0x05, data.usage_page, # Usage Page (Generic Desktop) - 0x09, data.usage, # Usage (Keyboard) - 0xA1, 0x01, # Collection (Application) - ) + - ((0x85, report_id) if report_id != 0 else ()) + - (0x05, 0x07, # Usage Page (Keyboard) - 0x19, 224, # Usage Minimum (224) - 0x29, 231, # Usage Maximum (231) - 0x15, 0x00, # Logical Minimum (0) - 0x25, 0x01, # Logical Maximum (1) - 0x75, 0x01, # Report Size (1) - 0x95, 0x08, # Report Count (8) - 0x81, 0x02, # Input (Data, Variable, Absolute) - 0x81, 0x01, # Input (Constant) - 0x19, 0x00, # Usage Minimum (0) - 0x29, 0xDD, # Usage Maximum (221) - 0x15, 0x00, # Logical Minimum (0) - 0x25, 0xDD, # Logical Maximum (221) - 0x75, 0x08, # Report Size (8) - 0x95, 0x06, # Report Count (6) - 0x81, 0x00, # Input (Data, Array) - 0x05, 0x08, # Usage Page (LED) - 0x19, 0x01, # Usage Minimum (1) - 0x29, 0x05, # Usage Maximum (5) - 0x15, 0x00, # Logical Minimum (0) - 0x25, 0x01, # Logical Maximum (1) - 0x75, 0x01, # Report Size (1) - 0x95, 0x05, # Report Count (5) - 0x91, 0x02, # Output (Data, Variable, Absolute) - 0x95, 0x03, # Report Count (3) - 0x91, 0x01, # Output (Constant) - 0xC0, # End Collection - ))) + ( + 0x05, + data.usage_page, # Usage Page (Generic Desktop) + 0x09, + data.usage, # Usage (Keyboard) + 0xA1, + 0x01, # Collection (Application) + ) + + ((0x85, report_id) if report_id != 0 else ()) + + ( + 0x05, + 0x07, # Usage Page (Keyboard) + 0x19, + 224, # Usage Minimum (224) + 0x29, + 231, # Usage Maximum (231) + 0x15, + 0x00, # Logical Minimum (0) + 0x25, + 0x01, # Logical Maximum (1) + 0x75, + 0x01, # Report Size (1) + 0x95, + 0x08, # Report Count (8) + 0x81, + 0x02, # Input (Data, Variable, Absolute) + 0x81, + 0x01, # Input (Constant) + 0x19, + 0x00, # Usage Minimum (0) + 0x29, + 0xDD, # Usage Maximum (221) + 0x15, + 0x00, # Logical Minimum (0) + 0x25, + 0xDD, # Logical Maximum (221) + 0x75, + 0x08, # Report Size (8) + 0x95, + 0x06, # Report Count (6) + 0x81, + 0x00, # Input (Data, Array) + 0x05, + 0x08, # Usage Page (LED) + 0x19, + 0x01, # Usage Minimum (1) + 0x29, + 0x05, # Usage Maximum (5) + 0x15, + 0x00, # Logical Minimum (0) + 0x25, + 0x01, # Logical Maximum (1) + 0x75, + 0x01, # Report Size (1) + 0x95, + 0x05, # Report Count (5) + 0x91, + 0x02, # Output (Data, Variable, Absolute) + 0x95, + 0x03, # Report Count (3) + 0x91, + 0x01, # Output (Constant) + 0xC0, # End Collection + ) + ), + ) + def mouse_hid_descriptor(report_id): data = HID_DEVICE_DATA["MOUSE"] @@ -76,41 +129,76 @@ def mouse_hid_descriptor(report_id): description="MOUSE", report_descriptor=bytes( # Regular mouse - (0x05, data.usage_page, # Usage Page (Generic Desktop) - 0x09, data.usage, # Usage (Mouse) - 0xA1, 0x01, # Collection (Application) - 0x09, 0x01, # Usage (Pointer) - 0xA1, 0x00, # Collection (Physical) - ) + - ((0x85, report_id) if report_id != 0 else ()) + - (0x05, 0x09, # Usage Page (Button) - 0x19, 0x01, # Usage Minimum (0x01) - 0x29, 0x05, # Usage Maximum (0x05) - 0x15, 0x00, # Logical Minimum (0) - 0x25, 0x01, # Logical Maximum (1) - 0x95, 0x05, # Report Count (5) - 0x75, 0x01, # Report Size (1) - 0x81, 0x02, # Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0x95, 0x01, # Report Count (1) - 0x75, 0x03, # Report Size (3) - 0x81, 0x01, # Input (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0x05, 0x01, # Usage Page (Generic Desktop Ctrls) - 0x09, 0x30, # Usage (X) - 0x09, 0x31, # Usage (Y) - 0x15, 0x81, # Logical Minimum (-127) - 0x25, 0x7F, # Logical Maximum (127) - 0x75, 0x08, # Report Size (8) - 0x95, 0x02, # Report Count (2) - 0x81, 0x06, # Input (Data,Var,Rel,No Wrap,Linear,Preferred State,No Null Position) - 0x09, 0x38, # Usage (Wheel) - 0x15, 0x81, # Logical Minimum (-127) - 0x25, 0x7F, # Logical Maximum (127) - 0x75, 0x08, # Report Size (8) - 0x95, 0x01, # Report Count (1) - 0x81, 0x06, # Input (Data,Var,Rel,No Wrap,Linear,Preferred State,No Null Position) - 0xC0, # End Collection - 0xC0, # End Collection - ))) + ( + 0x05, + data.usage_page, # Usage Page (Generic Desktop) + 0x09, + data.usage, # Usage (Mouse) + 0xA1, + 0x01, # Collection (Application) + 0x09, + 0x01, # Usage (Pointer) + 0xA1, + 0x00, # Collection (Physical) + ) + + ((0x85, report_id) if report_id != 0 else ()) + + ( + 0x05, + 0x09, # Usage Page (Button) + 0x19, + 0x01, # Usage Minimum (0x01) + 0x29, + 0x05, # Usage Maximum (0x05) + 0x15, + 0x00, # Logical Minimum (0) + 0x25, + 0x01, # Logical Maximum (1) + 0x95, + 0x05, # Report Count (5) + 0x75, + 0x01, # Report Size (1) + 0x81, + 0x02, # Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0x95, + 0x01, # Report Count (1) + 0x75, + 0x03, # Report Size (3) + 0x81, + 0x01, # Input (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0x05, + 0x01, # Usage Page (Generic Desktop Ctrls) + 0x09, + 0x30, # Usage (X) + 0x09, + 0x31, # Usage (Y) + 0x15, + 0x81, # Logical Minimum (-127) + 0x25, + 0x7F, # Logical Maximum (127) + 0x75, + 0x08, # Report Size (8) + 0x95, + 0x02, # Report Count (2) + 0x81, + 0x06, # Input (Data,Var,Rel,No Wrap,Linear,Preferred State,No Null Position) + 0x09, + 0x38, # Usage (Wheel) + 0x15, + 0x81, # Logical Minimum (-127) + 0x25, + 0x7F, # Logical Maximum (127) + 0x75, + 0x08, # Report Size (8) + 0x95, + 0x01, # Report Count (1) + 0x81, + 0x06, # Input (Data,Var,Rel,No Wrap,Linear,Preferred State,No Null Position) + 0xC0, # End Collection + 0xC0, # End Collection + ) + ), + ) + def consumer_hid_descriptor(report_id): data = HID_DEVICE_DATA["CONSUMER"] @@ -118,20 +206,37 @@ def consumer_hid_descriptor(report_id): description="CONSUMER", report_descriptor=bytes( # Consumer ("multimedia") keys - (0x05, data.usage_page, # Usage Page (Consumer) - 0x09, data.usage, # Usage (Consumer Control) - 0xA1, 0x01, # Collection (Application) - ) + - ((0x85, report_id) if report_id != 0 else ()) + - (0x75, 0x10, # Report Size (16) - 0x95, 0x01, # Report Count (1) - 0x15, 0x01, # Logical Minimum (1) - 0x26, 0x8C, 0x02, # Logical Maximum (652) - 0x19, 0x01, # Usage Minimum (Consumer Control) - 0x2A, 0x8C, 0x02, # Usage Maximum (AC Send) - 0x81, 0x00, # Input (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0xC0, # End Collection - ))) + ( + 0x05, + data.usage_page, # Usage Page (Consumer) + 0x09, + data.usage, # Usage (Consumer Control) + 0xA1, + 0x01, # Collection (Application) + ) + + ((0x85, report_id) if report_id != 0 else ()) + + ( + 0x75, + 0x10, # Report Size (16) + 0x95, + 0x01, # Report Count (1) + 0x15, + 0x01, # Logical Minimum (1) + 0x26, + 0x8C, + 0x02, # Logical Maximum (652) + 0x19, + 0x01, # Usage Minimum (Consumer Control) + 0x2A, + 0x8C, + 0x02, # Usage Maximum (AC Send) + 0x81, + 0x00, # Input (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0xC0, # End Collection + ) + ), + ) + def sys_control_hid_descriptor(report_id): data = HID_DEVICE_DATA["SYS_CONTROL"] @@ -139,23 +244,41 @@ def sys_control_hid_descriptor(report_id): description="SYS_CONTROL", report_descriptor=bytes( # Power controls - (0x05, data.usage_page, # Usage Page (Generic Desktop Ctrls) - 0x09, data.usage, # Usage (Sys Control) - 0xA1, 0x01, # Collection (Application) - ) + - ((0x85, report_id) if report_id != 0 else ()) + - (0x75, 0x02, # Report Size (2) - 0x95, 0x01, # Report Count (1) - 0x15, 0x01, # Logical Minimum (1) - 0x25, 0x03, # Logical Maximum (3) - 0x09, 0x82, # Usage (Sys Sleep) - 0x09, 0x81, # Usage (Sys Power Down) - 0x09, 0x83, # Usage (Sys Wake Up) - 0x81, 0x60, # Input (Data,Array,Abs,No Wrap,Linear,No Preferred State,Null State) - 0x75, 0x06, # Report Size (6) - 0x81, 0x03, # Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0xC0, # End Collection - ))) + ( + 0x05, + data.usage_page, # Usage Page (Generic Desktop Ctrls) + 0x09, + data.usage, # Usage (Sys Control) + 0xA1, + 0x01, # Collection (Application) + ) + + ((0x85, report_id) if report_id != 0 else ()) + + ( + 0x75, + 0x02, # Report Size (2) + 0x95, + 0x01, # Report Count (1) + 0x15, + 0x01, # Logical Minimum (1) + 0x25, + 0x03, # Logical Maximum (3) + 0x09, + 0x82, # Usage (Sys Sleep) + 0x09, + 0x81, # Usage (Sys Power Down) + 0x09, + 0x83, # Usage (Sys Wake Up) + 0x81, + 0x60, # Input (Data,Array,Abs,No Wrap,Linear,No Preferred State,Null State) + 0x75, + 0x06, # Report Size (6) + 0x81, + 0x03, # Input (Const,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0xC0, # End Collection + ) + ), + ) + def gamepad_hid_descriptor(report_id): data = HID_DEVICE_DATA["GAMEPAD"] @@ -163,31 +286,57 @@ def gamepad_hid_descriptor(report_id): description="GAMEPAD", report_descriptor=bytes( # Gamepad with 16 buttons and two joysticks - (0x05, data.usage_page, # Usage Page (Generic Desktop Ctrls) - 0x09, data.usage, # Usage (Game Pad) - 0xA1, 0x01, # Collection (Application) - ) + - ((0x85, report_id) if report_id != 0 else ()) + - (0x05, 0x09, # Usage Page (Button) - 0x19, 0x01, # Usage Minimum (Button 1) - 0x29, 0x10, # Usage Maximum (Button 16) - 0x15, 0x00, # Logical Minimum (0) - 0x25, 0x01, # Logical Maximum (1) - 0x75, 0x01, # Report Size (1) - 0x95, 0x10, # Report Count (16) - 0x81, 0x02, # Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0x05, 0x01, # Usage Page (Generic Desktop Ctrls) - 0x15, 0x81, # Logical Minimum (-127) - 0x25, 0x7F, # Logical Maximum (127) - 0x09, 0x30, # Usage (X) - 0x09, 0x31, # Usage (Y) - 0x09, 0x32, # Usage (Z) - 0x09, 0x35, # Usage (Rz) - 0x75, 0x08, # Report Size (8) - 0x95, 0x04, # Report Count (4) - 0x81, 0x02, # Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0xC0, # End Collection - ))) + ( + 0x05, + data.usage_page, # Usage Page (Generic Desktop Ctrls) + 0x09, + data.usage, # Usage (Game Pad) + 0xA1, + 0x01, # Collection (Application) + ) + + ((0x85, report_id) if report_id != 0 else ()) + + ( + 0x05, + 0x09, # Usage Page (Button) + 0x19, + 0x01, # Usage Minimum (Button 1) + 0x29, + 0x10, # Usage Maximum (Button 16) + 0x15, + 0x00, # Logical Minimum (0) + 0x25, + 0x01, # Logical Maximum (1) + 0x75, + 0x01, # Report Size (1) + 0x95, + 0x10, # Report Count (16) + 0x81, + 0x02, # Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0x05, + 0x01, # Usage Page (Generic Desktop Ctrls) + 0x15, + 0x81, # Logical Minimum (-127) + 0x25, + 0x7F, # Logical Maximum (127) + 0x09, + 0x30, # Usage (X) + 0x09, + 0x31, # Usage (Y) + 0x09, + 0x32, # Usage (Z) + 0x09, + 0x35, # Usage (Rz) + 0x75, + 0x08, # Report Size (8) + 0x95, + 0x04, # Report Count (4) + 0x81, + 0x02, # Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0xC0, # End Collection + ) + ), + ) + def digitizer_hid_descriptor(report_id): data = HID_DEVICE_DATA["DIGITIZER"] @@ -195,36 +344,67 @@ def digitizer_hid_descriptor(report_id): description="DIGITIZER", report_descriptor=bytes( # Digitizer (used as an absolute pointer) - (0x05, data.usage_page, # Usage Page (Digitizers) - 0x09, data.usage, # Usage (Pen) - 0xA1, 0x01, # Collection (Application) - ) + - ((0x85, report_id) if report_id != 0 else ()) + - (0x09, 0x01, # Usage (Stylus) - 0xA1, 0x00, # Collection (Physical) - 0x09, 0x32, # Usage (In-Range) - 0x09, 0x42, # Usage (Tip Switch) - 0x09, 0x44, # Usage (Barrel Switch) - 0x09, 0x45, # Usage (Eraser Switch) - 0x15, 0x00, # Logical Minimum (0) - 0x25, 0x01, # Logical Maximum (1) - 0x75, 0x01, # Report Size (1) - 0x95, 0x04, # Report Count (4) - 0x81, 0x02, # Input (Data,Var,Abs) - 0x75, 0x04, # Report Size (4) -- Filler - 0x95, 0x01, # Report Count (1) -- Filler - 0x81, 0x01, # Input (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0x05, 0x01, # Usage Page (Generic Desktop Ctrls) - 0x15, 0x00, # Logical Minimum (0) - 0x26, 0xff, 0x7f, # Logical Maximum (32767) - 0x09, 0x30, # Usage (X) - 0x09, 0x31, # Usage (Y) - 0x75, 0x10, # Report Size (16) - 0x95, 0x02, # Report Count (2) - 0x81, 0x02, # Input (Data,Var,Abs) - 0xC0, # End Collection - 0xC0, # End Collection - ))) + ( + 0x05, + data.usage_page, # Usage Page (Digitizers) + 0x09, + data.usage, # Usage (Pen) + 0xA1, + 0x01, # Collection (Application) + ) + + ((0x85, report_id) if report_id != 0 else ()) + + ( + 0x09, + 0x01, # Usage (Stylus) + 0xA1, + 0x00, # Collection (Physical) + 0x09, + 0x32, # Usage (In-Range) + 0x09, + 0x42, # Usage (Tip Switch) + 0x09, + 0x44, # Usage (Barrel Switch) + 0x09, + 0x45, # Usage (Eraser Switch) + 0x15, + 0x00, # Logical Minimum (0) + 0x25, + 0x01, # Logical Maximum (1) + 0x75, + 0x01, # Report Size (1) + 0x95, + 0x04, # Report Count (4) + 0x81, + 0x02, # Input (Data,Var,Abs) + 0x75, + 0x04, # Report Size (4) -- Filler + 0x95, + 0x01, # Report Count (1) -- Filler + 0x81, + 0x01, # Input (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0x05, + 0x01, # Usage Page (Generic Desktop Ctrls) + 0x15, + 0x00, # Logical Minimum (0) + 0x26, + 0xFF, + 0x7F, # Logical Maximum (32767) + 0x09, + 0x30, # Usage (X) + 0x09, + 0x31, # Usage (Y) + 0x75, + 0x10, # Report Size (16) + 0x95, + 0x02, # Report Count (2) + 0x81, + 0x02, # Input (Data,Var,Abs) + 0xC0, # End Collection + 0xC0, # End Collection + ) + ), + ) + def xac_compatible_gamepad_hid_descriptor(report_id): data = HID_DEVICE_DATA["XAC_COMPATIBLE_GAMEPAD"] @@ -232,31 +412,59 @@ def xac_compatible_gamepad_hid_descriptor(report_id): description="XAC", report_descriptor=bytes( # This descriptor mimics the simple joystick from PDP that the XBox likes - (0x05, data.usage_page, # Usage Page (Desktop), - 0x09, data.usage, # Usage (Gamepad), - 0xA1, 0x01, # Collection (Application), - ) + - ((0x85, report_id) if report_id != 0 else ()) + - (0x15, 0x00, # Logical Minimum (0), - 0x25, 0x01, # Logical Maximum (1), - 0x35, 0x00, # Physical Minimum (0), - 0x45, 0x01, # Physical Maximum (1), - 0x75, 0x01, # Report Size (1), - 0x95, 0x08, # Report Count (8), - 0x05, 0x09, # Usage Page (Button), - 0x19, 0x01, # Usage Minimum (01h), - 0x29, 0x08, # Usage Maximum (08h), - 0x81, 0x02, # Input (Variable), - 0x05, 0x01, # Usage Page (Desktop), - 0x26, 0xFF, 0x00, # Logical Maximum (255), - 0x46, 0xFF, 0x00, # Physical Maximum (255), - 0x09, 0x30, # Usage (X), - 0x09, 0x31, # Usage (Y), - 0x75, 0x08, # Report Size (8), - 0x95, 0x02, # Report Count (2), - 0x81, 0x02, # Input (Variable), - 0xC0 # End Collection - ))) + ( + 0x05, + data.usage_page, # Usage Page (Desktop), + 0x09, + data.usage, # Usage (Gamepad), + 0xA1, + 0x01, # Collection (Application), + ) + + ((0x85, report_id) if report_id != 0 else ()) + + ( + 0x15, + 0x00, # Logical Minimum (0), + 0x25, + 0x01, # Logical Maximum (1), + 0x35, + 0x00, # Physical Minimum (0), + 0x45, + 0x01, # Physical Maximum (1), + 0x75, + 0x01, # Report Size (1), + 0x95, + 0x08, # Report Count (8), + 0x05, + 0x09, # Usage Page (Button), + 0x19, + 0x01, # Usage Minimum (01h), + 0x29, + 0x08, # Usage Maximum (08h), + 0x81, + 0x02, # Input (Variable), + 0x05, + 0x01, # Usage Page (Desktop), + 0x26, + 0xFF, + 0x00, # Logical Maximum (255), + 0x46, + 0xFF, + 0x00, # Physical Maximum (255), + 0x09, + 0x30, # Usage (X), + 0x09, + 0x31, # Usage (Y), + 0x75, + 0x08, # Report Size (8), + 0x95, + 0x02, # Report Count (2), + 0x81, + 0x02, # Input (Variable), + 0xC0, # End Collection + ) + ), + ) + def raw_hid_descriptor(report_id): if report_id != 0: @@ -267,29 +475,47 @@ def raw_hid_descriptor(report_id): report_descriptor=bytes( # Provide vendor-defined # This is a two-byte page value. - (0x06, data.usage_page & 0xff, (data.usage_page >> 8) & 0xff, # Usage Page (Vendor 0xFFAF "Adafruit"), - 0x09, data.usage, # Usage (AF), - 0xA1, 0x01, # Collection (Application), - 0x75, 0x08, # Report Size (8), - 0x15, 0x00, # Logical Minimum (0), - 0x26, 0xFF, 0x00, # Logical Maximum (255), - 0x95, 0x08, # Report Count (8), - 0x09, 0x01, # Usage(xxx) - 0x81, 0x02, # Input (Variable) - 0x95, 0x08, # Report Count (8), - 0x09, 0x02, # Usage(xxx) - 0x91, 0x02, # Input (Variable) - 0xC0 # End Collection - ))) + ( + 0x06, + data.usage_page & 0xFF, + (data.usage_page >> 8) & 0xFF, # Usage Page (Vendor 0xFFAF "Adafruit"), + 0x09, + data.usage, # Usage (AF), + 0xA1, + 0x01, # Collection (Application), + 0x75, + 0x08, # Report Size (8), + 0x15, + 0x00, # Logical Minimum (0), + 0x26, + 0xFF, + 0x00, # Logical Maximum (255), + 0x95, + 0x08, # Report Count (8), + 0x09, + 0x01, # Usage(xxx) + 0x81, + 0x02, # Input (Variable) + 0x95, + 0x08, # Report Count (8), + 0x09, + 0x02, # Usage(xxx) + 0x91, + 0x02, # Input (Variable) + 0xC0, # End Collection + ) + ), + ) + # Function to call for each kind of HID descriptor. REPORT_DESCRIPTOR_FUNCTIONS = { - "KEYBOARD" : keyboard_hid_descriptor, - "MOUSE" : mouse_hid_descriptor, - "CONSUMER" : consumer_hid_descriptor, - "SYS_CONTROL" : sys_control_hid_descriptor, - "GAMEPAD" : gamepad_hid_descriptor, - "DIGITIZER" : digitizer_hid_descriptor, - "XAC_COMPATIBLE_GAMEPAD" : xac_compatible_gamepad_hid_descriptor, - "RAW" : raw_hid_descriptor, + "KEYBOARD": keyboard_hid_descriptor, + "MOUSE": mouse_hid_descriptor, + "CONSUMER": consumer_hid_descriptor, + "SYS_CONTROL": sys_control_hid_descriptor, + "GAMEPAD": gamepad_hid_descriptor, + "DIGITIZER": digitizer_hid_descriptor, + "XAC_COMPATIBLE_GAMEPAD": xac_compatible_gamepad_hid_descriptor, + "RAW": raw_hid_descriptor, } diff --git a/tools/insert-usb-ids.py b/tools/insert-usb-ids.py index bf74ceeab5..f63059ca1b 100644 --- a/tools/insert-usb-ids.py +++ b/tools/insert-usb-ids.py @@ -12,15 +12,16 @@ import sys import re import string -needed_keys = ('USB_PID_CDC_MSC', 'USB_PID_CDC_HID', 'USB_PID_CDC', 'USB_VID') +needed_keys = ("USB_PID_CDC_MSC", "USB_PID_CDC_HID", "USB_PID_CDC", "USB_VID") + def parse_usb_ids(filename): rv = dict() for line in open(filename).readlines(): - line = line.rstrip('\r\n') - match = re.match('^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$', line) - if match and match.group(1).startswith('USBD_'): - key = match.group(1).replace('USBD', 'USB') + line = line.rstrip("\r\n") + match = re.match("^#define\s+(\w+)\s+\(0x([0-9A-Fa-f]+)\)$", line) + if match and match.group(1).startswith("USBD_"): + key = match.group(1).replace("USBD", "USB") val = match.group(2) print("key =", key, "val =", val) if key in needed_keys: @@ -30,9 +31,10 @@ def parse_usb_ids(filename): raise Exception("Unable to parse %s from %s" % (k, filename)) return rv + if __name__ == "__main__": usb_ids_file = sys.argv[1] template_file = sys.argv[2] replacements = parse_usb_ids(usb_ids_file) - for line in open(template_file, 'r').readlines(): - print(string.Template(line).safe_substitute(replacements), end='') + for line in open(template_file, "r").readlines(): + print(string.Template(line).safe_substitute(replacements), end="") diff --git a/tools/make-frozen.py b/tools/make-frozen.py index ad23b9d595..f9ffa76421 100755 --- a/tools/make-frozen.py +++ b/tools/make-frozen.py @@ -30,6 +30,7 @@ import os def module_name(f): return f + modules = [] root = sys.argv[1].rstrip("/") @@ -39,7 +40,7 @@ for dirpath, dirnames, filenames in os.walk(root): for f in filenames: fullpath = dirpath + "/" + f st = os.stat(fullpath) - modules.append((fullpath[root_len + 1:], st)) + modules.append((fullpath[root_len + 1 :], st)) print("#include ") print("const char mp_frozen_str_names[] = {") @@ -66,8 +67,8 @@ for f, st in modules: # data. We could just encode all characters as hex digits but it's nice # to be able to read the resulting C code as ASCII when possible. - data = bytearray(data) # so Python2 extracts each byte as an integer - esc_dict = {ord('\n'): '\\n', ord('\r'): '\\r', ord('"'): '\\"', ord('\\'): '\\\\'} + data = bytearray(data) # so Python2 extracts each byte as an integer + esc_dict = {ord("\n"): "\\n", ord("\r"): "\\r", ord('"'): '\\"', ord("\\"): "\\\\"} chrs = ['"'] break_str = False for c in data: @@ -80,9 +81,9 @@ for f, st in modules: break_str = False chrs.append(chr(c)) else: - chrs.append('\\x%02x' % c) + chrs.append("\\x%02x" % c) break_str = True chrs.append('\\0"') - print(''.join(chrs)) + print("".join(chrs)) print("};") diff --git a/tools/mpconfig_category_reader.py b/tools/mpconfig_category_reader.py index 2f813931e8..7c2aede5b9 100644 --- a/tools/mpconfig_category_reader.py +++ b/tools/mpconfig_category_reader.py @@ -1,4 +1,4 @@ -filepath = '../py/circuitpy_mpconfig.mk' +filepath = "../py/circuitpy_mpconfig.mk" with open(filepath) as fp: line = fp.readline() cnt = 1 diff --git a/tools/mpy-tool.py b/tools/mpy-tool.py index 95090466c4..c989b63007 100755 --- a/tools/mpy-tool.py +++ b/tools/mpy-tool.py @@ -8,7 +8,8 @@ # Python 2/3 compatibility code from __future__ import print_function import platform -if platform.python_version_tuple()[0] == '2': + +if platform.python_version_tuple()[0] == "2": str_cons = lambda val, enc=None: val bytes_cons = lambda val, enc=None: bytearray(val) is_str_type = lambda o: type(o) is str @@ -26,22 +27,26 @@ import sys import struct from collections import namedtuple -sys.path.append(sys.path[0] + '/../py') +sys.path.append(sys.path[0] + "/../py") import makeqstrdata as qstrutil + class FreezeError(Exception): def __init__(self, rawcode, msg): self.rawcode = rawcode self.msg = msg def __str__(self): - return 'error while freezing %s: %s' % (self.rawcode.source_file, self.msg) + return "error while freezing %s: %s" % (self.rawcode.source_file, self.msg) + class Config: MPY_VERSION = 3 MICROPY_LONGINT_IMPL_NONE = 0 MICROPY_LONGINT_IMPL_LONGLONG = 1 MICROPY_LONGINT_IMPL_MPZ = 2 + + config = Config() MP_OPCODE_BYTE = 0 @@ -52,11 +57,11 @@ MP_OPCODE_OFFSET = 3 # extra bytes: MP_BC_MAKE_CLOSURE = 0x62 MP_BC_MAKE_CLOSURE_DEFARGS = 0x63 -MP_BC_RAISE_VARARGS = 0x5c +MP_BC_RAISE_VARARGS = 0x5C # extra byte if caching enabled: -MP_BC_LOAD_NAME = 0x1c -MP_BC_LOAD_GLOBAL = 0x1d -MP_BC_LOAD_ATTR = 0x1e +MP_BC_LOAD_NAME = 0x1C +MP_BC_LOAD_GLOBAL = 0x1D +MP_BC_LOAD_ATTR = 0x1E MP_BC_STORE_ATTR = 0x26 # load opcode names @@ -71,87 +76,86 @@ with open("../../py/bc0.h") as f: opcode = int(value.strip("()"), 0) opcode_names[opcode] = name + def make_opcode_format(): def OC4(a, b, c, d): return a | (b << 2) | (c << 4) | (d << 6) + U = 0 B = 0 Q = 1 V = 2 O = 3 - return bytes_cons(( - # this table is taken verbatim from py/bc.c - OC4(U, U, U, U), # 0x00-0x03 - OC4(U, U, U, U), # 0x04-0x07 - OC4(U, U, U, U), # 0x08-0x0b - OC4(U, U, U, U), # 0x0c-0x0f - OC4(B, B, B, U), # 0x10-0x13 - OC4(V, U, Q, V), # 0x14-0x17 - OC4(B, V, V, Q), # 0x18-0x1b - OC4(Q, Q, Q, Q), # 0x1c-0x1f - OC4(B, B, V, V), # 0x20-0x23 - OC4(Q, Q, Q, B), # 0x24-0x27 - OC4(V, V, Q, Q), # 0x28-0x2b - OC4(U, U, U, U), # 0x2c-0x2f - OC4(B, B, B, B), # 0x30-0x33 - OC4(B, O, O, O), # 0x34-0x37 - OC4(O, O, U, U), # 0x38-0x3b - OC4(U, O, B, O), # 0x3c-0x3f - OC4(O, B, B, O), # 0x40-0x43 - OC4(B, B, O, B), # 0x44-0x47 - OC4(U, U, U, U), # 0x48-0x4b - OC4(U, U, U, U), # 0x4c-0x4f - OC4(V, V, U, V), # 0x50-0x53 - OC4(B, U, V, V), # 0x54-0x57 - OC4(V, V, V, B), # 0x58-0x5b - OC4(B, B, B, U), # 0x5c-0x5f - OC4(V, V, V, V), # 0x60-0x63 - OC4(V, V, V, V), # 0x64-0x67 - OC4(Q, Q, B, U), # 0x68-0x6b - OC4(U, U, U, U), # 0x6c-0x6f + return bytes_cons( + ( + # this table is taken verbatim from py/bc.c + OC4(U, U, U, U), # 0x00-0x03 + OC4(U, U, U, U), # 0x04-0x07 + OC4(U, U, U, U), # 0x08-0x0b + OC4(U, U, U, U), # 0x0c-0x0f + OC4(B, B, B, U), # 0x10-0x13 + OC4(V, U, Q, V), # 0x14-0x17 + OC4(B, V, V, Q), # 0x18-0x1b + OC4(Q, Q, Q, Q), # 0x1c-0x1f + OC4(B, B, V, V), # 0x20-0x23 + OC4(Q, Q, Q, B), # 0x24-0x27 + OC4(V, V, Q, Q), # 0x28-0x2b + OC4(U, U, U, U), # 0x2c-0x2f + OC4(B, B, B, B), # 0x30-0x33 + OC4(B, O, O, O), # 0x34-0x37 + OC4(O, O, U, U), # 0x38-0x3b + OC4(U, O, B, O), # 0x3c-0x3f + OC4(O, B, B, O), # 0x40-0x43 + OC4(B, B, O, B), # 0x44-0x47 + OC4(U, U, U, U), # 0x48-0x4b + OC4(U, U, U, U), # 0x4c-0x4f + OC4(V, V, U, V), # 0x50-0x53 + OC4(B, U, V, V), # 0x54-0x57 + OC4(V, V, V, B), # 0x58-0x5b + OC4(B, B, B, U), # 0x5c-0x5f + OC4(V, V, V, V), # 0x60-0x63 + OC4(V, V, V, V), # 0x64-0x67 + OC4(Q, Q, B, U), # 0x68-0x6b + OC4(U, U, U, U), # 0x6c-0x6f + OC4(B, B, B, B), # 0x70-0x73 + OC4(B, B, B, B), # 0x74-0x77 + OC4(B, B, B, B), # 0x78-0x7b + OC4(B, B, B, B), # 0x7c-0x7f + OC4(B, B, B, B), # 0x80-0x83 + OC4(B, B, B, B), # 0x84-0x87 + OC4(B, B, B, B), # 0x88-0x8b + OC4(B, B, B, B), # 0x8c-0x8f + OC4(B, B, B, B), # 0x90-0x93 + OC4(B, B, B, B), # 0x94-0x97 + OC4(B, B, B, B), # 0x98-0x9b + OC4(B, B, B, B), # 0x9c-0x9f + OC4(B, B, B, B), # 0xa0-0xa3 + OC4(B, B, B, B), # 0xa4-0xa7 + OC4(B, B, B, B), # 0xa8-0xab + OC4(B, B, B, B), # 0xac-0xaf + OC4(B, B, B, B), # 0xb0-0xb3 + OC4(B, B, B, B), # 0xb4-0xb7 + OC4(B, B, B, B), # 0xb8-0xbb + OC4(B, B, B, B), # 0xbc-0xbf + OC4(B, B, B, B), # 0xc0-0xc3 + OC4(B, B, B, B), # 0xc4-0xc7 + OC4(B, B, B, B), # 0xc8-0xcb + OC4(B, B, B, B), # 0xcc-0xcf + OC4(B, B, B, B), # 0xd0-0xd3 + OC4(U, U, U, B), # 0xd4-0xd7 + OC4(B, B, B, B), # 0xd8-0xdb + OC4(B, B, B, B), # 0xdc-0xdf + OC4(B, B, B, B), # 0xe0-0xe3 + OC4(B, B, B, B), # 0xe4-0xe7 + OC4(B, B, B, B), # 0xe8-0xeb + OC4(B, B, B, B), # 0xec-0xef + OC4(B, B, B, B), # 0xf0-0xf3 + OC4(B, B, B, B), # 0xf4-0xf7 + OC4(U, U, U, U), # 0xf8-0xfb + OC4(U, U, U, U), # 0xfc-0xff + ) + ) - OC4(B, B, B, B), # 0x70-0x73 - OC4(B, B, B, B), # 0x74-0x77 - OC4(B, B, B, B), # 0x78-0x7b - OC4(B, B, B, B), # 0x7c-0x7f - OC4(B, B, B, B), # 0x80-0x83 - OC4(B, B, B, B), # 0x84-0x87 - OC4(B, B, B, B), # 0x88-0x8b - OC4(B, B, B, B), # 0x8c-0x8f - OC4(B, B, B, B), # 0x90-0x93 - OC4(B, B, B, B), # 0x94-0x97 - OC4(B, B, B, B), # 0x98-0x9b - OC4(B, B, B, B), # 0x9c-0x9f - OC4(B, B, B, B), # 0xa0-0xa3 - OC4(B, B, B, B), # 0xa4-0xa7 - OC4(B, B, B, B), # 0xa8-0xab - OC4(B, B, B, B), # 0xac-0xaf - - OC4(B, B, B, B), # 0xb0-0xb3 - OC4(B, B, B, B), # 0xb4-0xb7 - OC4(B, B, B, B), # 0xb8-0xbb - OC4(B, B, B, B), # 0xbc-0xbf - - OC4(B, B, B, B), # 0xc0-0xc3 - OC4(B, B, B, B), # 0xc4-0xc7 - OC4(B, B, B, B), # 0xc8-0xcb - OC4(B, B, B, B), # 0xcc-0xcf - - OC4(B, B, B, B), # 0xd0-0xd3 - OC4(U, U, U, B), # 0xd4-0xd7 - OC4(B, B, B, B), # 0xd8-0xdb - OC4(B, B, B, B), # 0xdc-0xdf - - OC4(B, B, B, B), # 0xe0-0xe3 - OC4(B, B, B, B), # 0xe4-0xe7 - OC4(B, B, B, B), # 0xe8-0xeb - OC4(B, B, B, B), # 0xec-0xef - - OC4(B, B, B, B), # 0xf0-0xf3 - OC4(B, B, B, B), # 0xf4-0xf7 - OC4(U, U, U, U), # 0xf8-0xfb - OC4(U, U, U, U), # 0xfc-0xff - )) # this function mirrors that in py/bc.c def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): @@ -165,7 +169,8 @@ def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): opcode == MP_BC_RAISE_VARARGS or opcode == MP_BC_MAKE_CLOSURE or opcode == MP_BC_MAKE_CLOSURE_DEFARGS - or config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE and ( + or config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE + and ( opcode == MP_BC_LOAD_NAME or opcode == MP_BC_LOAD_GLOBAL or opcode == MP_BC_LOAD_ATTR @@ -182,32 +187,51 @@ def mp_opcode_format(bytecode, ip, opcode_format=make_opcode_format()): ip += extra_byte return f, ip - ip_start + def decode_uint(bytecode, ip): unum = 0 while True: val = bytecode[ip] ip += 1 - unum = (unum << 7) | (val & 0x7f) + unum = (unum << 7) | (val & 0x7F) if not (val & 0x80): break return ip, unum + def extract_prelude(bytecode): ip = 0 ip, n_state = decode_uint(bytecode, ip) ip, n_exc_stack = decode_uint(bytecode, ip) - scope_flags = bytecode[ip]; ip += 1 - n_pos_args = bytecode[ip]; ip += 1 - n_kwonly_args = bytecode[ip]; ip += 1 - n_def_pos_args = bytecode[ip]; ip += 1 + scope_flags = bytecode[ip] + ip += 1 + n_pos_args = bytecode[ip] + ip += 1 + n_kwonly_args = bytecode[ip] + ip += 1 + n_def_pos_args = bytecode[ip] + ip += 1 ip2, code_info_size = decode_uint(bytecode, ip) ip += code_info_size - while bytecode[ip] != 0xff: + while bytecode[ip] != 0xFF: ip += 1 ip += 1 # ip now points to first opcode # ip2 points to simple_name qstr - return ip, ip2, (n_state, n_exc_stack, scope_flags, n_pos_args, n_kwonly_args, n_def_pos_args, code_info_size) + return ( + ip, + ip2, + ( + n_state, + n_exc_stack, + scope_flags, + n_pos_args, + n_kwonly_args, + n_def_pos_args, + code_info_size, + ), + ) + class RawCode: # a set of all escaped names, to make sure they are unique @@ -232,7 +256,7 @@ class RawCode: def dump(self): # dump children first for rc in self.raw_codes: - rc.freeze('') + rc.freeze("") # TODO def freeze(self, parent_name): @@ -245,35 +269,44 @@ class RawCode: i += 1 RawCode.escaped_names.add(self.escaped_name) - sizes = {"bytecode": 0, "strings": 0, "raw_code_overhead": 0, "const_table_overhead": 0, "string_overhead": 0, "number_overhead": 0} + sizes = { + "bytecode": 0, + "strings": 0, + "raw_code_overhead": 0, + "const_table_overhead": 0, + "string_overhead": 0, + "number_overhead": 0, + } # emit children first for rc in self.raw_codes: - subsize = rc.freeze(self.escaped_name + '_') + subsize = rc.freeze(self.escaped_name + "_") for k in sizes: sizes[k] += subsize[k] - # generate bytecode data print() - print('// frozen bytecode for file %s, scope %s%s' % (self.source_file.str, parent_name, self.simple_name.str)) + print( + "// frozen bytecode for file %s, scope %s%s" + % (self.source_file.str, parent_name, self.simple_name.str) + ) print("// bytecode size", len(self.bytecode)) - print('STATIC ', end='') + print("STATIC ", end="") if not config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE: - print('const ', end='') - print('byte bytecode_data_%s[%u] = {' % (self.escaped_name, len(self.bytecode))) + print("const ", end="") + print("byte bytecode_data_%s[%u] = {" % (self.escaped_name, len(self.bytecode))) sizes["bytecode"] += len(self.bytecode) - print(' ', end='') + print(" ", end="") for i in range(self.ip2): - print(' 0x%02x,' % self.bytecode[i], end='') + print(" 0x%02x," % self.bytecode[i], end="") print() print(" // simple name") - print(' ', self.simple_name.qstr_id, '& 0xff,', self.simple_name.qstr_id, '>> 8,') + print(" ", self.simple_name.qstr_id, "& 0xff,", self.simple_name.qstr_id, ">> 8,") print(" // source file") - print(' ', self.source_file.qstr_id, '& 0xff,', self.source_file.qstr_id, '>> 8,') + print(" ", self.source_file.qstr_id, "& 0xff,", self.source_file.qstr_id, ">> 8,") print(" // code info") - print(' ', end='') + print(" ", end="") for i in range(self.ip2 + 4, self.ip): - print(' 0x%02x,' % self.bytecode[i], end='') + print(" 0x%02x," % self.bytecode[i], end="") print() print(" // bytecode") ip = self.ip @@ -283,39 +316,51 @@ class RawCode: if opcode in opcode_names: opcode = opcode_names[opcode] else: - opcode = '0x%02x' % opcode + opcode = "0x%02x" % opcode if f == 1: qst = self._unpack_qstr(ip + 1).qstr_id - print(' {}, {} & 0xff, {} >> 8,'.format(opcode, qst, qst)) + print(" {}, {} & 0xff, {} >> 8,".format(opcode, qst, qst)) else: - print(' {},{}'.format(opcode, ''.join(' 0x%02x,' % self.bytecode[ip + i] for i in range(1, sz)))) + print( + " {},{}".format( + opcode, "".join(" 0x%02x," % self.bytecode[ip + i] for i in range(1, sz)) + ) + ) ip += sz - print('};') + print("};") # generate constant objects for i, obj in enumerate(self.objs): - obj_name = 'const_obj_%s_%u' % (self.escaped_name, i) + obj_name = "const_obj_%s_%u" % (self.escaped_name, i) if obj is Ellipsis: - print('#define %s mp_const_ellipsis_obj' % obj_name) + print("#define %s mp_const_ellipsis_obj" % obj_name) elif is_str_type(obj) or is_bytes_type(obj): if is_str_type(obj): - obj = bytes_cons(obj, 'utf8') - obj_type = 'mp_type_str' + obj = bytes_cons(obj, "utf8") + obj_type = "mp_type_str" else: - obj_type = 'mp_type_bytes' - print('STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"}; // %s' - % (obj_name, obj_type, qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH), - len(obj), ''.join(('\\x%02x' % b) for b in obj), obj)) + obj_type = "mp_type_bytes" + print( + 'STATIC const mp_obj_str_t %s = {{&%s}, %u, %u, (const byte*)"%s"}; // %s' + % ( + obj_name, + obj_type, + qstrutil.compute_hash(obj, config.MICROPY_QSTR_BYTES_IN_HASH), + len(obj), + "".join(("\\x%02x" % b) for b in obj), + obj, + ) + ) sizes["strings"] += len(obj) sizes["string_overhead"] += 16 elif is_int_type(obj): if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_NONE: # TODO check if we can actually fit this long-int into a small-int - raise FreezeError(self, 'target does not support long int') + raise FreezeError(self, "target does not support long int") elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_LONGLONG: # TODO - raise FreezeError(self, 'freezing int to long-long is not implemented') + raise FreezeError(self, "freezing int to long-long is not implemented") elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ: neg = 0 if obj < 0: @@ -328,117 +373,137 @@ class RawCode: digs.append(z & ((1 << bits_per_dig) - 1)) z >>= bits_per_dig ndigs = len(digs) - digs = ','.join(('%#x' % d) for d in digs) - print('STATIC const mp_obj_int_t %s = {{&mp_type_int}, ' - '{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t[]){%s}}};' - % (obj_name, neg, ndigs, ndigs, bits_per_dig, digs)) + digs = ",".join(("%#x" % d) for d in digs) + print( + "STATIC const mp_obj_int_t %s = {{&mp_type_int}, " + "{.neg=%u, .fixed_dig=1, .alloc=%u, .len=%u, .dig=(uint%u_t[]){%s}}};" + % (obj_name, neg, ndigs, ndigs, bits_per_dig, digs) + ) sizes["number_overhead"] += 16 elif type(obj) is float: - print('#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B') - print('STATIC const mp_obj_float_t %s = {{&mp_type_float}, %.16g};' - % (obj_name, obj)) - print('#endif') + print( + "#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B" + ) + print( + "STATIC const mp_obj_float_t %s = {{&mp_type_float}, %.16g};" % (obj_name, obj) + ) + print("#endif") sizes["number_overhead"] += 8 elif type(obj) is complex: - print('STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, %.16g, %.16g};' - % (obj_name, obj.real, obj.imag)) + print( + "STATIC const mp_obj_complex_t %s = {{&mp_type_complex}, %.16g, %.16g};" + % (obj_name, obj.real, obj.imag) + ) sizes["number_overhead"] += 12 else: - raise FreezeError(self, 'freezing of object %r is not implemented' % (obj,)) + raise FreezeError(self, "freezing of object %r is not implemented" % (obj,)) # generate constant table, if it has any entries const_table_len = len(self.qstrs) + len(self.objs) + len(self.raw_codes) if const_table_len: - print('STATIC const mp_rom_obj_t const_table_data_%s[%u] = {' - % (self.escaped_name, const_table_len)) + print( + "STATIC const mp_rom_obj_t const_table_data_%s[%u] = {" + % (self.escaped_name, const_table_len) + ) for qst in self.qstrs: sizes["const_table_overhead"] += 4 - print(' MP_ROM_QSTR(%s),' % global_qstrs[qst].qstr_id) + print(" MP_ROM_QSTR(%s)," % global_qstrs[qst].qstr_id) for i in range(len(self.objs)): sizes["const_table_overhead"] += 4 if type(self.objs[i]) is float: - print('#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_A || MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B') - print(' MP_ROM_PTR(&const_obj_%s_%u),' % (self.escaped_name, i)) - print('#elif MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C') - n = struct.unpack('> 8 + def read_bytecode_qstrs(file, bytecode, ip): while ip < len(bytecode): f, sz = mp_opcode_format(bytecode, ip) @@ -446,12 +511,13 @@ def read_bytecode_qstrs(file, bytecode, ip): read_qstr_and_pack(file, bytecode, ip + 1) ip += sz + def read_raw_code(f): bc_len = read_uint(f) bytecode = bytearray(f.read(bc_len)) ip, ip2, prelude = extract_prelude(bytecode) - read_qstr_and_pack(f, bytecode, ip2) # simple_name - read_qstr_and_pack(f, bytecode, ip2 + 2) # source_file + read_qstr_and_pack(f, bytecode, ip2) # simple_name + read_qstr_and_pack(f, bytecode, ip2 + 2) # source_file read_bytecode_qstrs(f, bytecode, ip) n_obj = read_uint(f) n_raw_code = read_uint(f) @@ -460,23 +526,26 @@ def read_raw_code(f): raw_codes = [read_raw_code(f) for _ in range(n_raw_code)] return RawCode(bytecode, qstrs, objs, raw_codes) + def read_mpy(filename): - with open(filename, 'rb') as f: + with open(filename, "rb") as f: header = bytes_cons(f.read(4)) - if header[0] != ord('M'): - raise Exception('not a valid .mpy file') + if header[0] != ord("M"): + raise Exception("not a valid .mpy file") if header[1] != config.MPY_VERSION: - raise Exception('incompatible .mpy version') + raise Exception("incompatible .mpy version") feature_flags = header[2] config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE = (feature_flags & 1) != 0 config.MICROPY_PY_BUILTINS_STR_UNICODE = (feature_flags & 2) != 0 config.mp_small_int_bits = header[3] return read_raw_code(f) + def dump_mpy(raw_codes): for rc in raw_codes: rc.dump() + def freeze_mpy(base_qstrs, raw_codes): # add to qstrs new = {} @@ -494,71 +563,79 @@ def freeze_mpy(base_qstrs, raw_codes): print('#include "py/emitglue.h"') print() - print('#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE != %u' % config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) + print( + "#if MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE != %u" + % config.MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE + ) print('#error "incompatible MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE"') - print('#endif') + print("#endif") print() - print('#if MICROPY_LONGINT_IMPL != %u' % config.MICROPY_LONGINT_IMPL) + print("#if MICROPY_LONGINT_IMPL != %u" % config.MICROPY_LONGINT_IMPL) print('#error "incompatible MICROPY_LONGINT_IMPL"') - print('#endif') + print("#endif") print() if config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ: - print('#if MPZ_DIG_SIZE != %u' % config.MPZ_DIG_SIZE) + print("#if MPZ_DIG_SIZE != %u" % config.MPZ_DIG_SIZE) print('#error "incompatible MPZ_DIG_SIZE"') - print('#endif') + print("#endif") print() - - print('#if MICROPY_PY_BUILTINS_FLOAT') - print('typedef struct _mp_obj_float_t {') - print(' mp_obj_base_t base;') - print(' mp_float_t value;') - print('} mp_obj_float_t;') - print('#endif') + print("#if MICROPY_PY_BUILTINS_FLOAT") + print("typedef struct _mp_obj_float_t {") + print(" mp_obj_base_t base;") + print(" mp_float_t value;") + print("} mp_obj_float_t;") + print("#endif") print() - print('#if MICROPY_PY_BUILTINS_COMPLEX') - print('typedef struct _mp_obj_complex_t {') - print(' mp_obj_base_t base;') - print(' mp_float_t real;') - print(' mp_float_t imag;') - print('} mp_obj_complex_t;') - print('#endif') + print("#if MICROPY_PY_BUILTINS_COMPLEX") + print("typedef struct _mp_obj_complex_t {") + print(" mp_obj_base_t base;") + print(" mp_float_t real;") + print(" mp_float_t imag;") + print("} mp_obj_complex_t;") + print("#endif") print() - print('enum {') + print("enum {") for i in range(len(new)): if i == 0: - print(' MP_QSTR_%s = MP_QSTRnumber_of,' % new[i][1]) + print(" MP_QSTR_%s = MP_QSTRnumber_of," % new[i][1]) else: - print(' MP_QSTR_%s,' % new[i][1]) - print('};') + print(" MP_QSTR_%s," % new[i][1]) + print("};") print() - print('extern const qstr_pool_t mp_qstr_const_pool;'); - print('const qstr_pool_t mp_qstr_frozen_const_pool = {') - print(' (qstr_pool_t*)&mp_qstr_const_pool, // previous pool') - print(' MP_QSTRnumber_of, // previous pool size') - print(' %u, // allocated entries' % len(new)) - print(' %u, // used entries' % len(new)) - print(' {') + print("extern const qstr_pool_t mp_qstr_const_pool;") + print("const qstr_pool_t mp_qstr_frozen_const_pool = {") + print(" (qstr_pool_t*)&mp_qstr_const_pool, // previous pool") + print(" MP_QSTRnumber_of, // previous pool size") + print(" %u, // allocated entries" % len(new)) + print(" %u, // used entries" % len(new)) + print(" {") qstr_size = {"metadata": 0, "data": 0} for _, _, qstr in new: - qstr_size["metadata"] += config.MICROPY_QSTR_BYTES_IN_LEN + config.MICROPY_QSTR_BYTES_IN_HASH + qstr_size["metadata"] += ( + config.MICROPY_QSTR_BYTES_IN_LEN + config.MICROPY_QSTR_BYTES_IN_HASH + ) qstr_size["data"] += len(qstr) - print(' %s,' - % qstrutil.make_bytes(config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr)) - print(' },') - print('};') + print( + " %s," + % qstrutil.make_bytes( + config.MICROPY_QSTR_BYTES_IN_LEN, config.MICROPY_QSTR_BYTES_IN_HASH, qstr + ) + ) + print(" },") + print("};") sizes = {} for rc in raw_codes: - sizes[rc.source_file.str] = rc.freeze(rc.source_file.str.replace('/', '_')[:-3] + '_') + sizes[rc.source_file.str] = rc.freeze(rc.source_file.str.replace("/", "_")[:-3] + "_") print() - print('const char mp_frozen_mpy_names[] = {') + print("const char mp_frozen_mpy_names[] = {") qstr_size["filenames"] = 1 for rc in raw_codes: module_name = rc.source_file.str @@ -566,53 +643,62 @@ def freeze_mpy(base_qstrs, raw_codes): qstr_size["filenames"] += len(module_name) + 1 print('"\\0"};') - print('const mp_raw_code_t *const mp_frozen_mpy_content[] = {') + print("const mp_raw_code_t *const mp_frozen_mpy_content[] = {") for rc in raw_codes: - print(' &raw_code_%s,' % rc.escaped_name) + print(" &raw_code_%s," % rc.escaped_name) size = sizes[rc.source_file.str] - print(' // Total size:', sum(size.values())) + print(" // Total size:", sum(size.values())) for k in size: print(" // {} {}".format(k, size[k])) - print('};') + print("};") print() - print('// Total size:', sum([sum(x.values()) for x in sizes.values()]) + sum(qstr_size.values())) + print( + "// Total size:", sum([sum(x.values()) for x in sizes.values()]) + sum(qstr_size.values()) + ) for k in size: total = sum([x[k] for x in sizes.values()]) print("// {} {}".format(k, total)) for k in qstr_size: print("// qstr {} {}".format(k, qstr_size[k])) + def main(): import argparse - cmd_parser = argparse.ArgumentParser(description='A tool to work with MicroPython .mpy files.') - cmd_parser.add_argument('-d', '--dump', action='store_true', - help='dump contents of files') - cmd_parser.add_argument('-f', '--freeze', action='store_true', - help='freeze files') - cmd_parser.add_argument('-q', '--qstr-header', - help='qstr header file to freeze against') - cmd_parser.add_argument('-mlongint-impl', choices=['none', 'longlong', 'mpz'], default='mpz', - help='long-int implementation used by target (default mpz)') - cmd_parser.add_argument('-mmpz-dig-size', metavar='N', type=int, default=16, - help='mpz digit size used by target (default 16)') - cmd_parser.add_argument('files', nargs='+', - help='input .mpy files') + + cmd_parser = argparse.ArgumentParser(description="A tool to work with MicroPython .mpy files.") + cmd_parser.add_argument("-d", "--dump", action="store_true", help="dump contents of files") + cmd_parser.add_argument("-f", "--freeze", action="store_true", help="freeze files") + cmd_parser.add_argument("-q", "--qstr-header", help="qstr header file to freeze against") + cmd_parser.add_argument( + "-mlongint-impl", + choices=["none", "longlong", "mpz"], + default="mpz", + help="long-int implementation used by target (default mpz)", + ) + cmd_parser.add_argument( + "-mmpz-dig-size", + metavar="N", + type=int, + default=16, + help="mpz digit size used by target (default 16)", + ) + cmd_parser.add_argument("files", nargs="+", help="input .mpy files") args = cmd_parser.parse_args() # set config values relevant to target machine config.MICROPY_LONGINT_IMPL = { - 'none':config.MICROPY_LONGINT_IMPL_NONE, - 'longlong':config.MICROPY_LONGINT_IMPL_LONGLONG, - 'mpz':config.MICROPY_LONGINT_IMPL_MPZ, + "none": config.MICROPY_LONGINT_IMPL_NONE, + "longlong": config.MICROPY_LONGINT_IMPL_LONGLONG, + "mpz": config.MICROPY_LONGINT_IMPL_MPZ, }[args.mlongint_impl] config.MPZ_DIG_SIZE = args.mmpz_dig_size # set config values for qstrs, and get the existing base set of qstrs if args.qstr_header: qcfgs, base_qstrs, _ = qstrutil.parse_input_headers([args.qstr_header]) - config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs['BYTES_IN_LEN']) - config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs['BYTES_IN_HASH']) + config.MICROPY_QSTR_BYTES_IN_LEN = int(qcfgs["BYTES_IN_LEN"]) + config.MICROPY_QSTR_BYTES_IN_HASH = int(qcfgs["BYTES_IN_HASH"]) else: config.MICROPY_QSTR_BYTES_IN_LEN = 1 config.MICROPY_QSTR_BYTES_IN_HASH = 1 @@ -629,5 +715,6 @@ def main(): print(er, file=sys.stderr) sys.exit(1) -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/tools/mpy_cross_all.py b/tools/mpy_cross_all.py index 5d9f8bc0ba..9c217400fb 100755 --- a/tools/mpy_cross_all.py +++ b/tools/mpy_cross_all.py @@ -11,14 +11,13 @@ import os.path argparser = argparse.ArgumentParser(description="Compile all .py files to .mpy recursively") argparser.add_argument("-o", "--out", help="output directory (default: input dir)") argparser.add_argument("--target", help="select MicroPython target config") -argparser.add_argument("-mcache-lookup-bc", action="store_true", help="cache map lookups in the bytecode") +argparser.add_argument( + "-mcache-lookup-bc", action="store_true", help="cache map lookups in the bytecode" +) argparser.add_argument("dir", help="input directory") args = argparser.parse_args() -TARGET_OPTS = { - "unix": "-mcache-lookup-bc", - "baremetal": "", -} +TARGET_OPTS = {"unix": "-mcache-lookup-bc", "baremetal": ""} args.dir = args.dir.rstrip("/") @@ -31,13 +30,17 @@ for path, subdirs, files in os.walk(args.dir): for f in files: if f.endswith(".py"): fpath = path + "/" + f - #print(fpath) + # print(fpath) out_fpath = args.out + "/" + fpath[path_prefix_len:-3] + ".mpy" out_dir = os.path.dirname(out_fpath) if not os.path.isdir(out_dir): os.makedirs(out_dir) - cmd = "mpy-cross -v -v %s -s %s %s -o %s" % (TARGET_OPTS.get(args.target, ""), - fpath[path_prefix_len:], fpath, out_fpath) - #print(cmd) + cmd = "mpy-cross -v -v %s -s %s %s -o %s" % ( + TARGET_OPTS.get(args.target, ""), + fpath[path_prefix_len:], + fpath, + out_fpath, + ) + # print(cmd) res = os.system(cmd) assert res == 0 diff --git a/tools/preprocess_frozen_modules.py b/tools/preprocess_frozen_modules.py index b75a2e7238..294df317bc 100755 --- a/tools/preprocess_frozen_modules.py +++ b/tools/preprocess_frozen_modules.py @@ -13,25 +13,35 @@ import subprocess # Compatible with Python 3.4 due to travis using trusty as default. + def version_string(path=None, *, valid_semver=False): version = None try: - tag = subprocess.check_output('git describe --tags --exact-match', shell=True, cwd=path) + tag = subprocess.check_output("git describe --tags --exact-match", shell=True, cwd=path) version = tag.strip().decode("utf-8", "strict") except subprocess.CalledProcessError: describe = subprocess.check_output("git describe --tags", shell=True, cwd=path) - tag, additional_commits, commitish = describe.strip().decode("utf-8", "strict").rsplit("-", maxsplit=2) + tag, additional_commits, commitish = ( + describe.strip().decode("utf-8", "strict").rsplit("-", maxsplit=2) + ) commitish = commitish[1:] if valid_semver: version_info = semver.parse_version_info(tag) if not version_info.prerelease: - version = semver.bump_patch(tag) + "-alpha.0.plus." + additional_commits + "+" + commitish + version = ( + semver.bump_patch(tag) + + "-alpha.0.plus." + + additional_commits + + "+" + + commitish + ) else: version = tag + ".plus." + additional_commits + "+" + commitish else: version = commitish return version + # Visit all the .py files in topdir. Replace any __version__ = "0.0.0-auto.0" type of info # with actual version info derived from git. def copy_and_process(in_dir, out_dir): @@ -39,14 +49,14 @@ def copy_and_process(in_dir, out_dir): # Skip library examples directory and subfolders. relative_path_parts = Path(root).relative_to(in_dir).parts - if relative_path_parts and relative_path_parts[0] in ['examples', 'docs', 'tests']: + if relative_path_parts and relative_path_parts[0] in ["examples", "docs", "tests"]: del subdirs[:] continue for file in files: # Skip top-level setup.py (module install info) and conf.py (sphinx config), # which are not part of the library - if (root == in_dir) and file in ('conf.py', 'setup.py'): + if (root == in_dir) and file in ("conf.py", "setup.py"): continue input_file_path = Path(root, file) @@ -62,15 +72,22 @@ def copy_and_process(in_dir, out_dir): line = line.replace("0.0.0-auto.0", module_version) output.write(line) -if __name__ == '__main__': - argparser = argparse.ArgumentParser(description="""\ + +if __name__ == "__main__": + argparser = argparse.ArgumentParser( + description="""\ Copy and pre-process .py files into output directory, before freezing. 1. Remove top-level repo directory. 2. Update __version__ info. 3. Remove examples. - 4. Remove non-library setup.py and conf.py""") - argparser.add_argument("in_dirs", metavar="input-dir", nargs="+", - help="top-level code dirs (may be git repo dirs)") + 4. Remove non-library setup.py and conf.py""" + ) + argparser.add_argument( + "in_dirs", + metavar="input-dir", + nargs="+", + help="top-level code dirs (may be git repo dirs)", + ) argparser.add_argument("-o", "--out_dir", help="output directory") args = argparser.parse_args() diff --git a/tools/print_status.py b/tools/print_status.py index 9a8b311dc2..50535502ea 100755 --- a/tools/print_status.py +++ b/tools/print_status.py @@ -5,15 +5,19 @@ # SPDX-License-Identifier: MIT import sys + if len(sys.argv) != 2: - print("""\ + print( + """\ Usage: print_status.py STATUS_FILENAME STATUS_FILENAME contains one line with an integer status.""" ) sys.exit(1) -with open(sys.argv[1], 'r') as status_in: +with open(sys.argv[1], "r") as status_in: status = int(status_in.readline()) -print('{} with status {}'.format( - "\033[32msucceeded\033[0m" if status == 0 else "\033[31mfailed\033[0m", - status)) +print( + "{} with status {}".format( + "\033[32msucceeded\033[0m" if status == 0 else "\033[31mfailed\033[0m", status + ) +) diff --git a/tools/pyboard.py b/tools/pyboard.py index ddf6bb6c40..b8f1c381e7 100755 --- a/tools/pyboard.py +++ b/tools/pyboard.py @@ -57,34 +57,41 @@ except AttributeError: # Python2 doesn't have buffer attr stdout = sys.stdout + def stdout_write_bytes(b): b = b.replace(b"\x04", b"") stdout.write(b) stdout.flush() + class PyboardError(BaseException): pass + class TelnetToSerial: def __init__(self, ip, user, password, read_timeout=None): import telnetlib + self.tn = telnetlib.Telnet(ip, timeout=15) self.read_timeout = read_timeout - if b'Login as:' in self.tn.read_until(b'Login as:', timeout=read_timeout): - self.tn.write(bytes(user, 'ascii') + b"\r\n") + if b"Login as:" in self.tn.read_until(b"Login as:", timeout=read_timeout): + self.tn.write(bytes(user, "ascii") + b"\r\n") - if b'Password:' in self.tn.read_until(b'Password:', timeout=read_timeout): + if b"Password:" in self.tn.read_until(b"Password:", timeout=read_timeout): # needed because of internal implementation details of the telnet server time.sleep(0.2) - self.tn.write(bytes(password, 'ascii') + b"\r\n") + self.tn.write(bytes(password, "ascii") + b"\r\n") - if b'for more information.' in self.tn.read_until(b'Type "help()" for more information.', timeout=read_timeout): + if b"for more information." in self.tn.read_until( + b'Type "help()" for more information.', timeout=read_timeout + ): # login successful from collections import deque + self.fifo = deque() return - raise PyboardError('Failed to establish a telnet connection with the board') + raise PyboardError("Failed to establish a telnet connection with the board") def __del__(self): self.close() @@ -109,7 +116,7 @@ class TelnetToSerial: break timeout_count += 1 - data = b'' + data = b"" while len(data) < size and len(self.fifo) > 0: data += bytes([self.fifo.popleft()]) return data @@ -133,24 +140,33 @@ class ProcessToSerial: def __init__(self, cmd): import subprocess - self.subp = subprocess.Popen(cmd.split(), bufsize=0, shell=True, preexec_fn=os.setsid, - stdin=subprocess.PIPE, stdout=subprocess.PIPE) + + self.subp = subprocess.Popen( + cmd.split(), + bufsize=0, + shell=True, + preexec_fn=os.setsid, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + ) # Initially was implemented with selectors, but that adds Python3 # dependency. However, there can be race conditions communicating # with a particular child process (like QEMU), and selectors may # still work better in that case, so left inplace for now. # - #import selectors - #self.sel = selectors.DefaultSelector() - #self.sel.register(self.subp.stdout, selectors.EVENT_READ) + # import selectors + # self.sel = selectors.DefaultSelector() + # self.sel.register(self.subp.stdout, selectors.EVENT_READ) import select + self.poll = select.poll() self.poll.register(self.subp.stdout.fileno()) def close(self): import signal + os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM) def read(self, size=1): @@ -164,7 +180,7 @@ class ProcessToSerial: return len(data) def inWaiting(self): - #res = self.sel.select(0) + # res = self.sel.select(0) res = self.poll.poll(0) if res: return 1 @@ -180,8 +196,16 @@ class ProcessPtyToTerminal: import subprocess import re import serial - self.subp = subprocess.Popen(cmd.split(), bufsize=0, shell=False, preexec_fn=os.setsid, - stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + self.subp = subprocess.Popen( + cmd.split(), + bufsize=0, + shell=False, + preexec_fn=os.setsid, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) pty_line = self.subp.stderr.readline().decode("utf-8") m = re.search(r"/dev/pts/[0-9]+", pty_line) if not m: @@ -195,6 +219,7 @@ class ProcessPtyToTerminal: def close(self): import signal + os.killpg(os.getpgid(self.subp.pid), signal.SIGTERM) def read(self, size=1): @@ -208,36 +233,37 @@ class ProcessPtyToTerminal: class Pyboard: - def __init__(self, device, baudrate=115200, user='micro', password='python', wait=0): + def __init__(self, device, baudrate=115200, user="micro", password="python", wait=0): if device.startswith("exec:"): - self.serial = ProcessToSerial(device[len("exec:"):]) + self.serial = ProcessToSerial(device[len("exec:") :]) elif device.startswith("execpty:"): - self.serial = ProcessPtyToTerminal(device[len("qemupty:"):]) - elif device and device[0].isdigit() and device[-1].isdigit() and device.count('.') == 3: + self.serial = ProcessPtyToTerminal(device[len("qemupty:") :]) + elif device and device[0].isdigit() and device[-1].isdigit() and device.count(".") == 3: # device looks like an IP address self.serial = TelnetToSerial(device, user, password, read_timeout=10) else: import serial + delayed = False for attempt in range(wait + 1): try: self.serial = serial.Serial(device, baudrate=baudrate, interCharTimeout=1) break - except (OSError, IOError): # Py2 and Py3 have different errors + except (OSError, IOError): # Py2 and Py3 have different errors if wait == 0: continue if attempt == 0: - sys.stdout.write('Waiting {} seconds for pyboard '.format(wait)) + sys.stdout.write("Waiting {} seconds for pyboard ".format(wait)) delayed = True time.sleep(1) - sys.stdout.write('.') + sys.stdout.write(".") sys.stdout.flush() else: if delayed: - print('') - raise PyboardError('failed to access ' + device) + print("") + raise PyboardError("failed to access " + device) if delayed: - print('') + print("") def close(self): self.serial.close() @@ -264,7 +290,7 @@ class Pyboard: return data def enter_raw_repl(self): - self.serial.write(b'\r\x03\x03') # ctrl-C twice: interrupt any running program + self.serial.write(b"\r\x03\x03") # ctrl-C twice: interrupt any running program # flush input (without relying on serial.flushInput()) n = self.serial.inWaiting() @@ -272,38 +298,38 @@ class Pyboard: self.serial.read(n) n = self.serial.inWaiting() - self.serial.write(b'\r\x01') # ctrl-A: enter raw REPL - data = self.read_until(1, b'raw REPL; CTRL-B to exit\r\n>') - if not data.endswith(b'raw REPL; CTRL-B to exit\r\n>'): + self.serial.write(b"\r\x01") # ctrl-A: enter raw REPL + data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n>") + if not data.endswith(b"raw REPL; CTRL-B to exit\r\n>"): print(data) - raise PyboardError('could not enter raw repl') + raise PyboardError("could not enter raw repl") - self.serial.write(b'\x04') # ctrl-D: soft reset - data = self.read_until(1, b'soft reboot\r\n') - if not data.endswith(b'soft reboot\r\n'): + self.serial.write(b"\x04") # ctrl-D: soft reset + data = self.read_until(1, b"soft reboot\r\n") + if not data.endswith(b"soft reboot\r\n"): print(data) - raise PyboardError('could not enter raw repl') + raise PyboardError("could not enter raw repl") # By splitting this into 2 reads, it allows boot.py to print stuff, # which will show up after the soft reboot and before the raw REPL. - data = self.read_until(1, b'raw REPL; CTRL-B to exit\r\n') - if not data.endswith(b'raw REPL; CTRL-B to exit\r\n'): + data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n") + if not data.endswith(b"raw REPL; CTRL-B to exit\r\n"): print(data) - raise PyboardError('could not enter raw repl') + raise PyboardError("could not enter raw repl") def exit_raw_repl(self): - self.serial.write(b'\r\x02') # ctrl-B: enter friendly REPL + self.serial.write(b"\r\x02") # ctrl-B: enter friendly REPL def follow(self, timeout, data_consumer=None): # wait for normal output - data = self.read_until(1, b'\x04', timeout=timeout, data_consumer=data_consumer) - if not data.endswith(b'\x04'): - raise PyboardError('timeout waiting for first EOF reception') + data = self.read_until(1, b"\x04", timeout=timeout, data_consumer=data_consumer) + if not data.endswith(b"\x04"): + raise PyboardError("timeout waiting for first EOF reception") data = data[:-1] # wait for error output - data_err = self.read_until(1, b'\x04', timeout=timeout) - if not data_err.endswith(b'\x04'): - raise PyboardError('timeout waiting for second EOF reception') + data_err = self.read_until(1, b"\x04", timeout=timeout) + if not data_err.endswith(b"\x04"): + raise PyboardError("timeout waiting for second EOF reception") data_err = data_err[:-1] # return normal and error output @@ -313,53 +339,55 @@ class Pyboard: if isinstance(command, bytes): command_bytes = command else: - command_bytes = bytes(command, encoding='utf8') + command_bytes = bytes(command, encoding="utf8") # check we have a prompt - data = self.read_until(1, b'>') - if not data.endswith(b'>'): - raise PyboardError('could not enter raw repl') + data = self.read_until(1, b">") + if not data.endswith(b">"): + raise PyboardError("could not enter raw repl") # write command for i in range(0, len(command_bytes), 256): - self.serial.write(command_bytes[i:min(i + 256, len(command_bytes))]) + self.serial.write(command_bytes[i : min(i + 256, len(command_bytes))]) time.sleep(0.01) - self.serial.write(b'\x04') + self.serial.write(b"\x04") # check if we could exec command data = self.serial.read(2) - if data != b'OK': - raise PyboardError('could not exec command (response: %r)' % data) + if data != b"OK": + raise PyboardError("could not exec command (response: %r)" % data) def exec_raw(self, command, timeout=10, data_consumer=None): - self.exec_raw_no_follow(command); + self.exec_raw_no_follow(command) return self.follow(timeout, data_consumer) def eval(self, expression): - ret = self.exec_('print({})'.format(expression)) + ret = self.exec_("print({})".format(expression)) ret = ret.strip() return ret def exec_(self, command): ret, ret_err = self.exec_raw(command) if ret_err: - raise PyboardError('exception', ret, ret_err) + raise PyboardError("exception", ret, ret_err) return ret def execfile(self, filename): - with open(filename, 'rb') as f: + with open(filename, "rb") as f: pyfile = f.read() return self.exec_(pyfile) def get_time(self): - t = str(self.eval('pyb.RTC().datetime()'), encoding='utf8')[1:-1].split(', ') + t = str(self.eval("pyb.RTC().datetime()"), encoding="utf8")[1:-1].split(", ") return int(t[4]) * 3600 + int(t[5]) * 60 + int(t[6]) + # in Python2 exec is a keyword so one must use "exec_" # but for Python3 we want to provide the nicer version "exec" setattr(Pyboard, "exec", Pyboard.exec_) -def execfile(filename, device='/dev/ttyACM0', baudrate=115200, user='micro', password='python'): + +def execfile(filename, device="/dev/ttyACM0", baudrate=115200, user="micro", password="python"): pyb = Pyboard(device, baudrate, user, password) pyb.enter_raw_repl() output = pyb.execfile(filename) @@ -367,17 +395,35 @@ def execfile(filename, device='/dev/ttyACM0', baudrate=115200, user='micro', pas pyb.exit_raw_repl() pyb.close() + def main(): import argparse - cmd_parser = argparse.ArgumentParser(description='Run scripts on the pyboard.') - cmd_parser.add_argument('--device', default='/dev/ttyACM0', help='the serial device or the IP address of the pyboard') - cmd_parser.add_argument('-b', '--baudrate', default=115200, help='the baud rate of the serial device') - cmd_parser.add_argument('-u', '--user', default='micro', help='the telnet login username') - cmd_parser.add_argument('-p', '--password', default='python', help='the telnet login password') - cmd_parser.add_argument('-c', '--command', help='program passed in as string') - cmd_parser.add_argument('-w', '--wait', default=0, type=int, help='seconds to wait for USB connected board to become available') - cmd_parser.add_argument('--follow', action='store_true', help='follow the output after running the scripts [default if no scripts given]') - cmd_parser.add_argument('files', nargs='*', help='input files') + + cmd_parser = argparse.ArgumentParser(description="Run scripts on the pyboard.") + cmd_parser.add_argument( + "--device", + default="/dev/ttyACM0", + help="the serial device or the IP address of the pyboard", + ) + cmd_parser.add_argument( + "-b", "--baudrate", default=115200, help="the baud rate of the serial device" + ) + cmd_parser.add_argument("-u", "--user", default="micro", help="the telnet login username") + cmd_parser.add_argument("-p", "--password", default="python", help="the telnet login password") + cmd_parser.add_argument("-c", "--command", help="program passed in as string") + cmd_parser.add_argument( + "-w", + "--wait", + default=0, + type=int, + help="seconds to wait for USB connected board to become available", + ) + cmd_parser.add_argument( + "--follow", + action="store_true", + help="follow the output after running the scripts [default if no scripts given]", + ) + cmd_parser.add_argument("files", nargs="*", help="input files") args = cmd_parser.parse_args() # open the connection to the pyboard @@ -415,11 +461,11 @@ def main(): # run the command, if given if args.command is not None: - execbuffer(args.command.encode('utf-8')) + execbuffer(args.command.encode("utf-8")) # run any files for filename in args.files: - with open(filename, 'rb') as f: + with open(filename, "rb") as f: pyfile = f.read() execbuffer(pyfile) @@ -443,5 +489,6 @@ def main(): # close the connection to the pyboard pyb.close() + if __name__ == "__main__": main() diff --git a/tools/pydfu.py b/tools/pydfu.py index a6210c603a..5ee942c177 100755 --- a/tools/pydfu.py +++ b/tools/pydfu.py @@ -24,34 +24,34 @@ import zlib # VID/PID __VID = 0x0483 -__PID = 0xdf11 +__PID = 0xDF11 # USB request __TIMEOUT __TIMEOUT = 4000 # DFU commands -__DFU_DETACH = 0 -__DFU_DNLOAD = 1 -__DFU_UPLOAD = 2 +__DFU_DETACH = 0 +__DFU_DNLOAD = 1 +__DFU_UPLOAD = 2 __DFU_GETSTATUS = 3 __DFU_CLRSTATUS = 4 -__DFU_GETSTATE = 5 -__DFU_ABORT = 6 +__DFU_GETSTATE = 5 +__DFU_ABORT = 6 # DFU status -__DFU_STATE_APP_IDLE = 0x00 -__DFU_STATE_APP_DETACH = 0x01 -__DFU_STATE_DFU_IDLE = 0x02 -__DFU_STATE_DFU_DOWNLOAD_SYNC = 0x03 -__DFU_STATE_DFU_DOWNLOAD_BUSY = 0x04 -__DFU_STATE_DFU_DOWNLOAD_IDLE = 0x05 -__DFU_STATE_DFU_MANIFEST_SYNC = 0x06 -__DFU_STATE_DFU_MANIFEST = 0x07 -__DFU_STATE_DFU_MANIFEST_WAIT_RESET = 0x08 -__DFU_STATE_DFU_UPLOAD_IDLE = 0x09 -__DFU_STATE_DFU_ERROR = 0x0a +__DFU_STATE_APP_IDLE = 0x00 +__DFU_STATE_APP_DETACH = 0x01 +__DFU_STATE_DFU_IDLE = 0x02 +__DFU_STATE_DFU_DOWNLOAD_SYNC = 0x03 +__DFU_STATE_DFU_DOWNLOAD_BUSY = 0x04 +__DFU_STATE_DFU_DOWNLOAD_IDLE = 0x05 +__DFU_STATE_DFU_MANIFEST_SYNC = 0x06 +__DFU_STATE_DFU_MANIFEST = 0x07 +__DFU_STATE_DFU_MANIFEST_WAIT_RESET = 0x08 +__DFU_STATE_DFU_UPLOAD_IDLE = 0x09 +__DFU_STATE_DFU_ERROR = 0x0A -_DFU_DESCRIPTOR_TYPE = 0x21 +_DFU_DESCRIPTOR_TYPE = 0x21 # USB device handle @@ -63,10 +63,13 @@ __verbose = None __DFU_INTERFACE = 0 import inspect -if 'length' in inspect.getargspec(usb.util.get_string).args: + +if "length" in inspect.getargspec(usb.util.get_string).args: # PyUSB 1.0.0.b1 has the length argument def get_string(dev, index): return usb.util.get_string(dev, 255, index) + + else: # PyUSB 1.0.0.b2 dropped the length argument def get_string(dev, index): @@ -78,7 +81,7 @@ def init(): global __dev devices = get_dfu_devices(idVendor=__VID, idProduct=__PID) if not devices: - raise ValueError('No DFU device found') + raise ValueError("No DFU device found") if len(devices) > 1: raise ValueError("Multiple DFU devices found") __dev = devices[0] @@ -93,14 +96,12 @@ def init(): def clr_status(): """Clears any error status (perhaps left over from a previous session).""" - __dev.ctrl_transfer(0x21, __DFU_CLRSTATUS, 0, __DFU_INTERFACE, - None, __TIMEOUT) + __dev.ctrl_transfer(0x21, __DFU_CLRSTATUS, 0, __DFU_INTERFACE, None, __TIMEOUT) def get_status(): """Get the status of the last operation.""" - stat = __dev.ctrl_transfer(0xA1, __DFU_GETSTATUS, 0, __DFU_INTERFACE, - 6, 20000) + stat = __dev.ctrl_transfer(0xA1, __DFU_GETSTATUS, 0, __DFU_INTERFACE, 6, 20000) # print (__DFU_STAT[stat[4]], stat) return stat[4] @@ -108,8 +109,7 @@ def get_status(): def mass_erase(): """Performs a MASS erase (i.e. erases the entire device.""" # Send DNLOAD with first byte=0x41 - __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, - "\x41", __TIMEOUT) + __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, "\x41", __TIMEOUT) # Execute last command if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY: @@ -166,22 +166,23 @@ def write_memory(addr, buf, progress=None, progress_addr=0, progress_size=0): while xfer_bytes < xfer_total: if __verbose and xfer_count % 512 == 0: - print ("Addr 0x%x %dKBs/%dKBs..." % (xfer_base + xfer_bytes, - xfer_bytes // 1024, - xfer_total // 1024)) + print( + "Addr 0x%x %dKBs/%dKBs..." + % (xfer_base + xfer_bytes, xfer_bytes // 1024, xfer_total // 1024) + ) if progress and xfer_count % 2 == 0: - progress(progress_addr, xfer_base + xfer_bytes - progress_addr, - progress_size) + progress(progress_addr, xfer_base + xfer_bytes - progress_addr, progress_size) # Set mem write address - set_address(xfer_base+xfer_bytes) + set_address(xfer_base + xfer_bytes) # Send DNLOAD with fw data # the "2048" is the DFU transfer size supported by the ST DFU bootloader # TODO: this number should be extracted from the USB config descriptor - chunk = min(2048, xfer_total-xfer_bytes) - __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, - buf[xfer_bytes:xfer_bytes + chunk], __TIMEOUT) + chunk = min(2048, xfer_total - xfer_bytes) + __dev.ctrl_transfer( + 0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf[xfer_bytes : xfer_bytes + chunk], __TIMEOUT + ) # Execute last command if get_status() != __DFU_STATE_DFU_DOWNLOAD_BUSY: @@ -203,7 +204,7 @@ def write_page(buf, xfer_offset): xfer_base = 0x08000000 # Set mem write address - set_address(xfer_base+xfer_offset) + set_address(xfer_base + xfer_offset) # Send DNLOAD with fw data __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 2, __DFU_INTERFACE, buf, __TIMEOUT) @@ -217,7 +218,7 @@ def write_page(buf, xfer_offset): raise Exception("DFU: write memory failed") if __verbose: - print ("Write: 0x%x " % (xfer_base + xfer_offset)) + print("Write: 0x%x " % (xfer_base + xfer_offset)) def exit_dfu(): @@ -227,8 +228,7 @@ def exit_dfu(): set_address(0x08000000) # Send DNLOAD with 0 length to exit DFU - __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, - None, __TIMEOUT) + __dev.ctrl_transfer(0x21, __DFU_DNLOAD, 0, __DFU_INTERFACE, None, __TIMEOUT) try: # Execute last command @@ -256,7 +256,7 @@ def consume(fmt, data, names): def cstring(string): """Extracts a null-terminated string from a byte array.""" - return string.decode('utf-8').split('\0', 1)[0] + return string.decode("utf-8").split("\0", 1)[0] def compute_crc(data): @@ -276,7 +276,7 @@ def read_dfu_file(filename): """ print("File: {}".format(filename)) - with open(filename, 'rb') as fin: + with open(filename, "rb") as fin: data = fin.read() crc = compute_crc(data[:-4]) elements = [] @@ -289,11 +289,12 @@ def read_dfu_file(filename): # B uint8_t version 1 # I uint32_t size Size of the DFU file (not including suffix) # B uint8_t targets Number of targets - dfu_prefix, data = consume('<5sBIB', data, - 'signature version size targets') - print (" %(signature)s v%(version)d, image size: %(size)d, " - "targets: %(targets)d" % dfu_prefix) - for target_idx in range(dfu_prefix['targets']): + dfu_prefix, data = consume("<5sBIB", data, "signature version size targets") + print( + " %(signature)s v%(version)d, image size: %(size)d, " + "targets: %(targets)d" % dfu_prefix + ) + for target_idx in range(dfu_prefix["targets"]): # Decode the Image Prefix # # <6sBI255s2I @@ -304,33 +305,33 @@ def read_dfu_file(filename): # 255s char[255] name name of the target # I uint32_t size size of image (not incl prefix) # I uint32_t elements Number of elements in the image - img_prefix, data = consume('<6sBI255s2I', data, - 'signature altsetting named name ' - 'size elements') - img_prefix['num'] = target_idx - if img_prefix['named']: - img_prefix['name'] = cstring(img_prefix['name']) + img_prefix, data = consume( + "<6sBI255s2I", data, "signature altsetting named name " "size elements" + ) + img_prefix["num"] = target_idx + if img_prefix["named"]: + img_prefix["name"] = cstring(img_prefix["name"]) else: - img_prefix['name'] = '' - print(' %(signature)s %(num)d, alt setting: %(altsetting)s, ' - 'name: "%(name)s", size: %(size)d, elements: %(elements)d' - % img_prefix) + img_prefix["name"] = "" + print( + " %(signature)s %(num)d, alt setting: %(altsetting)s, " + 'name: "%(name)s", size: %(size)d, elements: %(elements)d' % img_prefix + ) - target_size = img_prefix['size'] + target_size = img_prefix["size"] target_data, data = data[:target_size], data[target_size:] - for elem_idx in range(img_prefix['elements']): + for elem_idx in range(img_prefix["elements"]): # Decode target prefix # < little endian # I uint32_t element address # I uint32_t element size - elem_prefix, target_data = consume('<2I', target_data, 'addr size') - elem_prefix['num'] = elem_idx - print(' %(num)d, address: 0x%(addr)08x, size: %(size)d' - % elem_prefix) - elem_size = elem_prefix['size'] + elem_prefix, target_data = consume("<2I", target_data, "addr size") + elem_prefix["num"] = elem_idx + print(" %(num)d, address: 0x%(addr)08x, size: %(size)d" % elem_prefix) + elem_size = elem_prefix["size"] elem_data = target_data[:elem_size] target_data = target_data[elem_size:] - elem_prefix['data'] = elem_data + elem_prefix["data"] = elem_data elements.append(elem_prefix) if len(target_data): @@ -345,11 +346,14 @@ def read_dfu_file(filename): # 3s char[3] ufd 'UFD' # B uint8_t len 16 # I uint32_t crc32 - dfu_suffix = named(struct.unpack('<4H3sBI', data[:16]), - 'device product vendor dfu ufd len crc') - print (' usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, ' - 'dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x' % dfu_suffix) - if crc != dfu_suffix['crc']: + dfu_suffix = named( + struct.unpack("<4H3sBI", data[:16]), "device product vendor dfu ufd len crc" + ) + print( + " usb: %(vendor)04x:%(product)04x, device: 0x%(device)04x, " + "dfu: 0x%(dfu)04x, %(ufd)s, %(len)d, 0x%(crc)08x" % dfu_suffix + ) + if crc != dfu_suffix["crc"]: print("CRC ERROR: computed crc32 is 0x%08x" % crc) return data = data[16:] @@ -368,8 +372,7 @@ class FilterDFU(object): def __call__(self, device): for cfg in device: for intf in cfg: - return (intf.bInterfaceClass == 0xFE and - intf.bInterfaceSubClass == 1) + return intf.bInterfaceClass == 0xFE and intf.bInterfaceSubClass == 1 def get_dfu_devices(*args, **kwargs): @@ -378,8 +381,7 @@ def get_dfu_devices(*args, **kwargs): refine the search. """ # convert to list for compatibility with newer pyusb - return list(usb.core.find(*args, find_all=True, - custom_match=FilterDFU(), **kwargs)) + return list(usb.core.find(*args, find_all=True, custom_match=FilterDFU(), **kwargs)) def get_memory_layout(device): @@ -394,25 +396,29 @@ def get_memory_layout(device): cfg = device[0] intf = cfg[(0, 0)] mem_layout_str = get_string(device, intf.iInterface) - mem_layout = mem_layout_str.split('/') + mem_layout = mem_layout_str.split("/") result = [] for mem_layout_index in range(1, len(mem_layout), 2): addr = int(mem_layout[mem_layout_index], 0) - segments = mem_layout[mem_layout_index + 1].split(',') - seg_re = re.compile(r'(\d+)\*(\d+)(.)(.)') + segments = mem_layout[mem_layout_index + 1].split(",") + seg_re = re.compile(r"(\d+)\*(\d+)(.)(.)") for segment in segments: seg_match = seg_re.match(segment) num_pages = int(seg_match.groups()[0], 10) page_size = int(seg_match.groups()[1], 10) multiplier = seg_match.groups()[2] - if multiplier == 'K': + if multiplier == "K": page_size *= 1024 - if multiplier == 'M': + if multiplier == "M": page_size *= 1024 * 1024 size = num_pages * page_size last_addr = addr + size - 1 - result.append(named((addr, last_addr, size, num_pages, page_size), - "addr last_addr size num_pages page_size")) + result.append( + named( + (addr, last_addr, size, num_pages, page_size), + "addr last_addr size num_pages page_size", + ) + ) addr += size return result @@ -424,15 +430,19 @@ def list_dfu_devices(*args, **kwargs): print("No DFU capable devices found") return for device in devices: - print("Bus {} Device {:03d}: ID {:04x}:{:04x}" - .format(device.bus, device.address, - device.idVendor, device.idProduct)) + print( + "Bus {} Device {:03d}: ID {:04x}:{:04x}".format( + device.bus, device.address, device.idVendor, device.idProduct + ) + ) layout = get_memory_layout(device) print("Memory Layout") for entry in layout: - print(" 0x{:x} {:2d} pages of {:3d}K bytes" - .format(entry['addr'], entry['num_pages'], - entry['page_size'] // 1024)) + print( + " 0x{:x} {:2d} pages of {:3d}K bytes".format( + entry["addr"], entry["num_pages"], entry["page_size"] // 1024 + ) + ) def write_elements(elements, mass_erase_used, progress=None): @@ -442,9 +452,9 @@ def write_elements(elements, mass_erase_used, progress=None): mem_layout = get_memory_layout(__dev) for elem in elements: - addr = elem['addr'] - size = elem['size'] - data = elem['data'] + addr = elem["addr"] + size = elem["size"] + data = elem["data"] elem_size = size elem_addr = addr if progress: @@ -453,18 +463,16 @@ def write_elements(elements, mass_erase_used, progress=None): write_size = size if not mass_erase_used: for segment in mem_layout: - if addr >= segment['addr'] and \ - addr <= segment['last_addr']: + if addr >= segment["addr"] and addr <= segment["last_addr"]: # We found the page containing the address we want to # write, erase it - page_size = segment['page_size'] + page_size = segment["page_size"] page_addr = addr & ~(page_size - 1) if addr + write_size > page_addr + page_size: write_size = page_addr + page_size - addr page_erase(page_addr) break - write_memory(addr, data[:write_size], progress, - elem_addr, elem_size) + write_memory(addr, data[:write_size], progress, elem_addr, elem_size) data = data[write_size:] addr += write_size size -= write_size @@ -476,9 +484,12 @@ def cli_progress(addr, offset, size): """Prints a progress report suitable for use on the command line.""" width = 25 done = offset * width // size - print("\r0x{:08x} {:7d} [{}{}] {:3d}% " - .format(addr, size, '=' * done, ' ' * (width - done), - offset * 100 // size), end="") + print( + "\r0x{:08x} {:7d} [{}{}] {:3d}% ".format( + addr, size, "=" * done, " " * (width - done), offset * 100 // size + ), + end="", + ) sys.stdout.flush() if offset == size: print("") @@ -488,31 +499,19 @@ def main(): """Test program for verifying this files functionality.""" global __verbose # Parse CMD args - parser = argparse.ArgumentParser(description='DFU Python Util') - #parser.add_argument("path", help="file path") + parser = argparse.ArgumentParser(description="DFU Python Util") + # parser.add_argument("path", help="file path") parser.add_argument( - "-l", "--list", - help="list available DFU devices", - action="store_true", - default=False + "-l", "--list", help="list available DFU devices", action="store_true", default=False ) parser.add_argument( - "-m", "--mass-erase", - help="mass erase device", - action="store_true", - default=False + "-m", "--mass-erase", help="mass erase device", action="store_true", default=False ) parser.add_argument( - "-u", "--upload", - help="read file from DFU device", - dest="path", - default=False + "-u", "--upload", help="read file from DFU device", dest="path", default=False ) parser.add_argument( - "-v", "--verbose", - help="increase output verbosity", - action="store_true", - default=False + "-v", "--verbose", help="increase output verbosity", action="store_true", default=False ) args = parser.parse_args() @@ -525,7 +524,7 @@ def main(): init() if args.mass_erase: - print ("Mass erase...") + print("Mass erase...") mass_erase() if args.path: @@ -541,5 +540,6 @@ def main(): print("No command specified") -if __name__ == '__main__': + +if __name__ == "__main__": main() diff --git a/tools/tinytest-codegen.py b/tools/tinytest-codegen.py index 74b1878f95..0e7d2ee608 100755 --- a/tools/tinytest-codegen.py +++ b/tools/tinytest-codegen.py @@ -12,18 +12,13 @@ import argparse def escape(s): s = s.decode() - lookup = { - '\0': '\\0', - '\t': '\\t', - '\n': '\\n\"\n\"', - '\r': '\\r', - '\\': '\\\\', - '\"': '\\\"', - } - return "\"\"\n\"{}\"".format(''.join([lookup[x] if x in lookup else x for x in s])) + lookup = {"\0": "\\0", "\t": "\\t", "\n": '\\n"\n"', "\r": "\\r", "\\": "\\\\", '"': '\\"'} + return '""\n"{}"'.format("".join([lookup[x] if x in lookup else x for x in s])) + def chew_filename(t): - return { 'func': "test_{}_fn".format(sub(r'/|\.|-', '_', t)), 'desc': t } + return {"func": "test_{}_fn".format(sub(r"/|\.|-", "_", t)), "desc": t} + def script_to_map(test_file): r = {"name": chew_filename(test_file)["func"]} @@ -32,24 +27,25 @@ def script_to_map(test_file): # Test for import skip_if and inject it into the test as needed. if "import skip_if\n" in script: - index = script.index("import skip_if\n") - script.pop(index) - script.insert(index, "class skip_if:\n") - with open("../tests/skip_if.py") as skip_if: - total_lines = 1 - for line in skip_if: - stripped = line.strip() - if not stripped or stripped.startswith(("#", "\"\"\"")): - continue - script.insert(index + total_lines, "\t" + line) - total_lines += 1 - r['script'] = escape(b''.join(script)) + index = script.index("import skip_if\n") + script.pop(index) + script.insert(index, "class skip_if:\n") + with open("../tests/skip_if.py") as skip_if: + total_lines = 1 + for line in skip_if: + stripped = line.strip() + if not stripped or stripped.startswith(("#", '"""')): + continue + script.insert(index + total_lines, "\t" + line) + total_lines += 1 + r["script"] = escape(b"".join(script)) with open(test_file + ".exp", "rb") as f: r["output"] = escape(f.read()) return r + test_function = ( "void {name}(void* data) {{\n" " static const char pystr[] = {script};\n" @@ -59,73 +55,72 @@ test_function = ( "}}" ) -testcase_struct = ( - "struct testcase_t {name}_tests[] = {{\n{body}\n END_OF_TESTCASES\n}};" -) -testcase_member = ( - " {{ \"{desc}\", {func}, TT_ENABLED_, 0, 0 }}," -) +testcase_struct = "struct testcase_t {name}_tests[] = {{\n{body}\n END_OF_TESTCASES\n}};" +testcase_member = ' {{ "{desc}", {func}, TT_ENABLED_, 0, 0 }},' -testgroup_struct = ( - "struct testgroup_t groups[] = {{\n{body}\n END_OF_GROUPS\n}};" -) -testgroup_member = ( - " {{ \"{name}\", {name}_tests }}," -) +testgroup_struct = "struct testgroup_t groups[] = {{\n{body}\n END_OF_GROUPS\n}};" +testgroup_member = ' {{ "{name}", {name}_tests }},' ## XXX: may be we could have `--without ` argument... # currently these tests are selected because they pass on qemu-arm -test_dirs = ('basics', 'micropython', 'float', 'extmod', 'inlineasm') # 'import', 'io', 'misc') +test_dirs = ("basics", "micropython", "float", "extmod", "inlineasm") # 'import', 'io', 'misc') exclude_tests = ( # pattern matching in .exp - 'basics/bytes_compare3.py', - 'extmod/ticks_diff.py', - 'extmod/time_ms_us.py', - 'extmod/uheapq_timeq.py', + "basics/bytes_compare3.py", + "extmod/ticks_diff.py", + "extmod/time_ms_us.py", + "extmod/uheapq_timeq.py", # unicode char issue - 'extmod/ujson_loads.py', + "extmod/ujson_loads.py", # doesn't output to python stdout - 'extmod/ure_debug.py', - 'extmod/vfs_basic.py', - 'extmod/vfs_fat_ramdisk.py', 'extmod/vfs_fat_fileio.py', - 'extmod/vfs_fat_fsusermount.py', 'extmod/vfs_fat_oldproto.py', + "extmod/ure_debug.py", + "extmod/vfs_basic.py", + "extmod/vfs_fat_ramdisk.py", + "extmod/vfs_fat_fileio.py", + "extmod/vfs_fat_fsusermount.py", + "extmod/vfs_fat_oldproto.py", # rounding issues - 'float/float_divmod.py', + "float/float_divmod.py", # requires double precision floating point to work - 'float/float2int_doubleprec_intbig.py', - 'float/float_parse_doubleprec.py', + "float/float2int_doubleprec_intbig.py", + "float/float_parse_doubleprec.py", # inline asm FP tests (require Cortex-M4) - 'inlineasm/asmfpaddsub.py', 'inlineasm/asmfpcmp.py', 'inlineasm/asmfpldrstr.py', - 'inlineasm/asmfpmuldiv.py','inlineasm/asmfpsqrt.py', + "inlineasm/asmfpaddsub.py", + "inlineasm/asmfpcmp.py", + "inlineasm/asmfpldrstr.py", + "inlineasm/asmfpmuldiv.py", + "inlineasm/asmfpsqrt.py", # different filename in output - 'micropython/emg_exc.py', - 'micropython/heapalloc_traceback.py', + "micropython/emg_exc.py", + "micropython/heapalloc_traceback.py", # pattern matching in .exp - 'micropython/meminfo.py', + "micropython/meminfo.py", ) output = [] tests = [] -argparser = argparse.ArgumentParser(description='Convert native MicroPython tests to tinytest/upytesthelper C code') -argparser.add_argument('--stdin', action="store_true", help='read list of tests from stdin') +argparser = argparse.ArgumentParser( + description="Convert native MicroPython tests to tinytest/upytesthelper C code" +) +argparser.add_argument("--stdin", action="store_true", help="read list of tests from stdin") args = argparser.parse_args() if not args.stdin: for group in test_dirs: - tests += [test for test in glob('{}/*.py'.format(group)) if test not in exclude_tests] + tests += [test for test in glob("{}/*.py".format(group)) if test not in exclude_tests] else: for l in sys.stdin: tests.append(l.rstrip()) output.extend([test_function.format(**script_to_map(test)) for test in tests]) testcase_members = [testcase_member.format(**chew_filename(test)) for test in tests] -output.append(testcase_struct.format(name="", body='\n'.join(testcase_members))) +output.append(testcase_struct.format(name="", body="\n".join(testcase_members))) testgroup_members = [testgroup_member.format(name=group) for group in [""]] -output.append(testgroup_struct.format(body='\n'.join(testgroup_members))) +output.append(testgroup_struct.format(body="\n".join(testgroup_members))) ## XXX: may be we could have `--output ` argument... # Don't depend on what system locale is set, use utf8 encoding. -sys.stdout.buffer.write('\n\n'.join(output).encode('utf8')) +sys.stdout.buffer.write("\n\n".join(output).encode("utf8")) diff --git a/tools/upip.py b/tools/upip.py index 27fbae272f..a7187e700d 100644 --- a/tools/upip.py +++ b/tools/upip.py @@ -12,6 +12,7 @@ import uerrno as errno import ujson as json import uzlib import upip_utarfile as tarfile + gc.collect() @@ -22,9 +23,11 @@ gzdict_sz = 16 + 15 file_buf = bytearray(512) + class NotFoundError(Exception): pass + def op_split(path): if path == "": return ("", "") @@ -36,9 +39,11 @@ def op_split(path): head = "/" return (head, r[1]) + def op_basename(path): return op_split(path)[1] + # Expects *file* name def _makedirs(name, mode=0o777): ret = False @@ -69,26 +74,27 @@ def save_file(fname, subf): break outf.write(file_buf, sz) + def install_tar(f, prefix): meta = {} for info in f: - #print(info) + # print(info) fname = info.name try: - fname = fname[fname.index("/") + 1:] + fname = fname[fname.index("/") + 1 :] except ValueError: fname = "" save = True for p in ("setup.", "PKG-INFO", "README"): - #print(fname, p) - if fname.startswith(p) or ".egg-info" in fname: - if fname.endswith("/requires.txt"): - meta["deps"] = f.extractfile(info).read() - save = False - if debug: - print("Skipping", fname) - break + # print(fname, p) + if fname.startswith(p) or ".egg-info" in fname: + if fname.endswith("/requires.txt"): + meta["deps"] = f.extractfile(info).read() + save = False + if debug: + print("Skipping", fname) + break if save: outfname = prefix + fname @@ -100,32 +106,37 @@ def install_tar(f, prefix): save_file(outfname, subf) return meta + def expandhome(s): if "~/" in s: h = os.getenv("HOME") s = s.replace("~/", h + "/") return s + import ussl import usocket + warn_ussl = True + + def url_open(url): global warn_ussl if debug: print(url) - proto, _, host, urlpath = url.split('/', 3) + proto, _, host, urlpath = url.split("/", 3) try: ai = usocket.getaddrinfo(host, 443, 0, usocket.SOCK_STREAM) except OSError as e: fatal("Unable to resolve %s (no Internet?)" % host, e) - #print("Address infos:", ai) + # print("Address infos:", ai) ai = ai[0] s = usocket.socket(ai[0], ai[1], ai[2]) try: - #print("Connect address:", addr) + # print("Connect address:", addr) s.connect(ai[-1]) if proto == "https:": @@ -146,7 +157,7 @@ def url_open(url): l = s.readline() if not l: raise ValueError("Unexpected EOF in HTTP headers") - if l == b'\r\n': + if l == b"\r\n": break except Exception as e: s.close() @@ -169,6 +180,7 @@ def fatal(msg, exc=None): raise exc sys.exit(1) + def install_pkg(pkg_spec, install_path): data = get_pkg_metadata(pkg_spec) @@ -192,6 +204,7 @@ def install_pkg(pkg_spec, install_path): gc.collect() return meta + def install(to_install, install_path=None): # Calculate gzip dictionary size to use global gzdict_sz @@ -224,9 +237,11 @@ def install(to_install, install_path=None): deps = deps.decode("utf-8").split("\n") to_install.extend(deps) except Exception as e: - print("Error installing '{}': {}, packages may be partially installed".format( - pkg_spec, e), - file=sys.stderr) + print( + "Error installing '{}': {}, packages may be partially installed".format(pkg_spec, e), + file=sys.stderr, + ) + def get_install_path(): global install_path @@ -236,6 +251,7 @@ def get_install_path(): install_path = expandhome(install_path) return install_path + def cleanup(): for fname in cleanup_files: try: @@ -243,21 +259,27 @@ def cleanup(): except OSError: print("Warning: Cannot delete " + fname) + def help(): - print("""\ + print( + """\ upip - Simple PyPI package manager for MicroPython Usage: micropython -m upip install [-p ] ... | -r import upip; upip.install(package_or_list, []) If is not given, packages will be installed into sys.path[1] (can be set from MICROPYPATH environment variable, if current system -supports that).""") +supports that).""" + ) print("Current value of sys.path[1]:", sys.path[1]) - print("""\ + print( + """\ Note: only MicroPython packages (usually, named micropython-*) are supported for installation, upip does not support arbitrary code in setup.py. -""") +""" + ) + def main(): global debug diff --git a/tools/upip_utarfile.py b/tools/upip_utarfile.py index 44d6364524..3e527fad8d 100644 --- a/tools/upip_utarfile.py +++ b/tools/upip_utarfile.py @@ -13,11 +13,12 @@ TAR_HEADER = { DIRTYPE = "dir" REGTYPE = "file" + def roundup(val, align): return (val + align - 1) & ~(align - 1) -class FileSection: +class FileSection: def __init__(self, f, content_len, aligned_len): self.f = f self.content_len = content_len @@ -37,7 +38,7 @@ class FileSection: if self.content_len == 0: return 0 if len(buf) > self.content_len: - buf = memoryview(buf)[:self.content_len] + buf = memoryview(buf)[: self.content_len] sz = self.f.readinto(buf) self.content_len -= sz return sz @@ -51,13 +52,13 @@ class FileSection: self.f.readinto(buf, s) sz -= s -class TarInfo: +class TarInfo: def __str__(self): return "TarInfo(%r, %s, %d)" % (self.name, self.type, self.size) -class TarFile: +class TarFile: def __init__(self, name=None, fileobj=None): if fileobj: self.f = fileobj @@ -66,24 +67,24 @@ class TarFile: self.subf = None def next(self): - if self.subf: - self.subf.skip() - buf = self.f.read(512) - if not buf: - return None + if self.subf: + self.subf.skip() + buf = self.f.read(512) + if not buf: + return None - h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) + h = uctypes.struct(uctypes.addressof(buf), TAR_HEADER, uctypes.LITTLE_ENDIAN) - # Empty block means end of archive - if h.name[0] == 0: - return None + # Empty block means end of archive + if h.name[0] == 0: + return None - d = TarInfo() - d.name = str(h.name, "utf-8").rstrip("\0") - d.size = int(bytes(h.size), 8) - d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] - self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) - return d + d = TarInfo() + d.name = str(h.name, "utf-8").rstrip("\0") + d.size = int(bytes(h.size), 8) + d.type = [REGTYPE, DIRTYPE][d.name[-1] == "/"] + self.subf = d.subf = FileSection(self.f, d.size, roundup(d.size, 512)) + return d def __iter__(self): return self